elastic.go 31 KB

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