elastic.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  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. }