elastic.go 31 KB

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