elastic.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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. "time"
  13. )
  14. func NewClient() (client *elastic.Client, err error) {
  15. //errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
  16. //file := ""
  17. //if utils.RunMode == "release" {
  18. // //file = `/data/rdlucklog/hongze_cygx/eslog.log`
  19. // file = `./rdlucklog/eslog.log`
  20. //} else {
  21. // file = `./rdlucklog/eslog.log`
  22. //}
  23. //logFile, _ := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
  24. //client, err = elastic.NewClient(
  25. // elastic.SetURL(ES_URL),
  26. // elastic.SetBasicAuth(ES_USERNAME, ES_PASSWORD),
  27. // elastic.SetTraceLog(log.New(logFile, "ES-TRACE: ", 0)),
  28. // elastic.SetSniff(false), elastic.SetErrorLog(errorlog))
  29. client, err = elastic.NewClient(
  30. elastic.SetURL(ES_URL),
  31. elastic.SetBasicAuth(ES_USERNAME, ES_PASSWORD),
  32. elastic.SetSniff(false))
  33. return
  34. }
  35. //创建文章阅读记录的Es索引
  36. func CreateIndexNameArticleHistory() {
  37. indexName := utils.IndexNameArticleHistory
  38. mappingJson := `{
  39. "mappings": {
  40. "dynamic": true,
  41. "properties": {
  42. "ArticleId": {
  43. "type": "integer"
  44. },
  45. "Id": {
  46. "type": "integer"
  47. },
  48. "ArticleType": {
  49. "type": "short"
  50. },
  51. "CompanyArticleHistoryNum": {
  52. "type": "integer"
  53. },
  54. "CompanyName": {
  55. "type": "keyword"
  56. },
  57. "CompanyId": {
  58. "type": "integer"
  59. },
  60. "CreateTime": {
  61. "type": "date",
  62. "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
  63. },
  64. "Email": {
  65. "type": "keyword"
  66. },
  67. "Mobile": {
  68. "type": "keyword"
  69. },
  70. "PublishDate": {
  71. "type": "date",
  72. "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
  73. },
  74. "RealName": {
  75. "type": "keyword"
  76. },
  77. "SellerName": {
  78. "type": "keyword"
  79. },
  80. "SellerId": {
  81. "type": "integer"
  82. },
  83. "StopTime": {
  84. "type": "integer"
  85. },
  86. "Title": {
  87. "type": "keyword"
  88. },
  89. "UserId": {
  90. "type": "integer"
  91. },
  92. "UserArticleHistoryNum": {
  93. "type": "integer"
  94. }
  95. }
  96. }
  97. }`
  98. EsCreateIndex(indexName, mappingJson)
  99. }
  100. //func UpdateWxUserLabel(cont context.Context) (err error) {
  101. func AddAllArticleHistory(cont context.Context) (err error) {
  102. defer func() {
  103. if err != nil {
  104. go utils.SendAlarmMsg("同步阅读记录到es失败;Err:"+err.Error(), 2)
  105. go utils.SendEmail("同步阅读记录到es失败"+"【"+utils.APPNAME+"】"+time.Now().Format(utils.FormatDateTime), ";Err:"+err.Error(), utils.EmailSendToUsers)
  106. utils.FileLog.Info("同步阅读记录到es失败,Err:%s", err.Error())
  107. }
  108. }()
  109. var updateUserIds string //更改过的用户ID
  110. userIdMap := make(map[int]int)
  111. condition := ` AND r.create_time < '` + time.Now().Format(utils.FormatDate) + `' AND r.company_id IN (
  112. SELECT a.company_id
  113. FROM company AS a INNER JOIN company_product AS b ON a.company_id = b.company_id
  114. WHERE a.enabled = 1 AND b.STATUS IN ( '正式', '试用', '冻结' )) `
  115. totalAll, err := models.GetCygxArticleHistoryCountByCompany(condition)
  116. if err != nil {
  117. fmt.Println("GetCygxArticleHistoryCountByCompany Err:totalAll", err.Error())
  118. return err
  119. }
  120. //更改阅读总数
  121. err = models.UpdateConfigByCode(strconv.Itoa(totalAll), "company_article_history_num")
  122. if err != nil {
  123. fmt.Println("UpdateConfigByCode Err:totalAll", err.Error())
  124. return err
  125. }
  126. //处理前一天新增的数据
  127. condition += ` AND r.create_time >='` + time.Now().AddDate(0, 0, -1).Format(utils.FormatDate) + `'`
  128. total, err := models.GetCygxArticleHistoryCountByCompany(condition)
  129. //fmt.Println(total)
  130. //return
  131. fmt.Println(total)
  132. if err != nil {
  133. fmt.Println("GetCygxArticleHistoryCountByCompany Err:", err.Error())
  134. return err
  135. }
  136. for i := 0; i <= total/1000; i++ {
  137. allList, err := models.GetCygxArticleHistoryRecordByCompanyList(condition, 1000*i, 1000)
  138. if err != nil {
  139. fmt.Println("GetCygxArticleHistoryRecordByCompanyList Err:", err.Error())
  140. return err
  141. }
  142. for k, v := range allList {
  143. fmt.Println(v.Id, "___", k)
  144. err := EsAddArticleHistoryData(v)
  145. if err != nil {
  146. fmt.Println("EsAddOrEditData Err:", err.Error())
  147. return err
  148. }
  149. if _, ok := userIdMap[v.UserId]; !ok {
  150. updateUserIds += strconv.Itoa(v.UserId) + ","
  151. userIdMap[v.UserId] = v.UserId
  152. }
  153. }
  154. }
  155. //处理前一天新增的数据 end
  156. //处理前一天被移动的用户
  157. startDate := time.Now().AddDate(0, 0, -1).Format(utils.FormatDate)
  158. endDate := time.Now().Format(utils.FormatDate)
  159. var mobiles string
  160. listUpdateUser, err := models.GetWxUserOpLogList(startDate, endDate)
  161. if err != nil && err.Error() != utils.ErrNoRow() {
  162. return err
  163. }
  164. if len(listUpdateUser) > 0 {
  165. for _, v := range listUpdateUser {
  166. mobiles += "'" + v.Mobile + "',"
  167. }
  168. }
  169. mobiles = strings.TrimRight(mobiles, ",")
  170. if mobiles != "" {
  171. condition = ` AND r.mobile IN (` + mobiles + `)`
  172. //修改用户的阅读记录(es 自动判断,如果有他会修改数据)
  173. listUpdatePv, err := models.GetCygxArticleHistoryRecordByCompanyList(condition, 0, 0)
  174. if err != nil {
  175. fmt.Println("GetArticleHistoryRecordAllByMobileList ,Err" + err.Error())
  176. return err
  177. }
  178. for _, v := range listUpdatePv {
  179. err := EsAddArticleHistoryData(v)
  180. if err != nil {
  181. fmt.Println("EsAddOrEditData Err:", err.Error())
  182. return err
  183. }
  184. }
  185. }
  186. //处理前一天被移动的用户 end
  187. //处理前一天被删除的用户
  188. {
  189. listDeleteUser, err := models.GetWxUserOpLogDeleteList(startDate, endDate)
  190. if err != nil && err.Error() != utils.ErrNoRow() {
  191. return err
  192. }
  193. mobiles = ""
  194. if len(listUpdateUser) > 0 {
  195. for _, v := range listDeleteUser {
  196. mobiles += "'" + v.Mobile + "',"
  197. }
  198. }
  199. mobiles = strings.TrimRight(mobiles, ",")
  200. if mobiles != "" {
  201. condition = ` AND r.mobile IN (` + mobiles + `)`
  202. listDeletePv, err := models.GetCygxArticleHistoryRecordByCompanyList(condition, 0, 0)
  203. if err != nil {
  204. fmt.Println("GetArticleHistoryRecordAllByMobileList ,Err" + err.Error())
  205. return err
  206. }
  207. //fmt.Println("Es 删除")
  208. for _, v := range listDeletePv {
  209. err := EsDeleteData(utils.IndexNameArticleHistory, strconv.Itoa(v.Id))
  210. if err != nil {
  211. fmt.Println("EsAddOrEditData Err:", err.Error())
  212. return err
  213. }
  214. }
  215. }
  216. }
  217. //处理前一天被删除的用户 end
  218. //处理新增的阅读记录的用户阅读数量、机构阅读数量(暂未找到批量修改的方法,后期优化处理 2022.7.11)
  219. updateUserIds = strings.TrimRight(updateUserIds, ",")
  220. if updateUserIds != "" {
  221. condition = ` AND r.create_time >='` + time.Now().AddDate(0, 0, -1).Format(utils.FormatDate) + `' AND r.user_id IN (` + updateUserIds + `)`
  222. total, err := models.GetCygxArticleHistoryCountByCompany(condition)
  223. //fmt.Println(total)
  224. //return
  225. fmt.Println(total)
  226. if err != nil {
  227. fmt.Println("GetCygxArticleHistoryCountByCompany Err:", err.Error())
  228. return err
  229. }
  230. for i := 0; i <= total/1000; i++ {
  231. allList, err := models.GetCygxArticleHistoryRecordByCompanyList(condition, 1000*i, 1000)
  232. if err != nil {
  233. fmt.Println("GetCygxArticleHistoryRecordByCompanyList Err:", err.Error())
  234. return err
  235. }
  236. for k, v := range allList {
  237. fmt.Println(v.Id, "___", k)
  238. err := EsAddArticleHistoryData(v)
  239. if err != nil {
  240. fmt.Println("EsAddOrEditData Err:", err.Error())
  241. return err
  242. }
  243. if _, ok := userIdMap[v.UserId]; !ok {
  244. updateUserIds += strconv.Itoa(v.UserId) + ","
  245. userIdMap[v.UserId] = v.UserId
  246. }
  247. }
  248. }
  249. }
  250. return
  251. }
  252. //新增数据
  253. func EsAddArticleHistoryData(item *models.EsUserInteraction) (err error) {
  254. defer func() {
  255. if err != nil {
  256. fmt.Println("EsAddOrEditData Err:", err.Error())
  257. }
  258. }()
  259. client := utils.Client
  260. resp, err := client.Index().Index(utils.IndexNameArticleHistory).Id(strconv.Itoa(item.Id)).BodyJson(item).Do(context.Background())
  261. if err != nil {
  262. fmt.Println("新增失败:", err.Error())
  263. return err
  264. }
  265. if resp.Status == 0 && resp.Result == "created" {
  266. //fmt.Println("新增成功")
  267. err = nil
  268. return err
  269. } else {
  270. fmt.Println("AddData", resp.Status, resp.Result)
  271. }
  272. return
  273. }
  274. //indexName:索引名称
  275. //mappingJson:表结构
  276. func EsCreateIndex(indexName, mappingJson string) (err error) {
  277. client := utils.Client
  278. //if err != nil {
  279. // return
  280. //}
  281. //定义表结构
  282. exists, err := client.IndexExists(indexName).Do(context.Background()) //<5>
  283. if err != nil {
  284. return
  285. }
  286. if !exists {
  287. resp, err := client.CreateIndex(indexName).BodyJson(mappingJson).Do(context.Background())
  288. //BodyJson(bodyJson).Do(context.Background())
  289. if err != nil {
  290. fmt.Println("CreateIndex Err:" + err.Error())
  291. return err
  292. }
  293. fmt.Println(resp.Index, resp.ShardsAcknowledged, resp.Acknowledged)
  294. } else {
  295. fmt.Println(indexName + " 已存在")
  296. }
  297. return
  298. }
  299. //新增和修改数据
  300. func EsAddOrEditData(indexName, docId string, item *ElasticTestArticleDetail) (err error) {
  301. defer func() {
  302. if err != nil {
  303. fmt.Println("EsAddOrEditData Err:", err.Error())
  304. }
  305. }()
  306. client := utils.Client
  307. searchById, err := client.Get().Index(indexName).Id(docId).Do(context.Background())
  308. if err != nil && !strings.Contains(err.Error(), "404") {
  309. fmt.Println("Get Err" + err.Error())
  310. return
  311. }
  312. if searchById != nil && searchById.Found {
  313. resp, err := client.Update().Index(indexName).Id(docId).Doc(map[string]interface{}{
  314. "BodyText": item.BodyText,
  315. "Title": item.Title,
  316. "PublishDate": item.PublishDate,
  317. "CategoryId": item.CategoryId,
  318. "ExpertBackground": item.ExpertBackground,
  319. }).Do(context.Background())
  320. if err != nil {
  321. return err
  322. }
  323. if resp.Status == 0 {
  324. fmt.Println("修改成功")
  325. } else {
  326. fmt.Println("EditData", resp.Status, resp.Result)
  327. }
  328. client.CloseIndex(indexName)
  329. } else {
  330. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
  331. if err != nil {
  332. fmt.Println("新增失败:", err.Error())
  333. return err
  334. }
  335. if resp.Status == 0 && resp.Result == "created" {
  336. fmt.Println("新增成功")
  337. err = nil
  338. } else {
  339. fmt.Println("AddData", resp.Status, resp.Result)
  340. }
  341. }
  342. return
  343. }
  344. //新增和修改数据
  345. func EsAddOrEditDataV4(indexName, docId string, item *ElasticTestArticleDetailV4) (err error) {
  346. defer func() {
  347. if err != nil {
  348. fmt.Println("EsAddOrEditData Err:", err.Error())
  349. }
  350. }()
  351. client := utils.Client
  352. //if err != nil {
  353. // return
  354. //}
  355. searchById, err := client.Get().Index(indexName).Id(docId).Do(context.Background())
  356. if err != nil && !strings.Contains(err.Error(), "404") {
  357. fmt.Println("Get Err" + err.Error())
  358. return
  359. }
  360. if searchById != nil && searchById.Found {
  361. resp, err := client.Update().Index(indexName).Id(docId).Doc(map[string]interface{}{
  362. "BodyText": item.BodyText,
  363. "Title": item.Title,
  364. "PublishDate": item.PublishDate,
  365. "IsSummary": item.IsSummary,
  366. "IsReport": item.IsReport,
  367. }).Do(context.Background())
  368. if err != nil {
  369. return err
  370. }
  371. fmt.Println(resp.Status, resp.Result)
  372. if resp.Status == 0 {
  373. fmt.Println("修改成功")
  374. } else {
  375. fmt.Println("EditData", resp.Status, resp.Result)
  376. }
  377. } else {
  378. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
  379. if err != nil {
  380. fmt.Println("新增失败:", err.Error())
  381. return err
  382. }
  383. if resp.Status == 0 && resp.Result == "created" {
  384. fmt.Println("新增成功")
  385. err = nil
  386. } else {
  387. fmt.Println("AddData", resp.Status, resp.Result)
  388. }
  389. }
  390. return
  391. }
  392. //删除数据
  393. func EsDeleteData(indexName, docId string) (err error) {
  394. client := utils.Client
  395. //if err != nil {
  396. // return
  397. //}
  398. resp, err := client.Delete().Index(indexName).Id(docId).Do(context.Background())
  399. if err != nil {
  400. return
  401. }
  402. if resp.Status == 0 {
  403. fmt.Println("删除成功")
  404. } else {
  405. fmt.Println("AddData", resp.Status, resp.Result)
  406. }
  407. return
  408. }
  409. func GetWeight(length int) []int {
  410. steep := 10
  411. intArr := make([]int, 0)
  412. for i := 1; i <= length; i++ {
  413. if i == 1 {
  414. intArr = append(intArr, 1)
  415. } else {
  416. min := GetArrSum(intArr)
  417. maxVal := utils.GetRandInt(min, min+steep)
  418. intArr = append(intArr, maxVal)
  419. }
  420. }
  421. //数组排序
  422. sort.Slice(intArr, func(i, j int) bool {
  423. return intArr[i] > intArr[j]
  424. })
  425. return intArr
  426. }
  427. func GetArrSum(intArr []int) (sum int) {
  428. for _, val := range intArr {
  429. //累计求和
  430. sum += val
  431. }
  432. return
  433. }
  434. func EsMultiMatchFunctionScoreQuerySort(indexName, keyWord string, startSize, pageSize, userId int, orderColumn string) (result []*models.SearchItem, total int64, err error) {
  435. client := utils.Client
  436. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  437. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  438. //artidArr := make([]elastic.Query, 0)
  439. //matchArr := make([]elastic.Query, 0)
  440. n := 0
  441. keyWordLen := len(keyWordArr)
  442. if keyWordLen <= 0 {
  443. keyWordArr = append(keyWordArr, keyWord)
  444. keyWordLen = len(keyWordArr)
  445. }
  446. // @Param OrderColumn query int true "排序字段 ,Comprehensive综合 ,Matching匹配度 ,PublishDate 发布时间 "
  447. utils.FileLog.Info("SearchKeyWord:%s, userId:%s", keyWordArr, strconv.Itoa(userId))
  448. //keyWordWeight := GetWeight(keyWordLen)
  449. for _, v := range keyWordArr {
  450. if v != "" {
  451. matchArr := make([]elastic.Query, 0)
  452. boolquery := elastic.NewBoolQuery()
  453. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  454. bodyFunctionQuery2 := elastic.NewFunctionScoreQuery()
  455. bodyFunctionQuery3 := elastic.NewFunctionScoreQuery()
  456. //multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText").Analyzer("ik_smart")
  457. multiMatch := elastic.NewMultiMatchQuery(v, "Title").Analyzer("ik_smart").Boost(100)
  458. bodyFunctionQuery.Query(multiMatch)
  459. matchArr = append(matchArr, bodyFunctionQuery)
  460. multiMatch = elastic.NewMultiMatchQuery(v, "BodyText").Analyzer("ik_smart").Boost(1)
  461. bodyFunctionQuery2.Query(multiMatch)
  462. matchArr = append(matchArr, bodyFunctionQuery2)
  463. //multiMatch = elastic.NewMultiMatchQuery(1, "IsSummary")
  464. bodyFunctionQuery3.Query(multiMatch)
  465. matchArr = append(matchArr, bodyFunctionQuery3)
  466. boolquery.Should(matchArr...)
  467. //multiMatch = elastic.NewMultiMatchQuery(v, "BodyText").Analyzer("ik_smart")
  468. //bodyFunctionQuery.Query(multiMatch)
  469. //matchArr = append(matchArr, bodyFunctionQuery)
  470. //boolquery.Should(matchArr...)
  471. highlight := elastic.NewHighlight()
  472. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  473. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  474. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).From(0).Size(pageSize).Query(boolquery)
  475. if orderColumn == "Matching" {
  476. request = client.Search(indexName).Highlight(highlight).From(0).Size(pageSize).Query(boolquery)
  477. }
  478. searchByMatch, err := request.Do(context.Background())
  479. if err != nil {
  480. return nil, 0, err
  481. }
  482. if searchByMatch != nil {
  483. if searchByMatch.Hits != nil {
  484. for _, v := range searchByMatch.Hits.Hits {
  485. var isAppend bool
  486. articleJson, err := v.Source.MarshalJSON()
  487. if err != nil {
  488. return nil, 0, err
  489. }
  490. article := new(models.CygxArticleEs)
  491. err = json.Unmarshal(articleJson, &article)
  492. if err != nil {
  493. return nil, 0, err
  494. }
  495. searchItem := new(models.SearchItem)
  496. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  497. if len(v.Highlight["BodyText"]) > 0 {
  498. searchItem.Body = v.Highlight["BodyText"]
  499. } else {
  500. bodyRune := []rune(article.BodyText)
  501. bodyRuneLen := len(bodyRune)
  502. if bodyRuneLen > 100 {
  503. bodyRuneLen = 100
  504. }
  505. body := string(bodyRune[:bodyRuneLen])
  506. searchItem.Body = []string{body}
  507. }
  508. var title string
  509. if len(v.Highlight["Title"]) > 0 {
  510. title = v.Highlight["Title"][0]
  511. } else {
  512. title = article.Title
  513. }
  514. searchItem.Title = title
  515. searchItem.PublishDate = article.PublishDate
  516. searchItem.ExpertBackground = article.ExpertBackground
  517. searchItem.CategoryId = article.CategoryId
  518. for _, v_result := range result {
  519. if v_result.ArticleId == searchItem.ArticleId {
  520. isAppend = true
  521. }
  522. }
  523. if !isAppend {
  524. result = append(result, searchItem)
  525. }
  526. }
  527. }
  528. //total += searchByMatch.Hits.TotalHits.Value
  529. }
  530. }
  531. n++
  532. }
  533. total = int64(len(result))
  534. return
  535. }
  536. func EsMultiMatchFunctionScoreQueryTimeSort(indexName, keyWord string, startSize, pageSize, userId int) (result []*models.SearchItem, total int64, err error) {
  537. client := utils.Client
  538. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  539. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  540. boolquery := elastic.NewBoolQuery()
  541. matchArr := make([]elastic.Query, 0)
  542. //matchArr2 := make([]elastic.Query, 0)
  543. n := 0
  544. keyWordLen := len(keyWordArr)
  545. if keyWordLen <= 0 {
  546. keyWordArr = append(keyWordArr, keyWord)
  547. keyWordLen = len(keyWordArr)
  548. }
  549. utils.FileLog.Info("SearchKeyWord:%s, userId:%s", keyWordArr, strconv.Itoa(userId))
  550. for _, v := range keyWordArr {
  551. if v != "" {
  552. multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText")
  553. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  554. bodyFunctionQuery.Query(multiMatch)
  555. matchArr = append(matchArr, bodyFunctionQuery)
  556. }
  557. n++
  558. }
  559. boolquery.Should(matchArr...)
  560. highlight := elastic.NewHighlight()
  561. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  562. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  563. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).Size(pageSize).Query(boolquery)
  564. searchByMatch, err := request.Do(context.Background())
  565. if searchByMatch != nil {
  566. matchResult, _ := json.Marshal(searchByMatch)
  567. utils.FileLog.Info("%s", string(matchResult))
  568. fmt.Println(len(searchByMatch.Hits.Hits))
  569. if searchByMatch.Hits != nil {
  570. for _, v := range searchByMatch.Hits.Hits {
  571. articleJson, err := v.Source.MarshalJSON()
  572. utils.FileLog.Info("%s", string(articleJson))
  573. if err != nil {
  574. return nil, 0, err
  575. }
  576. article := new(models.CygxArticleEs)
  577. err = json.Unmarshal(articleJson, &article)
  578. if err != nil {
  579. return nil, 0, err
  580. }
  581. searchItem := new(models.SearchItem)
  582. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  583. if len(v.Highlight["BodyText"]) > 0 {
  584. searchItem.Body = v.Highlight["BodyText"]
  585. } else {
  586. bodyRune := []rune(article.BodyText)
  587. bodyRuneLen := len(bodyRune)
  588. if bodyRuneLen > 100 {
  589. bodyRuneLen = 100
  590. }
  591. body := string(bodyRune[:bodyRuneLen])
  592. searchItem.Body = []string{body}
  593. }
  594. var title string
  595. if len(v.Highlight["Title"]) > 0 {
  596. title = v.Highlight["Title"][0]
  597. } else {
  598. title = article.Title
  599. }
  600. searchItem.Title = title
  601. searchItem.PublishDate = article.PublishDate
  602. searchItem.ExpertBackground = article.ExpertBackground
  603. searchItem.CategoryId = article.CategoryId
  604. result = append(result, searchItem)
  605. }
  606. }
  607. total = searchByMatch.Hits.TotalHits.Value
  608. }
  609. return
  610. }
  611. func EsSearchReport(indexName, keyWord string, startSize, pageSize, userId int) (result []*models.SearchItem, total int64, err error) {
  612. client := utils.Client
  613. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  614. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  615. n := 0
  616. keyWordLen := len(keyWordArr)
  617. if keyWordLen <= 0 {
  618. keyWordArr = append(keyWordArr, keyWord)
  619. keyWordLen = len(keyWordArr)
  620. }
  621. for _, v := range keyWordArr {
  622. fmt.Println(v)
  623. }
  624. utils.FileLog.Info("SearchKeyWord:%s, userId:%s", keyWordArr, strconv.Itoa(userId))
  625. for _, v := range keyWordArr {
  626. if v != "" {
  627. matchArr := make([]elastic.Query, 0)
  628. boolquery := elastic.NewBoolQuery()
  629. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  630. bodyFunctionQuery2 := elastic.NewFunctionScoreQuery()
  631. multiMatch := elastic.NewMultiMatchQuery(v, "Title").Analyzer("ik_smart")
  632. bodyFunctionQuery.Query(multiMatch)
  633. matchArr = append(matchArr, bodyFunctionQuery)
  634. multiMatch = elastic.NewMultiMatchQuery(1, "IsReport")
  635. bodyFunctionQuery2.Query(multiMatch)
  636. matchArr = append(matchArr, bodyFunctionQuery2)
  637. boolquery.Must(matchArr...)
  638. highlight := elastic.NewHighlight()
  639. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  640. highlight = highlight.Fields(elastic.NewHighlighterField("Title"))
  641. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).From(0).Size(pageSize).Query(boolquery)
  642. searchByMatch, err := request.Do(context.Background())
  643. if err != nil {
  644. return nil, 0, err
  645. }
  646. if searchByMatch != nil {
  647. if searchByMatch.Hits != nil {
  648. for _, v := range searchByMatch.Hits.Hits {
  649. var isAppend bool
  650. articleJson, err := v.Source.MarshalJSON()
  651. if err != nil {
  652. return nil, 0, err
  653. }
  654. article := new(models.CygxArticleEs)
  655. err = json.Unmarshal(articleJson, &article)
  656. if err != nil {
  657. return nil, 0, err
  658. }
  659. searchItem := new(models.SearchItem)
  660. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  661. var title string
  662. if len(v.Highlight["Title"]) > 0 {
  663. title = v.Highlight["Title"][0]
  664. } else {
  665. title = article.Title
  666. }
  667. searchItem.Title = title
  668. searchItem.PublishDate = article.PublishDate
  669. for _, v_result := range result {
  670. if v_result.ArticleId == searchItem.ArticleId {
  671. isAppend = true
  672. }
  673. }
  674. if !isAppend {
  675. result = append(result, searchItem)
  676. }
  677. }
  678. }
  679. }
  680. }
  681. n++
  682. }
  683. total = int64(len(result))
  684. return
  685. }
  686. //分页
  687. func EsMultiMatchFunctionScoreQueryTimeSortPage(indexName, keyWord string, startSize, pageSize, userId int) (result []*models.SearchItem, total int64, err error) {
  688. client := utils.Client
  689. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  690. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  691. boolquery := elastic.NewBoolQuery()
  692. matchArr := make([]elastic.Query, 0)
  693. n := 0
  694. keyWordLen := len(keyWordArr)
  695. if keyWordLen <= 0 {
  696. keyWordArr = append(keyWordArr, keyWord)
  697. keyWordLen = len(keyWordArr)
  698. }
  699. for _, v := range keyWordArr {
  700. if v != "" {
  701. multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText")
  702. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  703. bodyFunctionQuery.Query(multiMatch)
  704. matchArr = append(matchArr, bodyFunctionQuery)
  705. }
  706. n++
  707. }
  708. boolquery.Should(matchArr...)
  709. highlight := elastic.NewHighlight()
  710. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  711. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  712. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).From(startSize).Size(pageSize).Query(boolquery)
  713. searchByMatch, err := request.Do(context.Background())
  714. if searchByMatch != nil {
  715. if searchByMatch.Hits != nil {
  716. for _, v := range searchByMatch.Hits.Hits {
  717. articleJson, err := v.Source.MarshalJSON()
  718. if err != nil {
  719. return nil, 0, err
  720. }
  721. article := new(models.CygxArticleEs)
  722. err = json.Unmarshal(articleJson, &article)
  723. if err != nil {
  724. return nil, 0, err
  725. }
  726. searchItem := new(models.SearchItem)
  727. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  728. if len(v.Highlight["BodyText"]) > 0 {
  729. searchItem.Body = v.Highlight["BodyText"]
  730. } else {
  731. bodyRune := []rune(article.BodyText)
  732. bodyRuneLen := len(bodyRune)
  733. if bodyRuneLen > 100 {
  734. bodyRuneLen = 100
  735. }
  736. body := string(bodyRune[:bodyRuneLen])
  737. searchItem.Body = []string{body}
  738. }
  739. var title string
  740. if len(v.Highlight["Title"]) > 0 {
  741. title = v.Highlight["Title"][0]
  742. } else {
  743. title = article.Title
  744. }
  745. searchItem.Title = title
  746. searchItem.PublishDate = article.PublishDate
  747. searchItem.ExpertBackground = article.ExpertBackground
  748. searchItem.CategoryId = article.CategoryId
  749. result = append(result, searchItem)
  750. }
  751. }
  752. total = searchByMatch.Hits.TotalHits.Value
  753. }
  754. return
  755. }
  756. func EsMultiMatchFunctionScoreQuerySortPage(indexName, keyWord string, startSize, pageSize, userId int, orderColumn string) (result []*models.SearchItem, total int64, err error) {
  757. client := utils.Client
  758. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  759. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  760. keyWordLen := len(keyWordArr)
  761. if keyWordLen <= 0 {
  762. keyWordArr = append(keyWordArr, keyWord)
  763. keyWordLen = len(keyWordArr)
  764. }
  765. var keyWords string
  766. for _, v := range keyWordArr {
  767. keyWords += v + " "
  768. }
  769. // @Param OrderColumn query int true "排序字段 ,Comprehensive综合 ,Matching匹配度 ,PublishDate 发布时间 "
  770. //keyWordWeight := GetWeight(keyWordLen)
  771. matchArr := make([]elastic.Query, 0)
  772. boolquery := elastic.NewBoolQuery()
  773. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  774. bodyFunctionQuery2 := elastic.NewFunctionScoreQuery()
  775. bodyFunctionQuery3 := elastic.NewFunctionScoreQuery()
  776. multiMatch := elastic.NewMultiMatchQuery(keyWords, "Title").Analyzer("ik_smart").Boost(100)
  777. bodyFunctionQuery.Query(multiMatch)
  778. matchArr = append(matchArr, bodyFunctionQuery)
  779. multiMatch = elastic.NewMultiMatchQuery(keyWords, "BodyText").Analyzer("ik_smart").Boost(1)
  780. bodyFunctionQuery2.Query(multiMatch)
  781. matchArr = append(matchArr, bodyFunctionQuery2)
  782. bodyFunctionQuery3.Query(multiMatch)
  783. matchArr = append(matchArr, bodyFunctionQuery3)
  784. boolquery.Should(matchArr...)
  785. highlight := elastic.NewHighlight()
  786. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  787. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  788. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).From(startSize).Size(pageSize).Query(boolquery)
  789. if orderColumn == "Matching" {
  790. request = client.Search(indexName).Highlight(highlight).From(startSize).Size(pageSize).Query(boolquery)
  791. }
  792. searchByMatch, err := request.Do(context.Background())
  793. if err != nil {
  794. return nil, 0, err
  795. }
  796. if searchByMatch != nil {
  797. if searchByMatch.Hits != nil {
  798. for _, v := range searchByMatch.Hits.Hits {
  799. var isAppend bool
  800. articleJson, err := v.Source.MarshalJSON()
  801. if err != nil {
  802. return nil, 0, err
  803. }
  804. article := new(models.CygxArticleEs)
  805. err = json.Unmarshal(articleJson, &article)
  806. if err != nil {
  807. return nil, 0, err
  808. }
  809. searchItem := new(models.SearchItem)
  810. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  811. if len(v.Highlight["BodyText"]) > 0 {
  812. searchItem.Body = v.Highlight["BodyText"]
  813. } else {
  814. bodyRune := []rune(article.BodyText)
  815. bodyRuneLen := len(bodyRune)
  816. if bodyRuneLen > 100 {
  817. bodyRuneLen = 100
  818. }
  819. body := string(bodyRune[:bodyRuneLen])
  820. searchItem.Body = []string{body}
  821. }
  822. var title string
  823. if len(v.Highlight["Title"]) > 0 {
  824. title = v.Highlight["Title"][0]
  825. } else {
  826. title = article.Title
  827. }
  828. searchItem.Title = title
  829. searchItem.PublishDate = article.PublishDate
  830. searchItem.ExpertBackground = article.ExpertBackground
  831. searchItem.CategoryId = article.CategoryId
  832. for _, v_result := range result {
  833. if v_result.ArticleId == searchItem.ArticleId {
  834. isAppend = true
  835. }
  836. }
  837. if !isAppend {
  838. result = append(result, searchItem)
  839. }
  840. }
  841. }
  842. }
  843. total += searchByMatch.Hits.TotalHits.Value
  844. return
  845. }
  846. func init23423() {
  847. EsArticleSearch("立高食品", 0, 10, "34")
  848. }
  849. func EsArticleSearch(keyWord string, startSize, pageSize int, orderColumn string) (result []*models.SearchItem, total int64, err error) {
  850. indexName := utils.IndexName
  851. client := utils.Client
  852. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  853. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  854. keyWordLen := len(keyWordArr)
  855. if keyWordLen <= 0 {
  856. keyWordArr = append(keyWordArr, keyWord)
  857. keyWordLen = len(keyWordArr)
  858. }
  859. //fmt.Println(keyWordArr)
  860. mustMap := make([]interface{}, 0)
  861. shouldMap := make(map[string]interface{}, 0)
  862. //shouldMapquery := make(map[string]interface{}, 0)
  863. shouldMapquery := make([]interface{}, 0)
  864. // @Param OrderColumn query int true "排序字段 ,Comprehensive综合 ,Matching匹配度 ,PublishDate 发布时间 "
  865. //keyWordWeight := GetWeight(keyWordLen)
  866. var boost int
  867. lenkeyWordArr := len(keyWordArr)
  868. for k, v := range keyWordArr {
  869. if k == 0 {
  870. boost = 2 * 1000
  871. } else {
  872. boost = 1000
  873. }
  874. if v != "" {
  875. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  876. "function_score": map[string]interface{}{
  877. "query": map[string]interface{}{
  878. "multi_match": map[string]interface{}{
  879. "boost": (lenkeyWordArr - k) * boost, //给查询的值赋予权重
  880. "fields": []interface{}{"Title"},
  881. "query": v,
  882. },
  883. },
  884. },
  885. })
  886. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  887. "function_score": map[string]interface{}{
  888. "query": map[string]interface{}{
  889. "multi_match": map[string]interface{}{
  890. "boost": (lenkeyWordArr-k)*boost - 1, //给查询的值赋予权重
  891. "fields": []interface{}{"BodyText"},
  892. "query": v,
  893. },
  894. },
  895. },
  896. })
  897. }
  898. }
  899. shouldMap = map[string]interface{}{
  900. "should": shouldMapquery,
  901. }
  902. //排序
  903. sortMap := make([]interface{}, 0)
  904. //时间
  905. sortMap = append(sortMap, map[string]interface{}{
  906. "PublishDate": map[string]interface{}{
  907. "order": "desc",
  908. },
  909. })
  910. //高亮
  911. highlightMap := make(map[string]interface{}, 0)
  912. highlightMap = map[string]interface{}{
  913. "fields": map[string]interface{}{
  914. "BodyText": map[string]interface{}{},
  915. "Title": map[string]interface{}{},
  916. },
  917. //样式 红色
  918. "post_tags": []interface{}{"</font>"},
  919. "pre_tags": []interface{}{"<font color='red'>"},
  920. }
  921. mustMap = append(mustMap, map[string]interface{}{
  922. "bool": shouldMap,
  923. })
  924. queryMap := map[string]interface{}{
  925. "query": map[string]interface{}{
  926. "bool": map[string]interface{}{
  927. "must": mustMap,
  928. },
  929. },
  930. }
  931. if orderColumn == "PublishDate" {
  932. queryMap["sort"] = sortMap
  933. }
  934. queryMap["from"] = startSize
  935. queryMap["size"] = pageSize
  936. queryMap["highlight"] = highlightMap
  937. jsonBytes, _ := json.Marshal(queryMap)
  938. fmt.Println(string(jsonBytes))
  939. //utils.FileLog.Info(string(jsonBytes))
  940. request := client.Search(indexName).Source(queryMap) // sets the JSON request
  941. searchByMatch, err := request.Do(context.Background())
  942. if searchByMatch != nil {
  943. if searchByMatch.Hits != nil {
  944. for _, v := range searchByMatch.Hits.Hits {
  945. var isAppend bool
  946. articleJson, err := v.Source.MarshalJSON()
  947. if err != nil {
  948. return nil, 0, err
  949. }
  950. article := new(models.CygxArticleEs)
  951. err = json.Unmarshal(articleJson, &article)
  952. if err != nil {
  953. return nil, 0, err
  954. }
  955. searchItem := new(models.SearchItem)
  956. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  957. if len(v.Highlight["BodyText"]) > 0 {
  958. searchItem.Body = v.Highlight["BodyText"]
  959. } else {
  960. bodyRune := []rune(article.BodyText)
  961. bodyRuneLen := len(bodyRune)
  962. if bodyRuneLen > 100 {
  963. bodyRuneLen = 100
  964. }
  965. body := string(bodyRune[:bodyRuneLen])
  966. searchItem.Body = []string{body}
  967. }
  968. var title string
  969. if len(v.Highlight["Title"]) > 0 {
  970. title = v.Highlight["Title"][0]
  971. } else {
  972. title = article.Title
  973. }
  974. searchItem.Title = title
  975. searchItem.PublishDate = article.PublishDate
  976. searchItem.ExpertBackground = article.ExpertBackground
  977. searchItem.CategoryId = article.CategoryId
  978. for _, v_result := range result {
  979. if v_result.ArticleId == searchItem.ArticleId {
  980. isAppend = true
  981. }
  982. }
  983. if !isAppend {
  984. result = append(result, searchItem)
  985. }
  986. }
  987. }
  988. total = searchByMatch.Hits.TotalHits.Value
  989. }
  990. //fmt.Println(result)
  991. //for _, v := range result {
  992. // fmt.Println(v)
  993. //}
  994. return
  995. }