elastic.go 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  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 := utils.Client
  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 := utils.Client
  67. searchById, err := client.Get().Index(indexName).Id(docId).Do(context.Background())
  68. if err != nil && !strings.Contains(err.Error(), "404") {
  69. fmt.Println("Get Err" + err.Error())
  70. return
  71. }
  72. if searchById != nil && searchById.Found {
  73. resp, err := client.Update().Index(indexName).Id(docId).Doc(map[string]interface{}{
  74. "BodyText": item.BodyText,
  75. "Title": item.Title,
  76. "PublishDate": item.PublishDate,
  77. "CategoryId": item.CategoryId,
  78. "ExpertBackground": item.ExpertBackground,
  79. }).Do(context.Background())
  80. if err != nil {
  81. return err
  82. }
  83. if resp.Status == 0 {
  84. fmt.Println("修改成功")
  85. } else {
  86. fmt.Println("EditData", resp.Status, resp.Result)
  87. }
  88. client.CloseIndex(indexName)
  89. } else {
  90. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
  91. if err != nil {
  92. fmt.Println("新增失败:", err.Error())
  93. return err
  94. }
  95. if resp.Status == 0 && resp.Result == "created" {
  96. fmt.Println("新增成功")
  97. err = nil
  98. } else {
  99. fmt.Println("AddData", resp.Status, resp.Result)
  100. }
  101. }
  102. return
  103. }
  104. //新增和修改数据
  105. func EsAddOrEditDataV4(indexName, docId string, item *ElasticTestArticleDetailV4) (err error) {
  106. defer func() {
  107. if err != nil {
  108. fmt.Println("EsAddOrEditData Err:", err.Error())
  109. }
  110. }()
  111. client := utils.Client
  112. //if err != nil {
  113. // return
  114. //}
  115. searchById, err := client.Get().Index(indexName).Id(docId).Do(context.Background())
  116. if err != nil && !strings.Contains(err.Error(), "404") {
  117. fmt.Println("Get Err" + err.Error())
  118. return
  119. }
  120. if searchById != nil && searchById.Found {
  121. resp, err := client.Update().Index(indexName).Id(docId).Doc(map[string]interface{}{
  122. "BodyText": item.BodyText,
  123. "Title": item.Title,
  124. "PublishDate": item.PublishDate,
  125. "IsSummary": item.IsSummary,
  126. "IsReport": item.IsReport,
  127. }).Do(context.Background())
  128. if err != nil {
  129. return err
  130. }
  131. fmt.Println(resp.Status, resp.Result)
  132. if resp.Status == 0 {
  133. fmt.Println("修改成功")
  134. } else {
  135. fmt.Println("EditData", resp.Status, resp.Result)
  136. }
  137. } else {
  138. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
  139. if err != nil {
  140. fmt.Println("新增失败:", err.Error())
  141. return err
  142. }
  143. if resp.Status == 0 && resp.Result == "created" {
  144. fmt.Println("新增成功")
  145. err = nil
  146. } else {
  147. fmt.Println("AddData", resp.Status, resp.Result)
  148. }
  149. }
  150. return
  151. }
  152. //删除数据
  153. func EsDeleteData(indexName, docId string) (err error) {
  154. client := utils.Client
  155. //if err != nil {
  156. // return
  157. //}
  158. resp, err := client.Delete().Index(indexName).Id(docId).Do(context.Background())
  159. if err != nil {
  160. return
  161. }
  162. if resp.Status == 0 {
  163. fmt.Println("删除成功")
  164. } else {
  165. fmt.Println("AddData", resp.Status, resp.Result)
  166. }
  167. return
  168. }
  169. func MappingModify(indexName, mappingJson string) {
  170. client := utils.Client
  171. //if err != nil {
  172. // return
  173. //}
  174. result, err := client.PutMapping().Index(indexName).BodyString(mappingJson).Do(context.Background())
  175. fmt.Println(err)
  176. fmt.Println(result)
  177. return
  178. }
  179. func EsMatchQuery(indexName, keyWord string) (result []*models.SearchItem, err error) {
  180. client := utils.Client
  181. pageSize := 20
  182. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  183. fmt.Println(keyWordArr)
  184. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  185. fmt.Println("-------------------------------")
  186. fmt.Println(keyWordArr)
  187. searchMap := make(map[int]int)
  188. boolquery := elastic.NewBoolQuery()
  189. keyLen := len(keyWordArr)
  190. n := 5.0 * float64(keyLen)
  191. matchArr := make([]elastic.Query, 0)
  192. //
  193. //matchq1 := elastic.NewMatchQuery("Title", keyWord).Boost(n + 1).Analyzer("ik_smart")
  194. //matchq2 := elastic.NewMatchQuery("BodyText", keyWord).Boost(n + 1).Analyzer("ik_smart")
  195. //
  196. //matchArr = append(matchArr, matchq1)
  197. //matchArr = append(matchArr, matchq2)
  198. for _, v := range keyWordArr {
  199. if v != "" {
  200. matchq1 := elastic.NewMatchQuery("Title", v).Boost(n).Analyzer("ik_smart")
  201. matchq2 := elastic.NewMatchQuery("BodyText", v).Boost(n).Analyzer("ik_smart")
  202. matchArr = append(matchArr, matchq1)
  203. matchArr = append(matchArr, matchq2)
  204. }
  205. n = n - 5
  206. }
  207. boolquery.Should(matchArr...)
  208. highlight := elastic.NewHighlight()
  209. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  210. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  211. request := client.Search(indexName).Highlight(highlight).Size(pageSize).Query(boolquery)
  212. searchByMatch, err := request.Do(context.Background())
  213. if searchByMatch.Hits != nil {
  214. for _, v := range searchByMatch.Hits.Hits {
  215. articleJson, err := v.Source.MarshalJSON()
  216. if err != nil {
  217. return nil, err
  218. }
  219. article := new(models.CygxArticle)
  220. err = json.Unmarshal(articleJson, &article)
  221. if err != nil {
  222. return nil, err
  223. }
  224. if _, ok := searchMap[article.ArticleId]; !ok {
  225. searchItem := new(models.SearchItem)
  226. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  227. if len(v.Highlight["BodyText"]) > 0 {
  228. searchItem.Body = v.Highlight["BodyText"]
  229. } else {
  230. bodyRune := []rune(article.BodyText)
  231. bodyRuneLen := len(bodyRune)
  232. if bodyRuneLen > 100 {
  233. bodyRuneLen = 100
  234. }
  235. body := string(bodyRune[:bodyRuneLen])
  236. fmt.Println(body)
  237. searchItem.Body = []string{body}
  238. }
  239. var title string
  240. if len(v.Highlight["Title"]) > 0 {
  241. title = v.Highlight["Title"][0]
  242. } else {
  243. title = article.Title
  244. }
  245. searchItem.Title = title
  246. searchItem.PublishDate = article.PublishDate
  247. result = append(result, searchItem)
  248. searchMap[article.ArticleId] = article.ArticleId
  249. }
  250. }
  251. }
  252. return
  253. }
  254. func EsMatchPhraseQuery(indexName, keyWord string) (result []*models.SearchItem, err error) {
  255. client := utils.Client
  256. pageSize := 20
  257. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  258. fmt.Println(keyWordArr)
  259. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  260. fmt.Println("-------------------------------")
  261. fmt.Println(keyWordArr)
  262. searchMap := make(map[int]int)
  263. boolquery := elastic.NewBoolQuery()
  264. //keyLen := len(keyWordArr)
  265. //n := float64(keyLen)
  266. matchArr := make([]elastic.Query, 0)
  267. //matchq1 := elastic.NewMatchQuery("Title", keyWord).Boost(n + 1).Analyzer("ik_smart")
  268. //matchq2 := elastic.NewMatchQuery("BodyText", keyWord).Boost(n + 1).Analyzer("ik_smart")
  269. matchq1 := elastic.NewMatchPhraseQuery("Title", keyWord) //.Analyzer("ik_smart")
  270. matchq2 := elastic.NewMatchPhraseQuery("BodyText", keyWord)
  271. matchArr = append(matchArr, matchq1)
  272. matchArr = append(matchArr, matchq2)
  273. //matchArr = append(matchArr, matchq2)
  274. //for _, v := range keyWordArr {
  275. // if v != "" {
  276. // matchq1 := elastic.NewMatchQuery("Title", v).Boost(n).Analyzer("ik_smart")
  277. // matchq2 := elastic.NewMatchQuery("BodyText", v).Boost(n).Analyzer("ik_smart")
  278. // matchArr = append(matchArr, matchq1)
  279. // matchArr = append(matchArr, matchq2)
  280. // }
  281. // n--
  282. //}
  283. //boolquery.Should(matchArr...)
  284. boolquery.Should(matchArr...)
  285. highlight := elastic.NewHighlight()
  286. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  287. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  288. request := client.Search(indexName).Highlight(highlight).Size(pageSize).Query(boolquery)
  289. searchByMatch, err := request.Do(context.Background())
  290. fmt.Println("err:", err, searchByMatch)
  291. return
  292. if searchByMatch.Hits != nil {
  293. for _, v := range searchByMatch.Hits.Hits {
  294. articleJson, err := v.Source.MarshalJSON()
  295. if err != nil {
  296. return nil, err
  297. }
  298. article := new(models.CygxArticle)
  299. err = json.Unmarshal(articleJson, &article)
  300. if err != nil {
  301. return nil, err
  302. }
  303. if _, ok := searchMap[article.ArticleId]; !ok {
  304. searchItem := new(models.SearchItem)
  305. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  306. searchItem.Body = v.Highlight["BodyText"]
  307. var title string
  308. if len(v.Highlight["Title"]) > 0 {
  309. title = v.Highlight["Title"][0]
  310. } else {
  311. title = article.Title
  312. }
  313. searchItem.Title = title
  314. searchItem.PublishDate = article.PublishDate
  315. result = append(result, searchItem)
  316. searchMap[article.ArticleId] = article.ArticleId
  317. }
  318. }
  319. }
  320. return
  321. }
  322. func EsMatchFunctionScoreQuery(indexName, keyWord string, startSize, pageSize int) (result []*models.SearchItem, total int64, err error) {
  323. client := utils.Client
  324. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  325. fmt.Println(keyWordArr)
  326. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  327. fmt.Println("-------------------------------")
  328. fmt.Println(keyWordArr)
  329. searchMap := make(map[int]int)
  330. boolquery := elastic.NewBoolQuery()
  331. matchArr := make([]elastic.Query, 0)
  332. //
  333. //matchq1 := elastic.NewMatchQuery("Title", keyWord).Boost(n + 1).Analyzer("ik_smart")
  334. //matchq2 := elastic.NewMatchQuery("BodyText", keyWord).Boost(n + 1).Analyzer("ik_smart")
  335. //
  336. //matchArr = append(matchArr, matchq1)
  337. //matchArr = append(matchArr, matchq2)
  338. n := 0
  339. keyWordLen := len(keyWordArr)
  340. if keyWordLen <= 0 {
  341. keyWordArr = append(keyWordArr, keyWord)
  342. keyWordLen = len(keyWordArr)
  343. }
  344. keyWordWeight := GetWeight(keyWordLen)
  345. fmt.Println(keyWordArr)
  346. fmt.Println(keyWordWeight)
  347. for k, v := range keyWordArr {
  348. if v != "" {
  349. weight := float64(keyWordWeight[k])
  350. titleMatchq := elastic.NewMatchQuery("Title", v).Analyzer("ik_smart")
  351. bodyMatchq := elastic.NewMatchQuery("BodyText", v).Analyzer("ik_smart")
  352. titleFunctionQuery := elastic.NewFunctionScoreQuery()
  353. titleFunctionQuery.Query(titleMatchq)
  354. titleFunctions := elastic.NewWeightFactorFunction(weight)
  355. titleFunctionQuery.AddScoreFunc(titleFunctions)
  356. titleFunctionQuery.BoostMode("replace")
  357. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  358. bodyFunctionQuery.Query(bodyMatchq)
  359. bodyFunctions := elastic.NewWeightFactorFunction(weight)
  360. bodyFunctionQuery.AddScoreFunc(bodyFunctions)
  361. bodyFunctionQuery.BoostMode("replace")
  362. matchArr = append(matchArr, titleFunctionQuery)
  363. matchArr = append(matchArr, bodyFunctionQuery)
  364. }
  365. n++
  366. }
  367. boolquery.Should(matchArr...)
  368. highlight := elastic.NewHighlight()
  369. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  370. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  371. request := client.Search(indexName).Highlight(highlight).From(startSize).Size(pageSize).Query(boolquery)
  372. searchByMatch, err := request.Do(context.Background())
  373. //searchJson, err := json.Marshal(searchByMatch)
  374. if searchByMatch != nil {
  375. if searchByMatch.Hits != nil {
  376. for _, v := range searchByMatch.Hits.Hits {
  377. articleJson, err := v.Source.MarshalJSON()
  378. if err != nil {
  379. return nil, 0, err
  380. }
  381. article := new(models.CygxArticle)
  382. err = json.Unmarshal(articleJson, &article)
  383. if err != nil {
  384. return nil, 0, err
  385. }
  386. if _, ok := searchMap[article.ArticleId]; !ok {
  387. searchItem := new(models.SearchItem)
  388. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  389. if len(v.Highlight["BodyText"]) > 0 {
  390. searchItem.Body = v.Highlight["BodyText"]
  391. } else {
  392. bodyRune := []rune(article.BodyText)
  393. bodyRuneLen := len(bodyRune)
  394. if bodyRuneLen > 100 {
  395. bodyRuneLen = 100
  396. }
  397. body := string(bodyRune[:bodyRuneLen])
  398. fmt.Println(body)
  399. searchItem.Body = []string{body}
  400. }
  401. var title string
  402. if len(v.Highlight["Title"]) > 0 {
  403. title = v.Highlight["Title"][0]
  404. } else {
  405. title = article.Title
  406. }
  407. searchItem.Title = title
  408. searchItem.PublishDate = article.PublishDate
  409. result = append(result, searchItem)
  410. searchMap[article.ArticleId] = article.ArticleId
  411. }
  412. }
  413. }
  414. }
  415. total = searchByMatch.Hits.TotalHits.Value
  416. return
  417. }
  418. func EsMultiMatchFunctionScoreQuery(indexName, keyWord string, startSize, pageSize, userId int) (result []*models.SearchItem, total int64, err error) {
  419. client := utils.Client
  420. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  421. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  422. //artidArr := make([]elastic.Query, 0)
  423. //matchArr := make([]elastic.Query, 0)
  424. n := 0
  425. keyWordLen := len(keyWordArr)
  426. if keyWordLen <= 0 {
  427. keyWordArr = append(keyWordArr, keyWord)
  428. keyWordLen = len(keyWordArr)
  429. }
  430. utils.FileLog.Info("SearchKeyWord:%s, userId:%s", keyWordArr, strconv.Itoa(userId))
  431. //keyWordWeight := GetWeight(keyWordLen)
  432. for _, v := range keyWordArr {
  433. if v != "" {
  434. matchArr := make([]elastic.Query, 0)
  435. boolquery := elastic.NewBoolQuery()
  436. //weight := float64(keyWordWeight[k])
  437. //multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText").Analyzer("ik_smart")
  438. //bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  439. //bodyFunctionQuery.Query(multiMatch)
  440. //bodyFunctions := elastic.NewWeightFactorFunction(weight)
  441. //bodyFunctionQuery.AddScoreFunc(bodyFunctions)
  442. //bodyFunctionQuery.BoostMode("replace")
  443. //matchArr = append(matchArr, bodyFunctionQuery)
  444. //weight := float64(keyWordWeight[k])
  445. multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText").Analyzer("ik_smart")
  446. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  447. bodyFunctionQuery.Query(multiMatch)
  448. //bodyFunctions := elastic.NewWeightFactorFunction(weight)
  449. //bodyFunctionQuery.AddScoreFunc(bodyFunctions)
  450. //bodyFunctionQuery.BoostMode("replace")
  451. matchArr = append(matchArr, bodyFunctionQuery)
  452. boolquery.Should(matchArr...)
  453. highlight := elastic.NewHighlight()
  454. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  455. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  456. request := client.Search(indexName).Highlight(highlight).From(startSize).Size(pageSize).Query(boolquery)
  457. searchByMatch, err := request.Do(context.Background())
  458. if err != nil {
  459. return nil, 0, err
  460. }
  461. if searchByMatch != nil {
  462. if searchByMatch.Hits != nil {
  463. for _, v := range searchByMatch.Hits.Hits {
  464. var isAppend bool
  465. articleJson, err := v.Source.MarshalJSON()
  466. if err != nil {
  467. return nil, 0, err
  468. }
  469. article := new(models.CygxArticle)
  470. err = json.Unmarshal(articleJson, &article)
  471. if err != nil {
  472. return nil, 0, err
  473. }
  474. searchItem := new(models.SearchItem)
  475. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  476. if len(v.Highlight["BodyText"]) > 0 {
  477. searchItem.Body = v.Highlight["BodyText"]
  478. } else {
  479. bodyRune := []rune(article.BodyText)
  480. bodyRuneLen := len(bodyRune)
  481. if bodyRuneLen > 100 {
  482. bodyRuneLen = 100
  483. }
  484. body := string(bodyRune[:bodyRuneLen])
  485. searchItem.Body = []string{body}
  486. }
  487. var title string
  488. if len(v.Highlight["Title"]) > 0 {
  489. title = v.Highlight["Title"][0]
  490. } else {
  491. title = article.Title
  492. }
  493. searchItem.Title = title
  494. searchItem.PublishDate = article.PublishDate
  495. for _, v_result := range result {
  496. if v_result.ArticleId == searchItem.ArticleId {
  497. isAppend = true
  498. }
  499. }
  500. if !isAppend {
  501. result = append(result, searchItem)
  502. }
  503. }
  504. }
  505. //total += searchByMatch.Hits.TotalHits.Value
  506. }
  507. }
  508. n++
  509. }
  510. total = int64(len(result))
  511. //fmt.Println(result)
  512. //boolquery.Should(matchArr...)
  513. //highlight := elastic.NewHighlight()
  514. //highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  515. //highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  516. //request := client.Search(indexName).Highlight(highlight).From(startSize).Size(pageSize).Query(boolquery)
  517. //searchByMatch, err := request.Do(context.Background())
  518. //if searchByMatch != nil {
  519. // if searchByMatch.Hits != nil {
  520. // for _, v := range searchByMatch.Hits.Hits {
  521. // articleJson, err := v.Source.MarshalJSON()
  522. // if err != nil {
  523. // return nil, 0, err
  524. // }
  525. // article := new(models.CygxArticle)
  526. // err = json.Unmarshal(articleJson, &article)
  527. // if err != nil {
  528. // return nil, 0, err
  529. // }
  530. // searchItem := new(models.SearchItem)
  531. // searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  532. // if len(v.Highlight["BodyText"]) > 0 {
  533. // searchItem.Body = v.Highlight["BodyText"]
  534. // } else {
  535. // bodyRune := []rune(article.BodyText)
  536. // bodyRuneLen := len(bodyRune)
  537. // if bodyRuneLen > 100 {
  538. // bodyRuneLen = 100
  539. // }
  540. // body := string(bodyRune[:bodyRuneLen])
  541. // searchItem.Body = []string{body}
  542. // }
  543. // var title string
  544. // if len(v.Highlight["Title"]) > 0 {
  545. // title = v.Highlight["Title"][0]
  546. // } else {
  547. // title = article.Title
  548. // }
  549. // searchItem.Title = title
  550. // searchItem.PublishDate = article.PublishDate
  551. //
  552. // result = append(result, searchItem)
  553. // }
  554. // }
  555. // total = searchByMatch.Hits.TotalHits.Value
  556. //}
  557. return
  558. }
  559. func EsMultiMatchFunctionScoreQueryFix(indexName, keyWord string, startSize, pageSize int) (result []*models.SearchItem, total int64, err error) {
  560. client := utils.Client
  561. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  562. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  563. boolquery := elastic.NewBoolQuery()
  564. matchArr := make([]elastic.Query, 0)
  565. n := 0
  566. keyWordLen := len(keyWordArr)
  567. if keyWordLen <= 0 {
  568. keyWordArr = append(keyWordArr, keyWord)
  569. keyWordLen = len(keyWordArr)
  570. }
  571. fmt.Println(keyWordArr)
  572. keyWordWeight := GetWeight(keyWordLen)
  573. for k, v := range keyWordArr {
  574. if v != "" {
  575. weight := float64(keyWordWeight[k])
  576. multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText").Analyzer("ik_smart")
  577. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  578. bodyFunctionQuery.Query(multiMatch)
  579. bodyFunctions := elastic.NewWeightFactorFunction(weight)
  580. bodyFunctionQuery.AddScoreFunc(bodyFunctions)
  581. bodyFunctionQuery.BoostMode("replace")
  582. matchArr = append(matchArr, bodyFunctionQuery)
  583. }
  584. n++
  585. }
  586. boolquery.Should(matchArr...)
  587. highlight := elastic.NewHighlight()
  588. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  589. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  590. request := client.Search(indexName).Highlight(highlight).From(startSize).Size(pageSize).Query(boolquery)
  591. searchByMatch, err := request.Do(context.Background())
  592. if searchByMatch != nil {
  593. matchResult, _ := json.Marshal(searchByMatch)
  594. utils.FileLog.Info("%s", string(matchResult))
  595. if searchByMatch.Hits != nil {
  596. for _, v := range searchByMatch.Hits.Hits {
  597. articleJson, err := v.Source.MarshalJSON()
  598. utils.FileLog.Info("%s", string(articleJson))
  599. if err != nil {
  600. return nil, 0, err
  601. }
  602. article := new(models.CygxArticle)
  603. err = json.Unmarshal(articleJson, &article)
  604. if err != nil {
  605. return nil, 0, err
  606. }
  607. searchItem := new(models.SearchItem)
  608. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  609. if len(v.Highlight["BodyText"]) > 0 {
  610. searchItem.Body = v.Highlight["BodyText"]
  611. } else {
  612. bodyRune := []rune(article.BodyText)
  613. bodyRuneLen := len(bodyRune)
  614. if bodyRuneLen > 100 {
  615. bodyRuneLen = 100
  616. }
  617. body := string(bodyRune[:bodyRuneLen])
  618. searchItem.Body = []string{body}
  619. }
  620. var title string
  621. if len(v.Highlight["Title"]) > 0 {
  622. title = v.Highlight["Title"][0]
  623. } else {
  624. title = article.Title
  625. }
  626. searchItem.Title = title
  627. searchItem.PublishDate = article.PublishDate
  628. result = append(result, searchItem)
  629. }
  630. }
  631. total = searchByMatch.Hits.TotalHits.Value
  632. }
  633. return
  634. }
  635. func GetWeight(length int) []int {
  636. steep := 10
  637. intArr := make([]int, 0)
  638. for i := 1; i <= length; i++ {
  639. if i == 1 {
  640. intArr = append(intArr, 1)
  641. } else {
  642. min := GetArrSum(intArr)
  643. maxVal := utils.GetRandInt(min, min+steep)
  644. intArr = append(intArr, maxVal)
  645. }
  646. }
  647. //数组排序
  648. sort.Slice(intArr, func(i, j int) bool {
  649. return intArr[i] > intArr[j]
  650. })
  651. return intArr
  652. }
  653. func GetArrSum(intArr []int) (sum int) {
  654. for _, val := range intArr {
  655. //累计求和
  656. sum += val
  657. }
  658. return
  659. }
  660. //func init() {
  661. // fmt.Println("start")
  662. // keyWord:="阿里巴巴"
  663. // keyWordArr, _ := GetIndustryMapNameSliceV2(keyWord)
  664. // keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  665. // fmt.Println(keyWordArr)
  666. // fmt.Println("end")
  667. //}
  668. func EsMultiMatchFunctionScoreQuerySort(indexName, keyWord string, startSize, pageSize, userId int, orderColumn string) (result []*models.SearchItem, total int64, err error) {
  669. client := utils.Client
  670. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  671. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  672. //artidArr := make([]elastic.Query, 0)
  673. //matchArr := make([]elastic.Query, 0)
  674. n := 0
  675. keyWordLen := len(keyWordArr)
  676. if keyWordLen <= 0 {
  677. keyWordArr = append(keyWordArr, keyWord)
  678. keyWordLen = len(keyWordArr)
  679. }
  680. // @Param OrderColumn query int true "排序字段 ,Comprehensive综合 ,Matching匹配度 ,PublishDate 发布时间 "
  681. utils.FileLog.Info("SearchKeyWord:%s, userId:%s", keyWordArr, strconv.Itoa(userId))
  682. //keyWordWeight := GetWeight(keyWordLen)
  683. for _, v := range keyWordArr {
  684. if v != "" {
  685. matchArr := make([]elastic.Query, 0)
  686. boolquery := elastic.NewBoolQuery()
  687. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  688. bodyFunctionQuery2 := elastic.NewFunctionScoreQuery()
  689. bodyFunctionQuery3 := elastic.NewFunctionScoreQuery()
  690. //multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText").Analyzer("ik_smart")
  691. multiMatch := elastic.NewMultiMatchQuery(v, "Title").Analyzer("ik_smart").Boost(100)
  692. bodyFunctionQuery.Query(multiMatch)
  693. matchArr = append(matchArr, bodyFunctionQuery)
  694. multiMatch = elastic.NewMultiMatchQuery(v, "BodyText").Analyzer("ik_smart").Boost(1)
  695. bodyFunctionQuery2.Query(multiMatch)
  696. matchArr = append(matchArr, bodyFunctionQuery2)
  697. //multiMatch = elastic.NewMultiMatchQuery(1, "IsSummary")
  698. bodyFunctionQuery3.Query(multiMatch)
  699. matchArr = append(matchArr, bodyFunctionQuery3)
  700. boolquery.Should(matchArr...)
  701. //multiMatch = elastic.NewMultiMatchQuery(v, "BodyText").Analyzer("ik_smart")
  702. //bodyFunctionQuery.Query(multiMatch)
  703. //matchArr = append(matchArr, bodyFunctionQuery)
  704. //boolquery.Should(matchArr...)
  705. highlight := elastic.NewHighlight()
  706. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  707. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  708. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).From(0).Size(pageSize).Query(boolquery)
  709. if orderColumn == "Matching" {
  710. request = client.Search(indexName).Highlight(highlight).From(0).Size(pageSize).Query(boolquery)
  711. }
  712. searchByMatch, err := request.Do(context.Background())
  713. if err != nil {
  714. return nil, 0, err
  715. }
  716. if searchByMatch != nil {
  717. if searchByMatch.Hits != nil {
  718. for _, v := range searchByMatch.Hits.Hits {
  719. var isAppend bool
  720. articleJson, err := v.Source.MarshalJSON()
  721. if err != nil {
  722. return nil, 0, err
  723. }
  724. article := new(models.CygxArticleEs)
  725. err = json.Unmarshal(articleJson, &article)
  726. if err != nil {
  727. return nil, 0, err
  728. }
  729. searchItem := new(models.SearchItem)
  730. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  731. if len(v.Highlight["BodyText"]) > 0 {
  732. searchItem.Body = v.Highlight["BodyText"]
  733. } else {
  734. bodyRune := []rune(article.BodyText)
  735. bodyRuneLen := len(bodyRune)
  736. if bodyRuneLen > 100 {
  737. bodyRuneLen = 100
  738. }
  739. body := string(bodyRune[:bodyRuneLen])
  740. searchItem.Body = []string{body}
  741. }
  742. var title string
  743. if len(v.Highlight["Title"]) > 0 {
  744. title = v.Highlight["Title"][0]
  745. } else {
  746. title = article.Title
  747. }
  748. searchItem.Title = title
  749. searchItem.PublishDate = article.PublishDate
  750. searchItem.ExpertBackground = article.ExpertBackground
  751. searchItem.CategoryId = article.CategoryId
  752. for _, v_result := range result {
  753. if v_result.ArticleId == searchItem.ArticleId {
  754. isAppend = true
  755. }
  756. }
  757. if !isAppend {
  758. result = append(result, searchItem)
  759. }
  760. }
  761. }
  762. //total += searchByMatch.Hits.TotalHits.Value
  763. }
  764. }
  765. n++
  766. }
  767. total = int64(len(result))
  768. return
  769. }
  770. func EsMultiMatchFunctionScoreQueryTimeSort(indexName, keyWord string, startSize, pageSize, userId int) (result []*models.SearchItem, total int64, err error) {
  771. client := utils.Client
  772. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  773. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  774. boolquery := elastic.NewBoolQuery()
  775. matchArr := make([]elastic.Query, 0)
  776. //matchArr2 := make([]elastic.Query, 0)
  777. n := 0
  778. keyWordLen := len(keyWordArr)
  779. if keyWordLen <= 0 {
  780. keyWordArr = append(keyWordArr, keyWord)
  781. keyWordLen = len(keyWordArr)
  782. }
  783. utils.FileLog.Info("SearchKeyWord:%s, userId:%s", keyWordArr, strconv.Itoa(userId))
  784. for _, v := range keyWordArr {
  785. if v != "" {
  786. multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText")
  787. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  788. bodyFunctionQuery.Query(multiMatch)
  789. matchArr = append(matchArr, bodyFunctionQuery)
  790. }
  791. n++
  792. }
  793. boolquery.Should(matchArr...)
  794. highlight := elastic.NewHighlight()
  795. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  796. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  797. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).Size(pageSize).Query(boolquery)
  798. searchByMatch, err := request.Do(context.Background())
  799. if searchByMatch != nil {
  800. matchResult, _ := json.Marshal(searchByMatch)
  801. utils.FileLog.Info("%s", string(matchResult))
  802. fmt.Println(len(searchByMatch.Hits.Hits))
  803. if searchByMatch.Hits != nil {
  804. for _, v := range searchByMatch.Hits.Hits {
  805. articleJson, err := v.Source.MarshalJSON()
  806. utils.FileLog.Info("%s", string(articleJson))
  807. if err != nil {
  808. return nil, 0, err
  809. }
  810. article := new(models.CygxArticleEs)
  811. err = json.Unmarshal(articleJson, &article)
  812. if err != nil {
  813. return nil, 0, err
  814. }
  815. searchItem := new(models.SearchItem)
  816. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  817. if len(v.Highlight["BodyText"]) > 0 {
  818. searchItem.Body = v.Highlight["BodyText"]
  819. } else {
  820. bodyRune := []rune(article.BodyText)
  821. bodyRuneLen := len(bodyRune)
  822. if bodyRuneLen > 100 {
  823. bodyRuneLen = 100
  824. }
  825. body := string(bodyRune[:bodyRuneLen])
  826. searchItem.Body = []string{body}
  827. }
  828. var title string
  829. if len(v.Highlight["Title"]) > 0 {
  830. title = v.Highlight["Title"][0]
  831. } else {
  832. title = article.Title
  833. }
  834. searchItem.Title = title
  835. searchItem.PublishDate = article.PublishDate
  836. searchItem.ExpertBackground = article.ExpertBackground
  837. searchItem.CategoryId = article.CategoryId
  838. result = append(result, searchItem)
  839. }
  840. }
  841. total = searchByMatch.Hits.TotalHits.Value
  842. }
  843. return
  844. }
  845. func EsSearchReport(indexName, keyWord string, startSize, pageSize, userId int) (result []*models.SearchItem, total int64, err error) {
  846. client := utils.Client
  847. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  848. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  849. n := 0
  850. keyWordLen := len(keyWordArr)
  851. if keyWordLen <= 0 {
  852. keyWordArr = append(keyWordArr, keyWord)
  853. keyWordLen = len(keyWordArr)
  854. }
  855. for _, v := range keyWordArr {
  856. fmt.Println(v)
  857. }
  858. utils.FileLog.Info("SearchKeyWord:%s, userId:%s", keyWordArr, strconv.Itoa(userId))
  859. for _, v := range keyWordArr {
  860. if v != "" {
  861. matchArr := make([]elastic.Query, 0)
  862. boolquery := elastic.NewBoolQuery()
  863. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  864. bodyFunctionQuery2 := elastic.NewFunctionScoreQuery()
  865. multiMatch := elastic.NewMultiMatchQuery(v, "Title").Analyzer("ik_smart")
  866. bodyFunctionQuery.Query(multiMatch)
  867. matchArr = append(matchArr, bodyFunctionQuery)
  868. multiMatch = elastic.NewMultiMatchQuery(1, "IsReport")
  869. bodyFunctionQuery2.Query(multiMatch)
  870. matchArr = append(matchArr, bodyFunctionQuery2)
  871. boolquery.Must(matchArr...)
  872. highlight := elastic.NewHighlight()
  873. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  874. highlight = highlight.Fields(elastic.NewHighlighterField("Title"))
  875. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).From(0).Size(pageSize).Query(boolquery)
  876. searchByMatch, err := request.Do(context.Background())
  877. if err != nil {
  878. return nil, 0, err
  879. }
  880. if searchByMatch != nil {
  881. if searchByMatch.Hits != nil {
  882. for _, v := range searchByMatch.Hits.Hits {
  883. var isAppend bool
  884. articleJson, err := v.Source.MarshalJSON()
  885. if err != nil {
  886. return nil, 0, err
  887. }
  888. article := new(models.CygxArticleEs)
  889. err = json.Unmarshal(articleJson, &article)
  890. if err != nil {
  891. return nil, 0, err
  892. }
  893. searchItem := new(models.SearchItem)
  894. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  895. var title string
  896. if len(v.Highlight["Title"]) > 0 {
  897. title = v.Highlight["Title"][0]
  898. } else {
  899. title = article.Title
  900. }
  901. searchItem.Title = title
  902. searchItem.PublishDate = article.PublishDate
  903. for _, v_result := range result {
  904. if v_result.ArticleId == searchItem.ArticleId {
  905. isAppend = true
  906. }
  907. }
  908. if !isAppend {
  909. result = append(result, searchItem)
  910. }
  911. }
  912. }
  913. }
  914. }
  915. n++
  916. }
  917. total = int64(len(result))
  918. return
  919. }
  920. //分页
  921. func EsMultiMatchFunctionScoreQueryTimeSortPage(indexName, keyWord string, startSize, pageSize, userId int) (result []*models.SearchItem, total int64, err error) {
  922. client := utils.Client
  923. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  924. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  925. boolquery := elastic.NewBoolQuery()
  926. matchArr := make([]elastic.Query, 0)
  927. n := 0
  928. keyWordLen := len(keyWordArr)
  929. if keyWordLen <= 0 {
  930. keyWordArr = append(keyWordArr, keyWord)
  931. keyWordLen = len(keyWordArr)
  932. }
  933. for _, v := range keyWordArr {
  934. if v != "" {
  935. multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText")
  936. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  937. bodyFunctionQuery.Query(multiMatch)
  938. matchArr = append(matchArr, bodyFunctionQuery)
  939. }
  940. n++
  941. }
  942. boolquery.Should(matchArr...)
  943. highlight := elastic.NewHighlight()
  944. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  945. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  946. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).From(startSize).Size(pageSize).Query(boolquery)
  947. searchByMatch, err := request.Do(context.Background())
  948. if searchByMatch != nil {
  949. if searchByMatch.Hits != nil {
  950. for _, v := range searchByMatch.Hits.Hits {
  951. articleJson, err := v.Source.MarshalJSON()
  952. if err != nil {
  953. return nil, 0, err
  954. }
  955. article := new(models.CygxArticleEs)
  956. err = json.Unmarshal(articleJson, &article)
  957. if err != nil {
  958. return nil, 0, err
  959. }
  960. searchItem := new(models.SearchItem)
  961. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  962. if len(v.Highlight["BodyText"]) > 0 {
  963. searchItem.Body = v.Highlight["BodyText"]
  964. } else {
  965. bodyRune := []rune(article.BodyText)
  966. bodyRuneLen := len(bodyRune)
  967. if bodyRuneLen > 100 {
  968. bodyRuneLen = 100
  969. }
  970. body := string(bodyRune[:bodyRuneLen])
  971. searchItem.Body = []string{body}
  972. }
  973. var title string
  974. if len(v.Highlight["Title"]) > 0 {
  975. title = v.Highlight["Title"][0]
  976. } else {
  977. title = article.Title
  978. }
  979. searchItem.Title = title
  980. searchItem.PublishDate = article.PublishDate
  981. searchItem.ExpertBackground = article.ExpertBackground
  982. searchItem.CategoryId = article.CategoryId
  983. result = append(result, searchItem)
  984. }
  985. }
  986. total = searchByMatch.Hits.TotalHits.Value
  987. }
  988. return
  989. }
  990. func EsMultiMatchFunctionScoreQuerySortPage(indexName, keyWord string, startSize, pageSize, userId int, orderColumn string) (result []*models.SearchItem, total int64, err error) {
  991. client := utils.Client
  992. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  993. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  994. keyWordLen := len(keyWordArr)
  995. if keyWordLen <= 0 {
  996. keyWordArr = append(keyWordArr, keyWord)
  997. keyWordLen = len(keyWordArr)
  998. }
  999. var keyWords string
  1000. for _, v := range keyWordArr {
  1001. keyWords += v + " "
  1002. }
  1003. // @Param OrderColumn query int true "排序字段 ,Comprehensive综合 ,Matching匹配度 ,PublishDate 发布时间 "
  1004. //keyWordWeight := GetWeight(keyWordLen)
  1005. matchArr := make([]elastic.Query, 0)
  1006. boolquery := elastic.NewBoolQuery()
  1007. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  1008. bodyFunctionQuery2 := elastic.NewFunctionScoreQuery()
  1009. bodyFunctionQuery3 := elastic.NewFunctionScoreQuery()
  1010. multiMatch := elastic.NewMultiMatchQuery(keyWords, "Title").Analyzer("ik_smart").Boost(100)
  1011. bodyFunctionQuery.Query(multiMatch)
  1012. matchArr = append(matchArr, bodyFunctionQuery)
  1013. multiMatch = elastic.NewMultiMatchQuery(keyWords, "BodyText").Analyzer("ik_smart").Boost(1)
  1014. bodyFunctionQuery2.Query(multiMatch)
  1015. matchArr = append(matchArr, bodyFunctionQuery2)
  1016. bodyFunctionQuery3.Query(multiMatch)
  1017. matchArr = append(matchArr, bodyFunctionQuery3)
  1018. boolquery.Should(matchArr...)
  1019. highlight := elastic.NewHighlight()
  1020. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  1021. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  1022. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).From(startSize).Size(pageSize).Query(boolquery)
  1023. if orderColumn == "Matching" {
  1024. request = client.Search(indexName).Highlight(highlight).From(startSize).Size(pageSize).Query(boolquery)
  1025. }
  1026. searchByMatch, err := request.Do(context.Background())
  1027. if err != nil {
  1028. return nil, 0, err
  1029. }
  1030. if searchByMatch != nil {
  1031. if searchByMatch.Hits != nil {
  1032. for _, v := range searchByMatch.Hits.Hits {
  1033. var isAppend bool
  1034. articleJson, err := v.Source.MarshalJSON()
  1035. if err != nil {
  1036. return nil, 0, err
  1037. }
  1038. article := new(models.CygxArticleEs)
  1039. err = json.Unmarshal(articleJson, &article)
  1040. if err != nil {
  1041. return nil, 0, err
  1042. }
  1043. searchItem := new(models.SearchItem)
  1044. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  1045. if len(v.Highlight["BodyText"]) > 0 {
  1046. searchItem.Body = v.Highlight["BodyText"]
  1047. } else {
  1048. bodyRune := []rune(article.BodyText)
  1049. bodyRuneLen := len(bodyRune)
  1050. if bodyRuneLen > 100 {
  1051. bodyRuneLen = 100
  1052. }
  1053. body := string(bodyRune[:bodyRuneLen])
  1054. searchItem.Body = []string{body}
  1055. }
  1056. var title string
  1057. if len(v.Highlight["Title"]) > 0 {
  1058. title = v.Highlight["Title"][0]
  1059. } else {
  1060. title = article.Title
  1061. }
  1062. searchItem.Title = title
  1063. searchItem.PublishDate = article.PublishDate
  1064. searchItem.ExpertBackground = article.ExpertBackground
  1065. searchItem.CategoryId = article.CategoryId
  1066. for _, v_result := range result {
  1067. if v_result.ArticleId == searchItem.ArticleId {
  1068. isAppend = true
  1069. }
  1070. }
  1071. if !isAppend {
  1072. result = append(result, searchItem)
  1073. }
  1074. }
  1075. }
  1076. }
  1077. total += searchByMatch.Hits.TotalHits.Value
  1078. return
  1079. }