elastic.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. package services
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/olivere/elastic/v7"
  7. "hongze/hongze_clpt/models"
  8. "hongze/hongze_clpt/utils"
  9. "strconv"
  10. "strings"
  11. )
  12. //func NewClient() (client *elastic.Client, err error) {
  13. // //errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
  14. // //file := ""
  15. // //if utils.RunMode == "release" {
  16. // // //file = `/data/rdlucklog/hongze_cygx/eslog.log`
  17. // // file = `./rdlucklog/eslog.log`
  18. // //} else {
  19. // // file = `./rdlucklog/eslog.log`
  20. // //}
  21. // //logFile, _ := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
  22. // //client, err = elastic.NewClient(
  23. // // elastic.SetURL(ES_URL),
  24. // // elastic.SetBasicAuth(ES_USERNAME, ES_PASSWORD),
  25. // // elastic.SetTraceLog(log.New(logFile, "ES-TRACE: ", 0)),
  26. // // elastic.SetSniff(false), elastic.SetErrorLog(errorlog))
  27. // client, err = elastic.NewClient(
  28. // elastic.SetURL(ES_URL),
  29. // elastic.SetBasicAuth(ES_USERNAME, ES_PASSWORD),
  30. // elastic.SetSniff(false))
  31. // return
  32. //}
  33. func RemoveDuplicatesAndEmpty(a []string) (ret []string) {
  34. a_len := len(a)
  35. for i := 0; i < a_len; i++ {
  36. if (i > 0 && a[i-1] == a[i]) || len(a[i]) == 0 {
  37. continue
  38. }
  39. ret = append(ret, a[i])
  40. }
  41. return
  42. }
  43. func GetArrSum(intArr []int) (sum int) {
  44. for _, val := range intArr {
  45. //累计求和
  46. sum += val
  47. }
  48. return
  49. }
  50. func EsMultiMatchFunctionScoreQuerySort(indexName, keyWord string, startSize, pageSize, userId int, orderColumn string) (result []*models.SearchItem, total int64, err error) {
  51. client := utils.Client
  52. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  53. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  54. //artidArr := make([]elastic.Query, 0)
  55. //matchArr := make([]elastic.Query, 0)
  56. n := 0
  57. keyWordLen := len(keyWordArr)
  58. if keyWordLen <= 0 {
  59. keyWordArr = append(keyWordArr, keyWord)
  60. keyWordLen = len(keyWordArr)
  61. }
  62. // @Param OrderColumn query int true "排序字段 ,Comprehensive综合 ,Matching匹配度 ,PublishDate 发布时间 "
  63. utils.FileLog.Info("SearchKeyWord:%s, userId:%s", keyWordArr, strconv.Itoa(userId))
  64. //keyWordWeight := GetWeight(keyWordLen)
  65. for _, v := range keyWordArr {
  66. if v != "" {
  67. matchArr := make([]elastic.Query, 0)
  68. boolquery := elastic.NewBoolQuery()
  69. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  70. bodyFunctionQuery2 := elastic.NewFunctionScoreQuery()
  71. bodyFunctionQuery3 := elastic.NewFunctionScoreQuery()
  72. //multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText").Analyzer("ik_smart")
  73. multiMatch := elastic.NewMultiMatchQuery(v, "Title").Analyzer("ik_smart").Boost(100)
  74. bodyFunctionQuery.Query(multiMatch)
  75. matchArr = append(matchArr, bodyFunctionQuery)
  76. multiMatch = elastic.NewMultiMatchQuery(v, "BodyText").Analyzer("ik_smart").Boost(1)
  77. bodyFunctionQuery2.Query(multiMatch)
  78. matchArr = append(matchArr, bodyFunctionQuery2)
  79. //multiMatch = elastic.NewMultiMatchQuery(1, "IsSummary")
  80. bodyFunctionQuery3.Query(multiMatch)
  81. matchArr = append(matchArr, bodyFunctionQuery3)
  82. boolquery.Should(matchArr...)
  83. //multiMatch = elastic.NewMultiMatchQuery(v, "BodyText").Analyzer("ik_smart")
  84. //bodyFunctionQuery.Query(multiMatch)
  85. //matchArr = append(matchArr, bodyFunctionQuery)
  86. //boolquery.Should(matchArr...)
  87. highlight := elastic.NewHighlight()
  88. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  89. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  90. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).From(0).Size(pageSize).Query(boolquery)
  91. if orderColumn == "Matching" {
  92. request = client.Search(indexName).Highlight(highlight).From(0).Size(pageSize).Query(boolquery)
  93. }
  94. searchByMatch, err := request.Do(context.Background())
  95. if err != nil {
  96. return nil, 0, err
  97. }
  98. if searchByMatch != nil {
  99. if searchByMatch.Hits != nil {
  100. for _, v := range searchByMatch.Hits.Hits {
  101. var isAppend bool
  102. articleJson, err := v.Source.MarshalJSON()
  103. if err != nil {
  104. return nil, 0, err
  105. }
  106. article := new(models.CygxArticleEs)
  107. err = json.Unmarshal(articleJson, &article)
  108. if err != nil {
  109. return nil, 0, err
  110. }
  111. searchItem := new(models.SearchItem)
  112. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  113. if len(v.Highlight["BodyText"]) > 0 {
  114. searchItem.Body = v.Highlight["BodyText"]
  115. } else {
  116. bodyRune := []rune(article.BodyText)
  117. bodyRuneLen := len(bodyRune)
  118. if bodyRuneLen > 100 {
  119. bodyRuneLen = 100
  120. }
  121. body := string(bodyRune[:bodyRuneLen])
  122. searchItem.Body = []string{body}
  123. }
  124. var title string
  125. if len(v.Highlight["Title"]) > 0 {
  126. title = v.Highlight["Title"][0]
  127. } else {
  128. title = article.Title
  129. }
  130. searchItem.Title = title
  131. searchItem.PublishDate = article.PublishDate
  132. searchItem.ExpertBackground = article.ExpertBackground
  133. searchItem.CategoryId = article.CategoryId
  134. for _, v_result := range result {
  135. if v_result.ArticleId == searchItem.ArticleId {
  136. isAppend = true
  137. }
  138. }
  139. if !isAppend {
  140. result = append(result, searchItem)
  141. }
  142. }
  143. }
  144. //total += searchByMatch.Hits.TotalHits.Value
  145. }
  146. }
  147. n++
  148. }
  149. total = int64(len(result))
  150. return
  151. }
  152. func EsMultiMatchFunctionScoreQueryTimeSort(indexName, keyWord string, startSize, pageSize, userId int) (result []*models.SearchItem, total int64, err error) {
  153. client := utils.Client
  154. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  155. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  156. boolquery := elastic.NewBoolQuery()
  157. matchArr := make([]elastic.Query, 0)
  158. //matchArr2 := make([]elastic.Query, 0)
  159. n := 0
  160. keyWordLen := len(keyWordArr)
  161. if keyWordLen <= 0 {
  162. keyWordArr = append(keyWordArr, keyWord)
  163. keyWordLen = len(keyWordArr)
  164. }
  165. utils.FileLog.Info("SearchKeyWord:%s, userId:%s", keyWordArr, strconv.Itoa(userId))
  166. for _, v := range keyWordArr {
  167. if v != "" {
  168. multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText")
  169. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  170. bodyFunctionQuery.Query(multiMatch)
  171. matchArr = append(matchArr, bodyFunctionQuery)
  172. }
  173. n++
  174. }
  175. boolquery.Should(matchArr...)
  176. highlight := elastic.NewHighlight()
  177. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  178. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  179. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).Size(pageSize).Query(boolquery)
  180. searchByMatch, err := request.Do(context.Background())
  181. if searchByMatch != nil {
  182. matchResult, _ := json.Marshal(searchByMatch)
  183. utils.FileLog.Info("%s", string(matchResult))
  184. fmt.Println(len(searchByMatch.Hits.Hits))
  185. if searchByMatch.Hits != nil {
  186. for _, v := range searchByMatch.Hits.Hits {
  187. articleJson, err := v.Source.MarshalJSON()
  188. utils.FileLog.Info("%s", string(articleJson))
  189. if err != nil {
  190. return nil, 0, err
  191. }
  192. article := new(models.CygxArticleEs)
  193. err = json.Unmarshal(articleJson, &article)
  194. if err != nil {
  195. return nil, 0, err
  196. }
  197. searchItem := new(models.SearchItem)
  198. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  199. if len(v.Highlight["BodyText"]) > 0 {
  200. searchItem.Body = v.Highlight["BodyText"]
  201. } else {
  202. bodyRune := []rune(article.BodyText)
  203. bodyRuneLen := len(bodyRune)
  204. if bodyRuneLen > 100 {
  205. bodyRuneLen = 100
  206. }
  207. body := string(bodyRune[:bodyRuneLen])
  208. searchItem.Body = []string{body}
  209. }
  210. var title string
  211. if len(v.Highlight["Title"]) > 0 {
  212. title = v.Highlight["Title"][0]
  213. } else {
  214. title = article.Title
  215. }
  216. searchItem.Title = title
  217. searchItem.PublishDate = article.PublishDate
  218. searchItem.ExpertBackground = article.ExpertBackground
  219. searchItem.CategoryId = article.CategoryId
  220. result = append(result, searchItem)
  221. }
  222. }
  223. total = searchByMatch.Hits.TotalHits.Value
  224. }
  225. return
  226. }
  227. func EsArticleSearch(keyWord string, startSize, pageSize int, orderColumn string, ikType int) (result []*models.SearchItem, total int64, err error) {
  228. indexName := utils.IndexName
  229. client := utils.Client
  230. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  231. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  232. keyWordLen := len(keyWordArr)
  233. if keyWordLen <= 0 {
  234. keyWordArr = append(keyWordArr, keyWord)
  235. keyWordLen = len(keyWordArr)
  236. }
  237. //如果没有联想词,而且查询的还是联想词就返回
  238. if ikType == 2 && keyWordLen == 1 {
  239. return
  240. }
  241. //Es 的高级查询有 自定义排序 文档一时半会儿撸不懂,先做多次查询手动过滤 2023.2.2
  242. //ikType 查询方式 ,0:查所有 、 1:查询键入词 、 2:查询除了查询键入词之外的联想词
  243. mustMap := make([]interface{}, 0)
  244. shouldMap := make(map[string]interface{}, 0)
  245. shouldMapquery := make([]interface{}, 0)
  246. mustNotMap := make([]interface{}, 0)
  247. shouldNotMap := make(map[string]interface{}, 0)
  248. shouldNotMapquery := make([]interface{}, 0)
  249. // @Param OrderColumn query int true "排序字段 ,Comprehensive综合 ,Matching匹配度 ,PublishDate 发布时间 "
  250. //keyWordWeight := GetWeight(keyWordLen)
  251. var boost int
  252. //lenkeyWordArr := len(keyWordArr)
  253. for k, v := range keyWordArr {
  254. if k == 0 {
  255. boost = 2 * 1000
  256. } else {
  257. boost = 1
  258. }
  259. //如果是 2:查询除了查询键入词之外的联想词
  260. if k == 0 && ikType == 2 {
  261. if v != "" {
  262. shouldNotMapquery = append(shouldNotMapquery, map[string]interface{}{
  263. "function_score": map[string]interface{}{
  264. "query": map[string]interface{}{
  265. "multi_match": map[string]interface{}{
  266. //"boost": (lenkeyWordArr - k) * boost, //给查询的值赋予权重
  267. "boost": boost, //给查询的值赋予权重
  268. "fields": []interface{}{"Title"},
  269. "query": v,
  270. },
  271. },
  272. },
  273. })
  274. shouldNotMapquery = append(shouldNotMapquery, map[string]interface{}{
  275. "function_score": map[string]interface{}{
  276. "query": map[string]interface{}{
  277. "multi_match": map[string]interface{}{
  278. "boost": boost, //给查询的值赋予权重
  279. "fields": []interface{}{"Abstract"},
  280. "query": v,
  281. },
  282. },
  283. },
  284. })
  285. shouldNotMapquery = append(shouldNotMapquery, map[string]interface{}{
  286. "function_score": map[string]interface{}{
  287. "query": map[string]interface{}{
  288. "multi_match": map[string]interface{}{
  289. "boost": boost, //给查询的值赋予权重
  290. "fields": []interface{}{"Annotation"},
  291. "query": v,
  292. },
  293. },
  294. },
  295. })
  296. shouldNotMapquery = append(shouldNotMapquery, map[string]interface{}{
  297. "function_score": map[string]interface{}{
  298. "query": map[string]interface{}{
  299. "multi_match": map[string]interface{}{
  300. //"boost": (lenkeyWordArr-k)*boost - 1, //给查询的值赋予权重
  301. "boost": boost, //给查询的值赋予权重
  302. "fields": []interface{}{"BodyText"},
  303. "query": v,
  304. },
  305. },
  306. },
  307. })
  308. }
  309. continue
  310. }
  311. //如果是 1:查询键入词
  312. if k > 0 && ikType == 1 {
  313. continue
  314. }
  315. if v != "" {
  316. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  317. "function_score": map[string]interface{}{
  318. "query": map[string]interface{}{
  319. "multi_match": map[string]interface{}{
  320. //"boost": (lenkeyWordArr - k) * boost, //给查询的值赋予权重
  321. "boost": boost, //给查询的值赋予权重
  322. "fields": []interface{}{"Title"},
  323. "query": v,
  324. },
  325. },
  326. },
  327. })
  328. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  329. "function_score": map[string]interface{}{
  330. "query": map[string]interface{}{
  331. "multi_match": map[string]interface{}{
  332. "boost": boost, //给查询的值赋予权重
  333. "fields": []interface{}{"Abstract"},
  334. "query": v,
  335. },
  336. },
  337. },
  338. })
  339. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  340. "function_score": map[string]interface{}{
  341. "query": map[string]interface{}{
  342. "multi_match": map[string]interface{}{
  343. "boost": boost, //给查询的值赋予权重
  344. "fields": []interface{}{"Annotation"},
  345. "query": v,
  346. },
  347. },
  348. },
  349. })
  350. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  351. "function_score": map[string]interface{}{
  352. "query": map[string]interface{}{
  353. "multi_match": map[string]interface{}{
  354. //"boost": (lenkeyWordArr-k)*boost - 1, //给查询的值赋予权重
  355. "boost": boost, //给查询的值赋予权重
  356. "fields": []interface{}{"BodyText"},
  357. "query": v,
  358. },
  359. },
  360. },
  361. })
  362. }
  363. }
  364. shouldMap = map[string]interface{}{
  365. "should": shouldMapquery,
  366. }
  367. shouldNotMap = map[string]interface{}{
  368. "should": shouldNotMapquery,
  369. }
  370. //排序
  371. sortMap := make([]interface{}, 0)
  372. //时间
  373. sortMap = append(sortMap, map[string]interface{}{
  374. "PublishDate": map[string]interface{}{
  375. "order": "desc",
  376. },
  377. })
  378. //sortMap = append(sortMap, map[string]interface{}{
  379. // "_score": map[string]interface{}{
  380. // "order": "desc",
  381. // },
  382. //})
  383. //高亮
  384. highlightMap := make(map[string]interface{}, 0)
  385. highlightMap = map[string]interface{}{
  386. "fields": map[string]interface{}{
  387. "BodyText": map[string]interface{}{},
  388. "Title": map[string]interface{}{},
  389. "Abstract": map[string]interface{}{},
  390. "Annotation": map[string]interface{}{},
  391. },
  392. //样式 红色
  393. "post_tags": []interface{}{"</font>"},
  394. "pre_tags": []interface{}{"<font color='red'>"},
  395. }
  396. mustMap = append(mustMap, map[string]interface{}{
  397. "bool": shouldMap,
  398. })
  399. mustNotMap = append(mustNotMap, map[string]interface{}{
  400. "bool": shouldNotMap,
  401. })
  402. queryMap := map[string]interface{}{
  403. "query": map[string]interface{}{
  404. "bool": map[string]interface{}{
  405. "must": mustMap,
  406. },
  407. },
  408. }
  409. //把第一次键入词的筛选条件过滤掉
  410. if ikType == 2 {
  411. queryMap = map[string]interface{}{
  412. "query": map[string]interface{}{
  413. "bool": map[string]interface{}{
  414. "must": mustMap,
  415. "must_not": mustNotMap,
  416. },
  417. },
  418. }
  419. }
  420. if orderColumn == "Matching" {
  421. queryMap["sort"] = sortMap
  422. }
  423. queryMap["from"] = startSize
  424. queryMap["size"] = pageSize
  425. queryMap["highlight"] = highlightMap
  426. jsonBytes, _ := json.Marshal(queryMap)
  427. fmt.Println(string(jsonBytes))
  428. //utils.FileLog.Info(string(jsonBytes))
  429. request := client.Search(indexName).Source(queryMap) // sets the JSON request
  430. searchByMatch, err := request.Do(context.Background())
  431. if searchByMatch != nil {
  432. if searchByMatch.Hits != nil {
  433. for _, v := range searchByMatch.Hits.Hits {
  434. var isAppend bool
  435. articleJson, err := v.Source.MarshalJSON()
  436. if err != nil {
  437. return nil, 0, err
  438. }
  439. article := new(models.CygxArticleEs)
  440. err = json.Unmarshal(articleJson, &article)
  441. if err != nil {
  442. return nil, 0, err
  443. }
  444. searchItem := new(models.SearchItem)
  445. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  446. if len(v.Highlight["Annotation"]) > 0 {
  447. for _, vText := range v.Highlight["Annotation"] {
  448. searchItem.Body = append(searchItem.Body, vText)
  449. }
  450. }
  451. if len(v.Highlight["Abstract"]) > 0 {
  452. for _, vText := range v.Highlight["Abstract"] {
  453. searchItem.Body = append(searchItem.Body, vText)
  454. }
  455. }
  456. if len(v.Highlight["BodyText"]) > 0 {
  457. for _, vText := range v.Highlight["BodyText"] {
  458. searchItem.Body = append(searchItem.Body, vText)
  459. }
  460. }
  461. if len(searchItem.Body) == 0 {
  462. bodyRune := []rune(article.BodyText)
  463. bodyRuneLen := len(bodyRune)
  464. if bodyRuneLen > 100 {
  465. bodyRuneLen = 100
  466. }
  467. body := string(bodyRune[:bodyRuneLen])
  468. searchItem.Body = []string{body}
  469. }
  470. //if len(v.Highlight["BodyText"]) > 0 {
  471. // searchItem.Body = v.Highlight["BodyText"]
  472. //} else {
  473. // bodyRune := []rune(article.BodyText)
  474. // bodyRuneLen := len(bodyRune)
  475. // if bodyRuneLen > 100 {
  476. // bodyRuneLen = 100
  477. // }
  478. // body := string(bodyRune[:bodyRuneLen])
  479. // searchItem.Body = []string{body}
  480. //}
  481. var title string
  482. if len(v.Highlight["Title"]) > 0 {
  483. title = v.Highlight["Title"][0]
  484. } else {
  485. title = article.Title
  486. }
  487. searchItem.Title = title
  488. searchItem.PublishDate = article.PublishDate
  489. searchItem.ExpertBackground = article.ExpertBackground
  490. searchItem.CategoryId = article.CategoryId
  491. for _, v_result := range result {
  492. if v_result.ArticleId == searchItem.ArticleId {
  493. isAppend = true
  494. }
  495. }
  496. if !isAppend {
  497. result = append(result, searchItem)
  498. }
  499. }
  500. }
  501. total = searchByMatch.Hits.TotalHits.Value
  502. }
  503. return
  504. }
  505. func EsArticleSearchBody(keyWord string, startSize, pageSize int, orderColumn string, searchType int) (result []*models.SearchItem, total int64, err error) {
  506. if keyWord == "" {
  507. return
  508. }
  509. indexName := utils.IndexName
  510. client := utils.Client
  511. //Es 的高级查询有 自定义排序 文档一时半会儿撸不懂,先做多次查询手动过滤 2023.2.2
  512. //ikType 查询方式 ,0:查所有 、 1:查询键入词 、 2:查询除了查询键入词之外的联想词
  513. mustMap := make([]interface{}, 0)
  514. shouldMap := make(map[string]interface{}, 0)
  515. shouldMapquery := make([]interface{}, 0)
  516. mustNotMap := make([]interface{}, 0)
  517. shouldNotMap := make(map[string]interface{}, 0)
  518. shouldNotMapquery := make([]interface{}, 0)
  519. // @Param OrderColumn query int true "排序字段 ,Comprehensive综合 ,Matching匹配度 ,PublishDate 发布时间 "
  520. //keyWordWeight := GetWeight(keyWordLen)
  521. var boost int
  522. //如果是 2:查询标题,摘要,核心观点的词
  523. if searchType == 1 {
  524. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  525. "function_score": map[string]interface{}{
  526. "query": map[string]interface{}{
  527. "multi_match": map[string]interface{}{
  528. "boost": boost, //给查询的值赋予权重
  529. "fields": []interface{}{"Title"},
  530. "query": keyWord,
  531. },
  532. },
  533. },
  534. })
  535. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  536. "function_score": map[string]interface{}{
  537. "query": map[string]interface{}{
  538. "multi_match": map[string]interface{}{
  539. "boost": boost, //给查询的值赋予权重
  540. "fields": []interface{}{"Abstract"},
  541. "query": keyWord,
  542. },
  543. },
  544. },
  545. })
  546. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  547. "function_score": map[string]interface{}{
  548. "query": map[string]interface{}{
  549. "multi_match": map[string]interface{}{
  550. "boost": boost, //给查询的值赋予权重
  551. "fields": []interface{}{"Annotation"},
  552. "query": keyWord,
  553. },
  554. },
  555. },
  556. })
  557. }
  558. //如果是 2:查询body的相关词
  559. if searchType == 2 {
  560. shouldNotMapquery = append(shouldNotMapquery, map[string]interface{}{
  561. "function_score": map[string]interface{}{
  562. "query": map[string]interface{}{
  563. "multi_match": map[string]interface{}{
  564. "boost": boost, //给查询的值赋予权重
  565. "fields": []interface{}{"Title"},
  566. "query": keyWord,
  567. },
  568. },
  569. },
  570. })
  571. shouldNotMapquery = append(shouldNotMapquery, map[string]interface{}{
  572. "function_score": map[string]interface{}{
  573. "query": map[string]interface{}{
  574. "multi_match": map[string]interface{}{
  575. "boost": boost, //给查询的值赋予权重
  576. "fields": []interface{}{"Abstract"},
  577. "query": keyWord,
  578. },
  579. },
  580. },
  581. })
  582. shouldNotMapquery = append(shouldNotMapquery, map[string]interface{}{
  583. "function_score": map[string]interface{}{
  584. "query": map[string]interface{}{
  585. "multi_match": map[string]interface{}{
  586. "boost": boost, //给查询的值赋予权重
  587. "fields": []interface{}{"Annotation"},
  588. "query": keyWord,
  589. },
  590. },
  591. },
  592. })
  593. //shouldNotMapquery = append(shouldNotMapquery, map[string]interface{}{
  594. // "function_score": map[string]interface{}{
  595. // "query": map[string]interface{}{
  596. // "multi_match": map[string]interface{}{
  597. // //"boost": (lenkeyWordArr-k)*boost - 1, //给查询的值赋予权重
  598. // "boost": boost, //给查询的值赋予权重
  599. // "fields": []interface{}{"BodyText"},
  600. // "query": keyWord,
  601. // },
  602. // },
  603. // },
  604. //})
  605. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  606. "function_score": map[string]interface{}{
  607. "query": map[string]interface{}{
  608. "multi_match": map[string]interface{}{
  609. //"boost": (lenkeyWordArr-k)*boost - 1, //给查询的值赋予权重
  610. "boost": boost, //给查询的值赋予权重
  611. "fields": []interface{}{"BodyText"},
  612. "query": keyWord,
  613. },
  614. },
  615. },
  616. })
  617. }
  618. shouldMap = map[string]interface{}{
  619. "should": shouldMapquery,
  620. }
  621. shouldNotMap = map[string]interface{}{
  622. "should": shouldNotMapquery,
  623. }
  624. //排序
  625. sortMap := make([]interface{}, 0)
  626. //时间
  627. sortMap = append(sortMap, map[string]interface{}{
  628. "PublishDate": map[string]interface{}{
  629. "order": "desc",
  630. },
  631. })
  632. //高亮
  633. highlightMap := make(map[string]interface{}, 0)
  634. highlightMap = map[string]interface{}{
  635. "fields": map[string]interface{}{
  636. "BodyText": map[string]interface{}{},
  637. "Title": map[string]interface{}{},
  638. "Abstract": map[string]interface{}{},
  639. "Annotation": map[string]interface{}{},
  640. },
  641. //样式 红色
  642. "post_tags": []interface{}{"</font>"},
  643. "pre_tags": []interface{}{"<font color='red'>"},
  644. }
  645. mustMap = append(mustMap, map[string]interface{}{
  646. "bool": shouldMap,
  647. })
  648. mustNotMap = append(mustNotMap, map[string]interface{}{
  649. "bool": shouldNotMap,
  650. })
  651. queryMap := map[string]interface{}{
  652. "query": map[string]interface{}{
  653. "bool": map[string]interface{}{
  654. "must": mustMap,
  655. },
  656. },
  657. }
  658. //把第一次的筛选条件过滤掉
  659. if searchType == 2 {
  660. queryMap = map[string]interface{}{
  661. "query": map[string]interface{}{
  662. "bool": map[string]interface{}{
  663. "must": mustMap,
  664. "must_not": mustNotMap,
  665. },
  666. },
  667. }
  668. }
  669. if orderColumn == "Matching" {
  670. queryMap["sort"] = sortMap
  671. }
  672. queryMap["from"] = startSize
  673. queryMap["size"] = pageSize
  674. queryMap["highlight"] = highlightMap
  675. jsonBytes, _ := json.Marshal(queryMap)
  676. fmt.Println(string(jsonBytes))
  677. //utils.FileLog.Info(string(jsonBytes))
  678. request := client.Search(indexName).Source(queryMap) // sets the JSON request
  679. searchByMatch, err := request.Do(context.Background())
  680. if searchByMatch != nil {
  681. if searchByMatch.Hits != nil {
  682. for _, v := range searchByMatch.Hits.Hits {
  683. var isAppend bool
  684. articleJson, err := v.Source.MarshalJSON()
  685. if err != nil {
  686. return nil, 0, err
  687. }
  688. article := new(models.CygxArticleEs)
  689. err = json.Unmarshal(articleJson, &article)
  690. if err != nil {
  691. return nil, 0, err
  692. }
  693. searchItem := new(models.SearchItem)
  694. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  695. if len(v.Highlight["Annotation"]) > 0 {
  696. for _, vText := range v.Highlight["Annotation"] {
  697. searchItem.Body = append(searchItem.Body, vText)
  698. }
  699. }
  700. if len(v.Highlight["Abstract"]) > 0 {
  701. for _, vText := range v.Highlight["Abstract"] {
  702. searchItem.Body = append(searchItem.Body, vText)
  703. }
  704. }
  705. if len(v.Highlight["BodyText"]) > 0 {
  706. for _, vText := range v.Highlight["BodyText"] {
  707. searchItem.Body = append(searchItem.Body, vText)
  708. }
  709. }
  710. if len(searchItem.Body) == 0 {
  711. bodyRune := []rune(article.BodyText)
  712. bodyRuneLen := len(bodyRune)
  713. if bodyRuneLen > 100 {
  714. bodyRuneLen = 100
  715. }
  716. body := string(bodyRune[:bodyRuneLen])
  717. searchItem.Body = []string{body}
  718. }
  719. //if len(v.Highlight["BodyText"]) > 0 {
  720. // searchItem.Body = v.Highlight["BodyText"]
  721. //} else {
  722. // bodyRune := []rune(article.BodyText)
  723. // bodyRuneLen := len(bodyRune)
  724. // if bodyRuneLen > 100 {
  725. // bodyRuneLen = 100
  726. // }
  727. // body := string(bodyRune[:bodyRuneLen])
  728. // searchItem.Body = []string{body}
  729. //}
  730. var title string
  731. if len(v.Highlight["Title"]) > 0 {
  732. title = v.Highlight["Title"][0]
  733. } else {
  734. title = article.Title
  735. }
  736. searchItem.Title = title
  737. searchItem.PublishDate = article.PublishDate
  738. searchItem.ExpertBackground = article.ExpertBackground
  739. searchItem.CategoryId = article.CategoryId
  740. for _, v_result := range result {
  741. if v_result.ArticleId == searchItem.ArticleId {
  742. isAppend = true
  743. }
  744. }
  745. if !isAppend {
  746. result = append(result, searchItem)
  747. }
  748. }
  749. }
  750. total = searchByMatch.Hits.TotalHits.Value
  751. }
  752. return
  753. }
  754. // KeyWordArrSqlRegexp 预处理ik联想词的模糊查询语句
  755. func KeyWordArrSqlRegexpAll(a []string) (ret string) {
  756. a_len := len(a)
  757. for i := 0; i < a_len; i++ {
  758. ret += a[i] + "|"
  759. }
  760. ret = strings.TrimRight(ret, "|")
  761. //ret = "'" + ret + "'"
  762. return
  763. }
  764. // KeyWordArrSqlRegexp 预处理ik联想词的模糊查询语句
  765. func KeyWordArrSqlRegexp(a []string) (ret string) {
  766. a_len := len(a)
  767. for i := 0; i < a_len; i++ {
  768. if i == 0 {
  769. continue
  770. }
  771. ret += a[i] + "|"
  772. }
  773. ret = strings.TrimRight(ret, "|")
  774. return
  775. }