elastic.go 31 KB

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