elastic.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. package services
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/olivere/elastic/v7"
  7. "hongze/hongze_cygx/models"
  8. "hongze/hongze_cygx/utils"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. )
  13. func NewClient() (client *elastic.Client, err error) {
  14. //errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
  15. //file := ""
  16. //if utils.RunMode == "release" {
  17. // //file = `/data/rdlucklog/hongze_cygx/eslog.log`
  18. // file = `./rdlucklog/eslog.log`
  19. //} else {
  20. // file = `./rdlucklog/eslog.log`
  21. //}
  22. //logFile, _ := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
  23. //client, err = elastic.NewClient(
  24. // elastic.SetURL(ES_URL),
  25. // elastic.SetBasicAuth(ES_USERNAME, ES_PASSWORD),
  26. // elastic.SetTraceLog(log.New(logFile, "ES-TRACE: ", 0)),
  27. // elastic.SetSniff(false), elastic.SetErrorLog(errorlog))
  28. client, err = elastic.NewClient(
  29. elastic.SetURL(ES_URL),
  30. elastic.SetBasicAuth(ES_USERNAME, ES_PASSWORD),
  31. elastic.SetSniff(false))
  32. return
  33. }
  34. //indexName:索引名称
  35. //mappingJson:表结构
  36. func EsCreateIndex(indexName, mappingJson string) (err error) {
  37. client, err := NewClient()
  38. if err != nil {
  39. return
  40. }
  41. //定义表结构
  42. exists, err := client.IndexExists(indexName).Do(context.Background()) //<5>
  43. if err != nil {
  44. return
  45. }
  46. if !exists {
  47. resp, err := client.CreateIndex(indexName).BodyJson(mappingJson).Do(context.Background())
  48. //BodyJson(bodyJson).Do(context.Background())
  49. if err != nil {
  50. fmt.Println("CreateIndex Err:" + err.Error())
  51. return err
  52. }
  53. fmt.Println(resp.Index, resp.ShardsAcknowledged, resp.Acknowledged)
  54. } else {
  55. fmt.Println(indexName + " 已存在")
  56. }
  57. return
  58. }
  59. //新增和修改数据
  60. func EsAddOrEditData(indexName, docId string, item *ElasticTestArticleDetail) (err error) {
  61. defer func() {
  62. if err != nil {
  63. fmt.Println("EsAddOrEditData Err:", err.Error())
  64. }
  65. }()
  66. client, err := NewClient()
  67. if err != nil {
  68. return
  69. }
  70. searchById, err := client.Get().Index(indexName).Id(docId).Do(context.Background())
  71. if err != nil && !strings.Contains(err.Error(), "404") {
  72. fmt.Println("Get Err" + err.Error())
  73. return
  74. }
  75. if searchById != nil && searchById.Found {
  76. resp, err := client.Update().Index(indexName).Id(docId).Doc(map[string]interface{}{
  77. "BodyText": item.BodyText,
  78. "Title": item.Title,
  79. "PublishDate": item.PublishDate,
  80. }).Do(context.Background())
  81. if err != nil {
  82. return err
  83. }
  84. fmt.Println(resp.Status, resp.Result)
  85. if resp.Status == 0 {
  86. fmt.Println("修改成功")
  87. } else {
  88. fmt.Println("EditData", resp.Status, resp.Result)
  89. }
  90. client.CloseIndex(indexName)
  91. } else {
  92. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
  93. if err != nil {
  94. fmt.Println("新增失败:", err.Error())
  95. return err
  96. }
  97. if resp.Status == 0 && resp.Result == "created" {
  98. fmt.Println("新增成功")
  99. err = nil
  100. } else {
  101. fmt.Println("AddData", resp.Status, resp.Result)
  102. }
  103. }
  104. return
  105. }
  106. //新增和修改数据
  107. func EsAddOrEditDataV4(indexName, docId string, item *ElasticTestArticleDetailV4) (err error) {
  108. defer func() {
  109. if err != nil {
  110. fmt.Println("EsAddOrEditData Err:", err.Error())
  111. }
  112. }()
  113. client, err := NewClient()
  114. if err != nil {
  115. return
  116. }
  117. searchById, err := client.Get().Index(indexName).Id(docId).Do(context.Background())
  118. if err != nil && !strings.Contains(err.Error(), "404") {
  119. fmt.Println("Get Err" + err.Error())
  120. return
  121. }
  122. if searchById != nil && searchById.Found {
  123. resp, err := client.Update().Index(indexName).Id(docId).Doc(map[string]interface{}{
  124. "BodyText": item.BodyText,
  125. "Title": item.Title,
  126. "PublishDate": item.PublishDate,
  127. "IsSummary": item.IsSummary,
  128. "IsReport": item.IsReport,
  129. }).Do(context.Background())
  130. if err != nil {
  131. return err
  132. }
  133. fmt.Println(resp.Status, resp.Result)
  134. if resp.Status == 0 {
  135. fmt.Println("修改成功")
  136. } else {
  137. fmt.Println("EditData", resp.Status, resp.Result)
  138. }
  139. } else {
  140. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
  141. if err != nil {
  142. fmt.Println("新增失败:", err.Error())
  143. return err
  144. }
  145. if resp.Status == 0 && resp.Result == "created" {
  146. fmt.Println("新增成功")
  147. err = nil
  148. } else {
  149. fmt.Println("AddData", resp.Status, resp.Result)
  150. }
  151. }
  152. return
  153. }
  154. //删除数据
  155. func EsDeleteData(indexName, docId string) (err error) {
  156. client, err := NewClient()
  157. if err != nil {
  158. return
  159. }
  160. resp, err := client.Delete().Index(indexName).Id(docId).Do(context.Background())
  161. if err != nil {
  162. return
  163. }
  164. if resp.Status == 0 {
  165. fmt.Println("删除成功")
  166. } else {
  167. fmt.Println("AddData", resp.Status, resp.Result)
  168. }
  169. return
  170. }
  171. func MappingModify(indexName, mappingJson string) {
  172. client, err := NewClient()
  173. if err != nil {
  174. return
  175. }
  176. result, err := client.PutMapping().Index(indexName).BodyString(mappingJson).Do(context.Background())
  177. fmt.Println(err)
  178. fmt.Println(result)
  179. return
  180. }
  181. func EsMatchQuery(indexName, keyWord string) (result []*models.SearchItem, err error) {
  182. client, err := NewClient()
  183. pageSize := 20
  184. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  185. fmt.Println(keyWordArr)
  186. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  187. fmt.Println("-------------------------------")
  188. fmt.Println(keyWordArr)
  189. searchMap := make(map[int]int)
  190. boolquery := elastic.NewBoolQuery()
  191. keyLen := len(keyWordArr)
  192. n := 5.0 * float64(keyLen)
  193. matchArr := make([]elastic.Query, 0)
  194. //
  195. //matchq1 := elastic.NewMatchQuery("Title", keyWord).Boost(n + 1).Analyzer("ik_smart")
  196. //matchq2 := elastic.NewMatchQuery("BodyText", keyWord).Boost(n + 1).Analyzer("ik_smart")
  197. //
  198. //matchArr = append(matchArr, matchq1)
  199. //matchArr = append(matchArr, matchq2)
  200. for _, v := range keyWordArr {
  201. if v != "" {
  202. matchq1 := elastic.NewMatchQuery("Title", v).Boost(n).Analyzer("ik_smart")
  203. matchq2 := elastic.NewMatchQuery("BodyText", v).Boost(n).Analyzer("ik_smart")
  204. matchArr = append(matchArr, matchq1)
  205. matchArr = append(matchArr, matchq2)
  206. }
  207. n = n - 5
  208. }
  209. boolquery.Should(matchArr...)
  210. highlight := elastic.NewHighlight()
  211. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  212. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  213. request := client.Search(indexName).Highlight(highlight).Size(pageSize).Query(boolquery)
  214. searchByMatch, err := request.Do(context.Background())
  215. if searchByMatch.Hits != nil {
  216. for _, v := range searchByMatch.Hits.Hits {
  217. articleJson, err := v.Source.MarshalJSON()
  218. if err != nil {
  219. return nil, err
  220. }
  221. article := new(models.CygxArticle)
  222. err = json.Unmarshal(articleJson, &article)
  223. if err != nil {
  224. return nil, err
  225. }
  226. if _, ok := searchMap[article.ArticleId]; !ok {
  227. searchItem := new(models.SearchItem)
  228. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  229. if len(v.Highlight["BodyText"]) > 0 {
  230. searchItem.Body = v.Highlight["BodyText"]
  231. } else {
  232. bodyRune := []rune(article.BodyText)
  233. bodyRuneLen := len(bodyRune)
  234. if bodyRuneLen > 100 {
  235. bodyRuneLen = 100
  236. }
  237. body := string(bodyRune[:bodyRuneLen])
  238. fmt.Println(body)
  239. searchItem.Body = []string{body}
  240. }
  241. var title string
  242. if len(v.Highlight["Title"]) > 0 {
  243. title = v.Highlight["Title"][0]
  244. } else {
  245. title = article.Title
  246. }
  247. searchItem.Title = title
  248. searchItem.PublishDate = article.PublishDate
  249. result = append(result, searchItem)
  250. searchMap[article.ArticleId] = article.ArticleId
  251. }
  252. }
  253. }
  254. return
  255. }
  256. func EsMatchPhraseQuery(indexName, keyWord string) (result []*models.SearchItem, err error) {
  257. client, err := NewClient()
  258. pageSize := 20
  259. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  260. fmt.Println(keyWordArr)
  261. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  262. fmt.Println("-------------------------------")
  263. fmt.Println(keyWordArr)
  264. searchMap := make(map[int]int)
  265. boolquery := elastic.NewBoolQuery()
  266. //keyLen := len(keyWordArr)
  267. //n := float64(keyLen)
  268. matchArr := make([]elastic.Query, 0)
  269. //matchq1 := elastic.NewMatchQuery("Title", keyWord).Boost(n + 1).Analyzer("ik_smart")
  270. //matchq2 := elastic.NewMatchQuery("BodyText", keyWord).Boost(n + 1).Analyzer("ik_smart")
  271. matchq1 := elastic.NewMatchPhraseQuery("Title", keyWord) //.Analyzer("ik_smart")
  272. matchq2 := elastic.NewMatchPhraseQuery("BodyText", keyWord)
  273. matchArr = append(matchArr, matchq1)
  274. matchArr = append(matchArr, matchq2)
  275. //matchArr = append(matchArr, matchq2)
  276. //for _, v := range keyWordArr {
  277. // if v != "" {
  278. // matchq1 := elastic.NewMatchQuery("Title", v).Boost(n).Analyzer("ik_smart")
  279. // matchq2 := elastic.NewMatchQuery("BodyText", v).Boost(n).Analyzer("ik_smart")
  280. // matchArr = append(matchArr, matchq1)
  281. // matchArr = append(matchArr, matchq2)
  282. // }
  283. // n--
  284. //}
  285. //boolquery.Should(matchArr...)
  286. boolquery.Should(matchArr...)
  287. highlight := elastic.NewHighlight()
  288. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  289. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  290. request := client.Search(indexName).Highlight(highlight).Size(pageSize).Query(boolquery)
  291. searchByMatch, err := request.Do(context.Background())
  292. fmt.Println("err:", err, searchByMatch)
  293. return
  294. if searchByMatch.Hits != nil {
  295. for _, v := range searchByMatch.Hits.Hits {
  296. articleJson, err := v.Source.MarshalJSON()
  297. if err != nil {
  298. return nil, err
  299. }
  300. article := new(models.CygxArticle)
  301. err = json.Unmarshal(articleJson, &article)
  302. if err != nil {
  303. return nil, err
  304. }
  305. if _, ok := searchMap[article.ArticleId]; !ok {
  306. searchItem := new(models.SearchItem)
  307. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  308. searchItem.Body = v.Highlight["BodyText"]
  309. var title string
  310. if len(v.Highlight["Title"]) > 0 {
  311. title = v.Highlight["Title"][0]
  312. } else {
  313. title = article.Title
  314. }
  315. searchItem.Title = title
  316. searchItem.PublishDate = article.PublishDate
  317. result = append(result, searchItem)
  318. searchMap[article.ArticleId] = article.ArticleId
  319. }
  320. }
  321. }
  322. return
  323. }
  324. func EsMatchFunctionScoreQuery(indexName, keyWord string, startSize, pageSize int) (result []*models.SearchItem, total int64, err error) {
  325. client, err := NewClient()
  326. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  327. fmt.Println(keyWordArr)
  328. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  329. fmt.Println("-------------------------------")
  330. fmt.Println(keyWordArr)
  331. searchMap := make(map[int]int)
  332. boolquery := elastic.NewBoolQuery()
  333. matchArr := make([]elastic.Query, 0)
  334. //
  335. //matchq1 := elastic.NewMatchQuery("Title", keyWord).Boost(n + 1).Analyzer("ik_smart")
  336. //matchq2 := elastic.NewMatchQuery("BodyText", keyWord).Boost(n + 1).Analyzer("ik_smart")
  337. //
  338. //matchArr = append(matchArr, matchq1)
  339. //matchArr = append(matchArr, matchq2)
  340. n := 0
  341. keyWordLen := len(keyWordArr)
  342. if keyWordLen <= 0 {
  343. keyWordArr = append(keyWordArr, keyWord)
  344. keyWordLen = len(keyWordArr)
  345. }
  346. keyWordWeight := GetWeight(keyWordLen)
  347. fmt.Println(keyWordArr)
  348. fmt.Println(keyWordWeight)
  349. for k, v := range keyWordArr {
  350. if v != "" {
  351. weight := float64(keyWordWeight[k])
  352. titleMatchq := elastic.NewMatchQuery("Title", v).Analyzer("ik_smart")
  353. bodyMatchq := elastic.NewMatchQuery("BodyText", v).Analyzer("ik_smart")
  354. titleFunctionQuery := elastic.NewFunctionScoreQuery()
  355. titleFunctionQuery.Query(titleMatchq)
  356. titleFunctions := elastic.NewWeightFactorFunction(weight)
  357. titleFunctionQuery.AddScoreFunc(titleFunctions)
  358. titleFunctionQuery.BoostMode("replace")
  359. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  360. bodyFunctionQuery.Query(bodyMatchq)
  361. bodyFunctions := elastic.NewWeightFactorFunction(weight)
  362. bodyFunctionQuery.AddScoreFunc(bodyFunctions)
  363. bodyFunctionQuery.BoostMode("replace")
  364. matchArr = append(matchArr, titleFunctionQuery)
  365. matchArr = append(matchArr, bodyFunctionQuery)
  366. }
  367. n++
  368. }
  369. boolquery.Should(matchArr...)
  370. highlight := elastic.NewHighlight()
  371. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  372. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  373. request := client.Search(indexName).Highlight(highlight).From(startSize).Size(pageSize).Query(boolquery)
  374. searchByMatch, err := request.Do(context.Background())
  375. //searchJson, err := json.Marshal(searchByMatch)
  376. if searchByMatch != nil {
  377. if searchByMatch.Hits != nil {
  378. for _, v := range searchByMatch.Hits.Hits {
  379. articleJson, err := v.Source.MarshalJSON()
  380. if err != nil {
  381. return nil, 0, err
  382. }
  383. article := new(models.CygxArticle)
  384. err = json.Unmarshal(articleJson, &article)
  385. if err != nil {
  386. return nil, 0, err
  387. }
  388. if _, ok := searchMap[article.ArticleId]; !ok {
  389. searchItem := new(models.SearchItem)
  390. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  391. if len(v.Highlight["BodyText"]) > 0 {
  392. searchItem.Body = v.Highlight["BodyText"]
  393. } else {
  394. bodyRune := []rune(article.BodyText)
  395. bodyRuneLen := len(bodyRune)
  396. if bodyRuneLen > 100 {
  397. bodyRuneLen = 100
  398. }
  399. body := string(bodyRune[:bodyRuneLen])
  400. fmt.Println(body)
  401. searchItem.Body = []string{body}
  402. }
  403. var title string
  404. if len(v.Highlight["Title"]) > 0 {
  405. title = v.Highlight["Title"][0]
  406. } else {
  407. title = article.Title
  408. }
  409. searchItem.Title = title
  410. searchItem.PublishDate = article.PublishDate
  411. result = append(result, searchItem)
  412. searchMap[article.ArticleId] = article.ArticleId
  413. }
  414. }
  415. }
  416. }
  417. total = searchByMatch.Hits.TotalHits.Value
  418. return
  419. }
  420. func EsMultiMatchFunctionScoreQuery(indexName, keyWord string, startSize, pageSize, userId int) (result []*models.SearchItem, total int64, err error) {
  421. client, err := NewClient()
  422. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  423. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  424. //artidArr := make([]elastic.Query, 0)
  425. //matchArr := make([]elastic.Query, 0)
  426. n := 0
  427. keyWordLen := len(keyWordArr)
  428. if keyWordLen <= 0 {
  429. keyWordArr = append(keyWordArr, keyWord)
  430. keyWordLen = len(keyWordArr)
  431. }
  432. utils.FileLog.Info("SearchKeyWord:%s, userId:%s", keyWordArr, strconv.Itoa(userId))
  433. //keyWordWeight := GetWeight(keyWordLen)
  434. for _, v := range keyWordArr {
  435. if v != "" {
  436. matchArr := make([]elastic.Query, 0)
  437. boolquery := elastic.NewBoolQuery()
  438. //weight := float64(keyWordWeight[k])
  439. //multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText").Analyzer("ik_smart")
  440. //bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  441. //bodyFunctionQuery.Query(multiMatch)
  442. //bodyFunctions := elastic.NewWeightFactorFunction(weight)
  443. //bodyFunctionQuery.AddScoreFunc(bodyFunctions)
  444. //bodyFunctionQuery.BoostMode("replace")
  445. //matchArr = append(matchArr, bodyFunctionQuery)
  446. //weight := float64(keyWordWeight[k])
  447. multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText").Analyzer("ik_smart")
  448. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  449. bodyFunctionQuery.Query(multiMatch)
  450. //bodyFunctions := elastic.NewWeightFactorFunction(weight)
  451. //bodyFunctionQuery.AddScoreFunc(bodyFunctions)
  452. //bodyFunctionQuery.BoostMode("replace")
  453. matchArr = append(matchArr, bodyFunctionQuery)
  454. boolquery.Should(matchArr...)
  455. highlight := elastic.NewHighlight()
  456. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  457. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  458. request := client.Search(indexName).Highlight(highlight).From(startSize).Size(pageSize).Query(boolquery)
  459. searchByMatch, err := request.Do(context.Background())
  460. if err != nil {
  461. return nil, 0, err
  462. }
  463. if searchByMatch != nil {
  464. if searchByMatch.Hits != nil {
  465. for _, v := range searchByMatch.Hits.Hits {
  466. var isAppend bool
  467. articleJson, err := v.Source.MarshalJSON()
  468. if err != nil {
  469. return nil, 0, err
  470. }
  471. article := new(models.CygxArticle)
  472. err = json.Unmarshal(articleJson, &article)
  473. if err != nil {
  474. return nil, 0, err
  475. }
  476. searchItem := new(models.SearchItem)
  477. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  478. if len(v.Highlight["BodyText"]) > 0 {
  479. searchItem.Body = v.Highlight["BodyText"]
  480. } else {
  481. bodyRune := []rune(article.BodyText)
  482. bodyRuneLen := len(bodyRune)
  483. if bodyRuneLen > 100 {
  484. bodyRuneLen = 100
  485. }
  486. body := string(bodyRune[:bodyRuneLen])
  487. searchItem.Body = []string{body}
  488. }
  489. var title string
  490. if len(v.Highlight["Title"]) > 0 {
  491. title = v.Highlight["Title"][0]
  492. } else {
  493. title = article.Title
  494. }
  495. searchItem.Title = title
  496. searchItem.PublishDate = article.PublishDate
  497. for _, v_result := range result {
  498. if v_result.ArticleId == searchItem.ArticleId {
  499. isAppend = true
  500. }
  501. }
  502. if !isAppend {
  503. result = append(result, searchItem)
  504. }
  505. }
  506. }
  507. //total += searchByMatch.Hits.TotalHits.Value
  508. }
  509. }
  510. n++
  511. }
  512. total = int64(len(result))
  513. //fmt.Println(result)
  514. //boolquery.Should(matchArr...)
  515. //highlight := elastic.NewHighlight()
  516. //highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  517. //highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  518. //request := client.Search(indexName).Highlight(highlight).From(startSize).Size(pageSize).Query(boolquery)
  519. //searchByMatch, err := request.Do(context.Background())
  520. //if searchByMatch != nil {
  521. // if searchByMatch.Hits != nil {
  522. // for _, v := range searchByMatch.Hits.Hits {
  523. // articleJson, err := v.Source.MarshalJSON()
  524. // if err != nil {
  525. // return nil, 0, err
  526. // }
  527. // article := new(models.CygxArticle)
  528. // err = json.Unmarshal(articleJson, &article)
  529. // if err != nil {
  530. // return nil, 0, err
  531. // }
  532. // searchItem := new(models.SearchItem)
  533. // searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  534. // if len(v.Highlight["BodyText"]) > 0 {
  535. // searchItem.Body = v.Highlight["BodyText"]
  536. // } else {
  537. // bodyRune := []rune(article.BodyText)
  538. // bodyRuneLen := len(bodyRune)
  539. // if bodyRuneLen > 100 {
  540. // bodyRuneLen = 100
  541. // }
  542. // body := string(bodyRune[:bodyRuneLen])
  543. // searchItem.Body = []string{body}
  544. // }
  545. // var title string
  546. // if len(v.Highlight["Title"]) > 0 {
  547. // title = v.Highlight["Title"][0]
  548. // } else {
  549. // title = article.Title
  550. // }
  551. // searchItem.Title = title
  552. // searchItem.PublishDate = article.PublishDate
  553. //
  554. // result = append(result, searchItem)
  555. // }
  556. // }
  557. // total = searchByMatch.Hits.TotalHits.Value
  558. //}
  559. return
  560. }
  561. func EsMultiMatchFunctionScoreQueryFix(indexName, keyWord string, startSize, pageSize int) (result []*models.SearchItem, total int64, err error) {
  562. client, err := NewClient()
  563. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  564. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  565. boolquery := elastic.NewBoolQuery()
  566. matchArr := make([]elastic.Query, 0)
  567. n := 0
  568. keyWordLen := len(keyWordArr)
  569. if keyWordLen <= 0 {
  570. keyWordArr = append(keyWordArr, keyWord)
  571. keyWordLen = len(keyWordArr)
  572. }
  573. fmt.Println(keyWordArr)
  574. keyWordWeight := GetWeight(keyWordLen)
  575. for k, v := range keyWordArr {
  576. if v != "" {
  577. weight := float64(keyWordWeight[k])
  578. multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText").Analyzer("ik_smart")
  579. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  580. bodyFunctionQuery.Query(multiMatch)
  581. bodyFunctions := elastic.NewWeightFactorFunction(weight)
  582. bodyFunctionQuery.AddScoreFunc(bodyFunctions)
  583. bodyFunctionQuery.BoostMode("replace")
  584. matchArr = append(matchArr, bodyFunctionQuery)
  585. }
  586. n++
  587. }
  588. boolquery.Should(matchArr...)
  589. highlight := elastic.NewHighlight()
  590. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  591. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  592. request := client.Search(indexName).Highlight(highlight).From(startSize).Size(pageSize).Query(boolquery)
  593. searchByMatch, err := request.Do(context.Background())
  594. if searchByMatch != nil {
  595. matchResult, _ := json.Marshal(searchByMatch)
  596. utils.FileLog.Info("%s", string(matchResult))
  597. if searchByMatch.Hits != nil {
  598. for _, v := range searchByMatch.Hits.Hits {
  599. articleJson, err := v.Source.MarshalJSON()
  600. utils.FileLog.Info("%s", string(articleJson))
  601. if err != nil {
  602. return nil, 0, err
  603. }
  604. article := new(models.CygxArticle)
  605. err = json.Unmarshal(articleJson, &article)
  606. if err != nil {
  607. return nil, 0, err
  608. }
  609. searchItem := new(models.SearchItem)
  610. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  611. if len(v.Highlight["BodyText"]) > 0 {
  612. searchItem.Body = v.Highlight["BodyText"]
  613. } else {
  614. bodyRune := []rune(article.BodyText)
  615. bodyRuneLen := len(bodyRune)
  616. if bodyRuneLen > 100 {
  617. bodyRuneLen = 100
  618. }
  619. body := string(bodyRune[:bodyRuneLen])
  620. searchItem.Body = []string{body}
  621. }
  622. var title string
  623. if len(v.Highlight["Title"]) > 0 {
  624. title = v.Highlight["Title"][0]
  625. } else {
  626. title = article.Title
  627. }
  628. searchItem.Title = title
  629. searchItem.PublishDate = article.PublishDate
  630. result = append(result, searchItem)
  631. }
  632. }
  633. total = searchByMatch.Hits.TotalHits.Value
  634. }
  635. return
  636. }
  637. func GetWeight(length int) []int {
  638. steep := 10
  639. intArr := make([]int, 0)
  640. for i := 1; i <= length; i++ {
  641. if i == 1 {
  642. intArr = append(intArr, 1)
  643. } else {
  644. min := GetArrSum(intArr)
  645. maxVal := utils.GetRandInt(min, min+steep)
  646. intArr = append(intArr, maxVal)
  647. }
  648. }
  649. //数组排序
  650. sort.Slice(intArr, func(i, j int) bool {
  651. return intArr[i] > intArr[j]
  652. })
  653. return intArr
  654. }
  655. func GetArrSum(intArr []int) (sum int) {
  656. for _, val := range intArr {
  657. //累计求和
  658. sum += val
  659. }
  660. return
  661. }
  662. //func init() {
  663. // fmt.Println("start")
  664. // keyWord:="阿里巴巴"
  665. // keyWordArr, _ := GetIndustryMapNameSliceV2(keyWord)
  666. // keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  667. // fmt.Println(keyWordArr)
  668. // fmt.Println("end")
  669. //}
  670. func EsMultiMatchFunctionScoreQuerySort(indexName, keyWord string, startSize, pageSize, userId int, orderColumn string) (result []*models.SearchItem, total int64, err error) {
  671. client, err := NewClient()
  672. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  673. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  674. //artidArr := make([]elastic.Query, 0)
  675. //matchArr := make([]elastic.Query, 0)
  676. n := 0
  677. keyWordLen := len(keyWordArr)
  678. if keyWordLen <= 0 {
  679. keyWordArr = append(keyWordArr, keyWord)
  680. keyWordLen = len(keyWordArr)
  681. }
  682. for _, v := range keyWordArr {
  683. fmt.Println(v)
  684. }
  685. // @Param OrderColumn query int true "排序字段 ,Comprehensive综合 ,Matching匹配度 ,PublishDate 发布时间 "
  686. utils.FileLog.Info("SearchKeyWord:%s, userId:%s", keyWordArr, strconv.Itoa(userId))
  687. //keyWordWeight := GetWeight(keyWordLen)
  688. for _, v := range keyWordArr {
  689. if v != "" {
  690. matchArr := make([]elastic.Query, 0)
  691. boolquery := elastic.NewBoolQuery()
  692. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  693. bodyFunctionQuery2 := elastic.NewFunctionScoreQuery()
  694. bodyFunctionQuery3 := elastic.NewFunctionScoreQuery()
  695. //multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText").Analyzer("ik_smart")
  696. multiMatch := elastic.NewMultiMatchQuery(v, "Title").Analyzer("ik_smart").Boost(100)
  697. bodyFunctionQuery.Query(multiMatch)
  698. matchArr = append(matchArr, bodyFunctionQuery)
  699. multiMatch = elastic.NewMultiMatchQuery(v, "BodyText").Analyzer("ik_smart").Boost(1)
  700. bodyFunctionQuery2.Query(multiMatch)
  701. matchArr = append(matchArr, bodyFunctionQuery2)
  702. //multiMatch = elastic.NewMultiMatchQuery(1, "IsSummary")
  703. bodyFunctionQuery3.Query(multiMatch)
  704. matchArr = append(matchArr, bodyFunctionQuery3)
  705. boolquery.Should(matchArr...)
  706. //multiMatch = elastic.NewMultiMatchQuery(v, "BodyText").Analyzer("ik_smart")
  707. //bodyFunctionQuery.Query(multiMatch)
  708. //matchArr = append(matchArr, bodyFunctionQuery)
  709. //boolquery.Should(matchArr...)
  710. highlight := elastic.NewHighlight()
  711. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  712. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  713. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).From(0).Size(pageSize).Query(boolquery)
  714. if orderColumn == "Matching" {
  715. request = client.Search(indexName).Highlight(highlight).From(0).Size(pageSize).Query(boolquery)
  716. }
  717. searchByMatch, err := request.Do(context.Background())
  718. if err != nil {
  719. return nil, 0, err
  720. }
  721. if searchByMatch != nil {
  722. if searchByMatch.Hits != nil {
  723. for _, v := range searchByMatch.Hits.Hits {
  724. var isAppend bool
  725. articleJson, err := v.Source.MarshalJSON()
  726. if err != nil {
  727. return nil, 0, err
  728. }
  729. article := new(models.CygxArticle)
  730. err = json.Unmarshal(articleJson, &article)
  731. if err != nil {
  732. return nil, 0, err
  733. }
  734. searchItem := new(models.SearchItem)
  735. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  736. if len(v.Highlight["BodyText"]) > 0 {
  737. searchItem.Body = v.Highlight["BodyText"]
  738. } else {
  739. bodyRune := []rune(article.BodyText)
  740. bodyRuneLen := len(bodyRune)
  741. if bodyRuneLen > 100 {
  742. bodyRuneLen = 100
  743. }
  744. body := string(bodyRune[:bodyRuneLen])
  745. searchItem.Body = []string{body}
  746. }
  747. var title string
  748. if len(v.Highlight["Title"]) > 0 {
  749. title = v.Highlight["Title"][0]
  750. } else {
  751. title = article.Title
  752. }
  753. searchItem.Title = title
  754. searchItem.PublishDate = article.PublishDate
  755. for _, v_result := range result {
  756. if v_result.ArticleId == searchItem.ArticleId {
  757. isAppend = true
  758. }
  759. }
  760. if !isAppend {
  761. result = append(result, searchItem)
  762. }
  763. }
  764. }
  765. //total += searchByMatch.Hits.TotalHits.Value
  766. }
  767. }
  768. n++
  769. }
  770. total = int64(len(result))
  771. return
  772. }
  773. func EsMultiMatchFunctionScoreQueryTimeSort(indexName, keyWord string, startSize, pageSize, userId int) (result []*models.SearchItem, total int64, err error) {
  774. client, err := NewClient()
  775. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  776. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  777. boolquery := elastic.NewBoolQuery()
  778. matchArr := make([]elastic.Query, 0)
  779. //matchArr2 := make([]elastic.Query, 0)
  780. n := 0
  781. keyWordLen := len(keyWordArr)
  782. if keyWordLen <= 0 {
  783. keyWordArr = append(keyWordArr, keyWord)
  784. keyWordLen = len(keyWordArr)
  785. }
  786. fmt.Println(keyWordArr)
  787. utils.FileLog.Info("SearchKeyWord:%s, userId:%s", keyWordArr, strconv.Itoa(userId))
  788. for _, v := range keyWordArr {
  789. if v != "" {
  790. multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText")
  791. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  792. bodyFunctionQuery.Query(multiMatch)
  793. matchArr = append(matchArr, bodyFunctionQuery)
  794. }
  795. n++
  796. }
  797. boolquery.Should(matchArr...)
  798. //multiMatch2 := elastic.NewMultiMatchQuery(1, "IsSummary")
  799. //bodyFunctionQuery2 := elastic.NewFunctionScoreQuery()
  800. //bodyFunctionQuery2.Query(multiMatch2)
  801. //matchArr2 = append(matchArr2, bodyFunctionQuery2)
  802. //boolquery.Must(matchArr2...).Should(matchArr...)
  803. highlight := elastic.NewHighlight()
  804. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  805. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  806. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).Size(pageSize).Query(boolquery)
  807. searchByMatch, err := request.Do(context.Background())
  808. if searchByMatch != nil {
  809. matchResult, _ := json.Marshal(searchByMatch)
  810. utils.FileLog.Info("%s", string(matchResult))
  811. fmt.Println(len(searchByMatch.Hits.Hits))
  812. if searchByMatch.Hits != nil {
  813. for _, v := range searchByMatch.Hits.Hits {
  814. articleJson, err := v.Source.MarshalJSON()
  815. utils.FileLog.Info("%s", string(articleJson))
  816. if err != nil {
  817. return nil, 0, err
  818. }
  819. article := new(models.CygxArticle)
  820. err = json.Unmarshal(articleJson, &article)
  821. if err != nil {
  822. return nil, 0, err
  823. }
  824. searchItem := new(models.SearchItem)
  825. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  826. if len(v.Highlight["BodyText"]) > 0 {
  827. searchItem.Body = v.Highlight["BodyText"]
  828. } else {
  829. bodyRune := []rune(article.BodyText)
  830. bodyRuneLen := len(bodyRune)
  831. if bodyRuneLen > 100 {
  832. bodyRuneLen = 100
  833. }
  834. body := string(bodyRune[:bodyRuneLen])
  835. searchItem.Body = []string{body}
  836. }
  837. var title string
  838. if len(v.Highlight["Title"]) > 0 {
  839. title = v.Highlight["Title"][0]
  840. } else {
  841. title = article.Title
  842. }
  843. searchItem.Title = title
  844. searchItem.PublishDate = article.PublishDate
  845. result = append(result, searchItem)
  846. }
  847. }
  848. total = searchByMatch.Hits.TotalHits.Value
  849. }
  850. return
  851. }
  852. func EsSearchReport(indexName, keyWord string, startSize, pageSize, userId int) (result []*models.SearchItem, total int64, err error) {
  853. client, err := NewClient()
  854. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  855. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  856. n := 0
  857. keyWordLen := len(keyWordArr)
  858. if keyWordLen <= 0 {
  859. keyWordArr = append(keyWordArr, keyWord)
  860. keyWordLen = len(keyWordArr)
  861. }
  862. for _, v := range keyWordArr {
  863. fmt.Println(v)
  864. }
  865. utils.FileLog.Info("SearchKeyWord:%s, userId:%s", keyWordArr, strconv.Itoa(userId))
  866. for _, v := range keyWordArr {
  867. if v != "" {
  868. matchArr := make([]elastic.Query, 0)
  869. boolquery := elastic.NewBoolQuery()
  870. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  871. bodyFunctionQuery2 := elastic.NewFunctionScoreQuery()
  872. multiMatch := elastic.NewMultiMatchQuery(v, "Title").Analyzer("ik_smart")
  873. bodyFunctionQuery.Query(multiMatch)
  874. matchArr = append(matchArr, bodyFunctionQuery)
  875. multiMatch = elastic.NewMultiMatchQuery(1, "IsReport")
  876. bodyFunctionQuery2.Query(multiMatch)
  877. matchArr = append(matchArr, bodyFunctionQuery2)
  878. boolquery.Must(matchArr...)
  879. highlight := elastic.NewHighlight()
  880. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  881. highlight = highlight.Fields(elastic.NewHighlighterField("Title"))
  882. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).From(0).Size(pageSize).Query(boolquery)
  883. searchByMatch, err := request.Do(context.Background())
  884. if err != nil {
  885. return nil, 0, err
  886. }
  887. if searchByMatch != nil {
  888. if searchByMatch.Hits != nil {
  889. for _, v := range searchByMatch.Hits.Hits {
  890. var isAppend bool
  891. articleJson, err := v.Source.MarshalJSON()
  892. if err != nil {
  893. return nil, 0, err
  894. }
  895. article := new(models.CygxArticle)
  896. err = json.Unmarshal(articleJson, &article)
  897. if err != nil {
  898. return nil, 0, err
  899. }
  900. searchItem := new(models.SearchItem)
  901. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  902. var title string
  903. if len(v.Highlight["Title"]) > 0 {
  904. title = v.Highlight["Title"][0]
  905. } else {
  906. title = article.Title
  907. }
  908. searchItem.Title = title
  909. searchItem.PublishDate = article.PublishDate
  910. for _, v_result := range result {
  911. if v_result.ArticleId == searchItem.ArticleId {
  912. isAppend = true
  913. }
  914. }
  915. if !isAppend {
  916. result = append(result, searchItem)
  917. }
  918. }
  919. }
  920. }
  921. }
  922. n++
  923. }
  924. total = int64(len(result))
  925. return
  926. }