elastic.go 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508
  1. package services
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/olivere/elastic/v7"
  8. "hongze/hongze_cygx/models"
  9. "hongze/hongze_cygx/utils"
  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. //
  102. //func init() {
  103. // AddAllArticleHistory()
  104. //}
  105. func AddAllArticleHistory(cont context.Context) (err error) {
  106. //func AddAllArticleHistory() (err error) {
  107. defer func() {
  108. if err != nil {
  109. fmt.Println(err)
  110. go utils.SendAlarmMsg("同步阅读记录到es失败;AddAllArticleHistory Err:"+err.Error(), 2)
  111. }
  112. }()
  113. var pars []interface{}
  114. var condition string
  115. var companyIds []int
  116. condition = " AND product_id = 2 AND STATUS IN ( '正式', '试用', '冻结' ) "
  117. list, e := models.GetCompanyProductList(condition, pars)
  118. if e != nil {
  119. err = errors.New("GetCompanyProductList, Err: " + e.Error())
  120. return
  121. }
  122. for _, v := range list {
  123. companyIds = append(companyIds, v.CompanyId)
  124. }
  125. var updateUserIds string //更改过的用户ID
  126. userIdMap := make(map[int]int)
  127. //condition := ` AND r.create_time < '` + time.Now().Format(utils.FormatDate) + `' AND r.company_id IN (
  128. // SELECT a.company_id
  129. // FROM company AS a INNER JOIN company_product AS b ON a.company_id = b.company_id
  130. // WHERE a.enabled = 1 AND b.STATUS IN ( '正式', '试用', '冻结' )) `
  131. //
  132. //totalAll, err := models.GetCygxArticleHistoryCountByCompany(condition)
  133. //获取阅读总数
  134. condition = " AND company_id IN (" + utils.GetOrmInReplace(len(companyIds)) + ") AND is_del = 0 "
  135. pars = append(pars, companyIds)
  136. totalAll, e := models.GetCygxArticleHistoryRecordAllCount(condition, pars)
  137. if e != nil {
  138. err = errors.New("GetCygxArticleHistoryRecordAllCount, Err: " + e.Error())
  139. return
  140. }
  141. //更改阅读总数
  142. e = models.UpdateConfigByCode(strconv.Itoa(totalAll), "company_article_history_num")
  143. if e != nil {
  144. err = errors.New("UpdateConfigByCode, Err: " + e.Error())
  145. return
  146. }
  147. //处理前一天新增的数据
  148. //condition += ` AND create_time >= ? AND is_del = 0 `
  149. //pars = append(pars, time.Now().AddDate(0, 0, -1).Format(utils.FormatDate))
  150. //total, err := models.GetCygxArticleHistoryRecordAllCount(condition, pars)
  151. ////fmt.Println(total)
  152. ////return
  153. //fmt.Println(total)
  154. //if err != nil {
  155. // fmt.Println("GetCygxArticleHistoryCountByCompany Err:", err.Error())
  156. // return err
  157. //}
  158. pars = make([]interface{}, 0)
  159. condition = ` `
  160. condition = " AND r.company_id IN (" + utils.GetOrmInReplace(len(companyIds)) + ") AND r.is_del = 0 AND r.create_time >= ? AND r.create_time <= ? "
  161. pars = append(pars, companyIds, time.Now().AddDate(0, 0, -1).Format(utils.FormatDate), time.Now().Format(utils.FormatDate))
  162. allList, e := models.GetCygxArticleHistoryRecordByCompanyListNew(condition, pars, 0, 0)
  163. if e != nil {
  164. err = errors.New("GetCygxArticleHistoryRecordByCompanyListNew, Err: " + e.Error())
  165. return
  166. }
  167. fmt.Println(len(allList))
  168. //return
  169. for k, v := range allList {
  170. //fmt.Println(v)
  171. fmt.Println(v.Id, "___", k)
  172. err := EsAddArticleHistoryData(v)
  173. if err != nil {
  174. fmt.Println("EsAddOrEditData Err:", err.Error())
  175. //return err
  176. }
  177. if _, ok := userIdMap[v.UserId]; !ok {
  178. updateUserIds += strconv.Itoa(v.UserId) + ","
  179. userIdMap[v.UserId] = v.UserId
  180. }
  181. }
  182. //for i := 0; i <= total/1000; i++ {
  183. // allList, err := models.GetCygxArticleHistoryRecordByCompanyListNew(condition, pars, 1000*i, 1000)
  184. // if err != nil {
  185. // fmt.Println("GetCygxArticleHistoryRecordByCompanyListNew Err:", err.Error())
  186. // return err
  187. // }
  188. // for k, v := range allList {
  189. // fmt.Println(v.Id, "___", k)
  190. // //err := EsAddArticleHistoryData(v)
  191. // //if err != nil {
  192. // // fmt.Println("EsAddOrEditData Err:", err.Error())
  193. // // return err
  194. // //}
  195. // //if _, ok := userIdMap[v.UserId]; !ok {
  196. // // updateUserIds += strconv.Itoa(v.UserId) + ","
  197. // // userIdMap[v.UserId] = v.UserId
  198. // //}
  199. // }
  200. //}
  201. //return
  202. //处理前一天新增的数据 end
  203. //处理前一天被移动的用户
  204. startDate := time.Now().AddDate(0, 0, -1).Format(utils.FormatDate)
  205. endDate := time.Now().Format(utils.FormatDate)
  206. var mobiles []string
  207. listUpdateUser, e := models.GetWxUserOpLogList(startDate, endDate)
  208. if e != nil && e.Error() != utils.ErrNoRow() {
  209. err = errors.New("GetWxUserOpLogList, Err: " + e.Error())
  210. return
  211. }
  212. if len(listUpdateUser) > 0 {
  213. for _, v := range listUpdateUser {
  214. mobiles = append(mobiles, v.Mobile)
  215. }
  216. }
  217. //mobiles = strings.TrimRight(mobiles, ",")
  218. if len(mobiles) > 0 {
  219. pars = make([]interface{}, 0)
  220. condition = ` AND r.mobile IN (` + utils.GetOrmInReplace(len(mobiles)) + `)`
  221. pars = append(pars, mobiles)
  222. //修改用户的阅读记录(es 自动判断,如果有他会修改数据)
  223. listUpdatePv, e := models.GetCygxArticleHistoryRecordByCompanyListNew(condition, pars, 0, 0)
  224. if e != nil && e.Error() != utils.ErrNoRow() {
  225. err = errors.New("GetCygxArticleHistoryRecordByCompanyListNew,mobilesUpdate Err: " + e.Error())
  226. return
  227. }
  228. for _, v := range listUpdatePv {
  229. err := EsAddArticleHistoryData(v)
  230. if err != nil {
  231. fmt.Println("EsAddOrEditData Err:", err.Error())
  232. //return err
  233. }
  234. }
  235. }
  236. //处理前一天被移动的用户 end
  237. //处理前一天被删除的用户
  238. {
  239. listDeleteUser, e := models.GetWxUserOpLogDeleteList(startDate, endDate)
  240. if e != nil && e.Error() != utils.ErrNoRow() {
  241. err = errors.New("GetWxUserOpLogDeleteList, Err: " + e.Error())
  242. return
  243. }
  244. var mobilesDel []string
  245. if len(listUpdateUser) > 0 {
  246. for _, v := range listDeleteUser {
  247. mobilesDel = append(mobilesDel, v.Mobile)
  248. }
  249. }
  250. if len(mobilesDel) > 0 {
  251. pars = make([]interface{}, 0)
  252. condition = ` AND r.mobile IN (` + utils.GetOrmInReplace(len(mobilesDel)) + `)`
  253. pars = append(pars, mobilesDel)
  254. listDeletePv, e := models.GetCygxArticleHistoryRecordByCompanyListNew(condition, pars, 0, 0)
  255. if e != nil && e.Error() != utils.ErrNoRow() {
  256. err = errors.New("GetCygxArticleHistoryRecordByCompanyListNew,mobilesDel Err: " + e.Error())
  257. return
  258. }
  259. for _, v := range listDeletePv {
  260. err := EsDeleteData(utils.IndexNameArticleHistory, strconv.Itoa(v.Id))
  261. if err != nil {
  262. fmt.Println("EsDeleteData Err:", err.Error())
  263. //return err
  264. }
  265. }
  266. }
  267. }
  268. //处理前一天被删除的用户 end
  269. //处理新增的阅读记录的用户阅读数量、机构阅读数量(暂未找到批量修改的方法,后期优化处理 2022.7.11)
  270. //updateUserIds = strings.TrimRight(updateUserIds, ",")
  271. //if updateUserIds != "" {
  272. // condition = ` AND r.create_time >='` + time.Now().AddDate(0, 0, -1).Format(utils.FormatDate) + `' AND r.user_id IN (` + updateUserIds + `)`
  273. // total, err := models.GetCygxArticleHistoryCountByCompany(condition)
  274. // //fmt.Println(total)
  275. // //return
  276. // fmt.Println(total)
  277. // if err != nil {
  278. // fmt.Println("GetCygxArticleHistoryCountByCompany Err:", err.Error())
  279. // return err
  280. // }
  281. // for i := 0; i <= total/1000; i++ {
  282. // allList, err := models.GetCygxArticleHistoryRecordByCompanyList(condition, 1000*i, 1000)
  283. // if err != nil {
  284. // fmt.Println("GetCygxArticleHistoryRecordByCompanyList Err:", err.Error())
  285. // return err
  286. // }
  287. // for k, v := range allList {
  288. // fmt.Println(v.Id, "___", k)
  289. // err := EsAddArticleHistoryData(v)
  290. // if err != nil {
  291. // fmt.Println("EsAddOrEditData Err:", err.Error())
  292. // return err
  293. // }
  294. // if _, ok := userIdMap[v.UserId]; !ok {
  295. // updateUserIds += strconv.Itoa(v.UserId) + ","
  296. // userIdMap[v.UserId] = v.UserId
  297. // }
  298. // }
  299. // }
  300. //}
  301. return
  302. }
  303. // 新增数据
  304. func EsAddArticleHistoryData(item *models.EsUserInteraction) (err error) {
  305. defer func() {
  306. if err != nil {
  307. fmt.Println("EsAddOrEditData Err:", err.Error())
  308. }
  309. }()
  310. client := utils.Client
  311. resp, err := client.Index().Index(utils.IndexNameArticleHistory).Id(strconv.Itoa(item.Id)).BodyJson(item).Do(context.Background())
  312. if err != nil {
  313. fmt.Println("新增失败:", err.Error())
  314. return err
  315. }
  316. if resp.Status == 0 && resp.Result == "created" {
  317. //fmt.Println("新增成功")
  318. err = nil
  319. return err
  320. } else {
  321. fmt.Println("AddData", resp.Status, resp.Result)
  322. }
  323. return
  324. }
  325. // indexName:索引名称
  326. // mappingJson:表结构
  327. func EsCreateIndex(indexName, mappingJson string) (err error) {
  328. client := utils.Client
  329. //if err != nil {
  330. // return
  331. //}
  332. //定义表结构
  333. exists, err := client.IndexExists(indexName).Do(context.Background()) //<5>
  334. if err != nil {
  335. return
  336. }
  337. if !exists {
  338. resp, err := client.CreateIndex(indexName).BodyJson(mappingJson).Do(context.Background())
  339. //BodyJson(bodyJson).Do(context.Background())
  340. if err != nil {
  341. fmt.Println("CreateIndex Err:" + err.Error())
  342. return err
  343. }
  344. fmt.Println(resp.Index, resp.ShardsAcknowledged, resp.Acknowledged)
  345. } else {
  346. fmt.Println(indexName + " 已存在")
  347. }
  348. return
  349. }
  350. // 新增和修改数据
  351. func EsAddOrEditData(indexName, docId string, item *ElasticTestArticleDetail) (err error) {
  352. defer func() {
  353. if err != nil {
  354. fmt.Println("EsAddOrEditData Err:", err.Error())
  355. }
  356. }()
  357. client := utils.Client
  358. searchById, err := client.Get().Index(indexName).Id(docId).Do(context.Background())
  359. if err != nil && !strings.Contains(err.Error(), "404") {
  360. fmt.Println("Get Err" + err.Error())
  361. return
  362. }
  363. if searchById != nil && searchById.Found {
  364. resp, err := client.Update().Index(indexName).Id(docId).Doc(map[string]interface{}{
  365. "BodyText": item.BodyText,
  366. "Title": item.Title,
  367. "PublishDate": item.PublishDate,
  368. "CategoryId": item.CategoryId,
  369. "ExpertBackground": item.ExpertBackground,
  370. "Abstract": item.Abstract,
  371. "Annotation": item.Annotation,
  372. }).Do(context.Background())
  373. if err != nil {
  374. return err
  375. }
  376. if resp.Status == 0 {
  377. fmt.Println("修改成功")
  378. } else {
  379. fmt.Println("EditData", resp.Status, resp.Result)
  380. }
  381. client.CloseIndex(indexName)
  382. } else {
  383. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
  384. if err != nil {
  385. fmt.Println("新增失败:", err.Error())
  386. return err
  387. }
  388. if resp.Status == 0 && resp.Result == "created" {
  389. fmt.Println("新增成功")
  390. err = nil
  391. } else {
  392. fmt.Println("AddData", resp.Status, resp.Result)
  393. }
  394. }
  395. return
  396. }
  397. // 新增和修改数据
  398. func EsAddOrEditDataV4(indexName, docId string, item *ElasticTestArticleDetailV4) (err error) {
  399. defer func() {
  400. if err != nil {
  401. fmt.Println("EsAddOrEditData Err:", err.Error())
  402. }
  403. }()
  404. client := utils.Client
  405. //if err != nil {
  406. // return
  407. //}
  408. searchById, err := client.Get().Index(indexName).Id(docId).Do(context.Background())
  409. if err != nil && !strings.Contains(err.Error(), "404") {
  410. fmt.Println("Get Err" + err.Error())
  411. return
  412. }
  413. if searchById != nil && searchById.Found {
  414. resp, err := client.Update().Index(indexName).Id(docId).Doc(map[string]interface{}{
  415. "BodyText": item.BodyText,
  416. "Title": item.Title,
  417. "PublishDate": item.PublishDate,
  418. "IsSummary": item.IsSummary,
  419. "IsReport": item.IsReport,
  420. }).Do(context.Background())
  421. if err != nil {
  422. return err
  423. }
  424. fmt.Println(resp.Status, resp.Result)
  425. if resp.Status == 0 {
  426. fmt.Println("修改成功")
  427. } else {
  428. fmt.Println("EditData", resp.Status, resp.Result)
  429. }
  430. } else {
  431. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
  432. if err != nil {
  433. fmt.Println("新增失败:", err.Error())
  434. return err
  435. }
  436. if resp.Status == 0 && resp.Result == "created" {
  437. fmt.Println("新增成功")
  438. err = nil
  439. } else {
  440. fmt.Println("AddData", resp.Status, resp.Result)
  441. }
  442. }
  443. return
  444. }
  445. // 删除数据
  446. func EsDeleteData(indexName, docId string) (err error) {
  447. client := utils.Client
  448. //if err != nil {
  449. // return
  450. //}
  451. resp, err := client.Delete().Index(indexName).Id(docId).Do(context.Background())
  452. if err != nil {
  453. return
  454. }
  455. if resp.Status == 0 {
  456. fmt.Println("删除成功")
  457. } else {
  458. fmt.Println("AddData", resp.Status, resp.Result)
  459. }
  460. return
  461. }
  462. func GetWeight(length int) []int {
  463. steep := 10
  464. intArr := make([]int, 0)
  465. for i := 1; i <= length; i++ {
  466. if i == 1 {
  467. intArr = append(intArr, 1)
  468. } else {
  469. min := GetArrSum(intArr)
  470. maxVal := utils.GetRandInt(min, min+steep)
  471. intArr = append(intArr, maxVal)
  472. }
  473. }
  474. //数组排序
  475. sort.Slice(intArr, func(i, j int) bool {
  476. return intArr[i] > intArr[j]
  477. })
  478. return intArr
  479. }
  480. func GetArrSum(intArr []int) (sum int) {
  481. for _, val := range intArr {
  482. //累计求和
  483. sum += val
  484. }
  485. return
  486. }
  487. func EsMultiMatchFunctionScoreQuerySort(indexName, keyWord string, startSize, pageSize, userId int, orderColumn string) (result []*models.SearchItem, total int64, err error) {
  488. client := utils.Client
  489. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  490. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  491. //artidArr := make([]elastic.Query, 0)
  492. //matchArr := make([]elastic.Query, 0)
  493. n := 0
  494. keyWordLen := len(keyWordArr)
  495. if keyWordLen <= 0 {
  496. keyWordArr = append(keyWordArr, keyWord)
  497. keyWordLen = len(keyWordArr)
  498. }
  499. // @Param OrderColumn query int true "排序字段 ,Comprehensive综合 ,Matching匹配度 ,PublishDate 发布时间 "
  500. utils.FileLog.Info("SearchKeyWord:%s, userId:%s", keyWordArr, strconv.Itoa(userId))
  501. //keyWordWeight := GetWeight(keyWordLen)
  502. for _, v := range keyWordArr {
  503. if v != "" {
  504. matchArr := make([]elastic.Query, 0)
  505. boolquery := elastic.NewBoolQuery()
  506. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  507. bodyFunctionQuery2 := elastic.NewFunctionScoreQuery()
  508. bodyFunctionQuery3 := elastic.NewFunctionScoreQuery()
  509. //multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText").Analyzer("ik_smart")
  510. multiMatch := elastic.NewMultiMatchQuery(v, "Title").Analyzer("ik_smart").Boost(100)
  511. bodyFunctionQuery.Query(multiMatch)
  512. matchArr = append(matchArr, bodyFunctionQuery)
  513. multiMatch = elastic.NewMultiMatchQuery(v, "BodyText").Analyzer("ik_smart").Boost(1)
  514. bodyFunctionQuery2.Query(multiMatch)
  515. matchArr = append(matchArr, bodyFunctionQuery2)
  516. //multiMatch = elastic.NewMultiMatchQuery(1, "IsSummary")
  517. bodyFunctionQuery3.Query(multiMatch)
  518. matchArr = append(matchArr, bodyFunctionQuery3)
  519. boolquery.Should(matchArr...)
  520. //multiMatch = elastic.NewMultiMatchQuery(v, "BodyText").Analyzer("ik_smart")
  521. //bodyFunctionQuery.Query(multiMatch)
  522. //matchArr = append(matchArr, bodyFunctionQuery)
  523. //boolquery.Should(matchArr...)
  524. highlight := elastic.NewHighlight()
  525. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  526. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  527. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).From(0).Size(pageSize).Query(boolquery)
  528. if orderColumn == "Matching" {
  529. request = client.Search(indexName).Highlight(highlight).From(0).Size(pageSize).Query(boolquery)
  530. }
  531. searchByMatch, err := request.Do(context.Background())
  532. if err != nil {
  533. return nil, 0, err
  534. }
  535. if searchByMatch != nil {
  536. if searchByMatch.Hits != nil {
  537. for _, v := range searchByMatch.Hits.Hits {
  538. var isAppend bool
  539. articleJson, err := v.Source.MarshalJSON()
  540. if err != nil {
  541. return nil, 0, err
  542. }
  543. article := new(models.CygxArticleEs)
  544. err = json.Unmarshal(articleJson, &article)
  545. if err != nil {
  546. return nil, 0, err
  547. }
  548. searchItem := new(models.SearchItem)
  549. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  550. if len(v.Highlight["BodyText"]) > 0 {
  551. searchItem.Body = v.Highlight["BodyText"]
  552. } else {
  553. bodyRune := []rune(article.BodyText)
  554. bodyRuneLen := len(bodyRune)
  555. if bodyRuneLen > 100 {
  556. bodyRuneLen = 100
  557. }
  558. body := string(bodyRune[:bodyRuneLen])
  559. searchItem.Body = []string{body}
  560. }
  561. var title string
  562. if len(v.Highlight["Title"]) > 0 {
  563. title = v.Highlight["Title"][0]
  564. } else {
  565. title = article.Title
  566. }
  567. searchItem.Title = title
  568. searchItem.PublishDate = article.PublishDate
  569. searchItem.ExpertBackground = article.ExpertBackground
  570. searchItem.CategoryId = article.CategoryId
  571. for _, v_result := range result {
  572. if v_result.ArticleId == searchItem.ArticleId {
  573. isAppend = true
  574. }
  575. }
  576. if !isAppend {
  577. result = append(result, searchItem)
  578. }
  579. }
  580. }
  581. //total += searchByMatch.Hits.TotalHits.Value
  582. }
  583. }
  584. n++
  585. }
  586. total = int64(len(result))
  587. return
  588. }
  589. func EsMultiMatchFunctionScoreQueryTimeSort(indexName, keyWord string, startSize, pageSize, userId int) (result []*models.SearchItem, total int64, err error) {
  590. client := utils.Client
  591. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  592. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  593. boolquery := elastic.NewBoolQuery()
  594. matchArr := make([]elastic.Query, 0)
  595. //matchArr2 := make([]elastic.Query, 0)
  596. n := 0
  597. keyWordLen := len(keyWordArr)
  598. if keyWordLen <= 0 {
  599. keyWordArr = append(keyWordArr, keyWord)
  600. keyWordLen = len(keyWordArr)
  601. }
  602. utils.FileLog.Info("SearchKeyWord:%s, userId:%s", keyWordArr, strconv.Itoa(userId))
  603. for _, v := range keyWordArr {
  604. if v != "" {
  605. multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText")
  606. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  607. bodyFunctionQuery.Query(multiMatch)
  608. matchArr = append(matchArr, bodyFunctionQuery)
  609. }
  610. n++
  611. }
  612. boolquery.Should(matchArr...)
  613. highlight := elastic.NewHighlight()
  614. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  615. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  616. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).Size(pageSize).Query(boolquery)
  617. searchByMatch, err := request.Do(context.Background())
  618. if searchByMatch != nil {
  619. matchResult, _ := json.Marshal(searchByMatch)
  620. utils.FileLog.Info("%s", string(matchResult))
  621. fmt.Println(len(searchByMatch.Hits.Hits))
  622. if searchByMatch.Hits != nil {
  623. for _, v := range searchByMatch.Hits.Hits {
  624. articleJson, err := v.Source.MarshalJSON()
  625. utils.FileLog.Info("%s", string(articleJson))
  626. if err != nil {
  627. return nil, 0, err
  628. }
  629. article := new(models.CygxArticleEs)
  630. err = json.Unmarshal(articleJson, &article)
  631. if err != nil {
  632. return nil, 0, err
  633. }
  634. searchItem := new(models.SearchItem)
  635. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  636. if len(v.Highlight["BodyText"]) > 0 {
  637. searchItem.Body = v.Highlight["BodyText"]
  638. } else {
  639. bodyRune := []rune(article.BodyText)
  640. bodyRuneLen := len(bodyRune)
  641. if bodyRuneLen > 100 {
  642. bodyRuneLen = 100
  643. }
  644. body := string(bodyRune[:bodyRuneLen])
  645. searchItem.Body = []string{body}
  646. }
  647. var title string
  648. if len(v.Highlight["Title"]) > 0 {
  649. title = v.Highlight["Title"][0]
  650. } else {
  651. title = article.Title
  652. }
  653. searchItem.Title = title
  654. searchItem.PublishDate = article.PublishDate
  655. searchItem.ExpertBackground = article.ExpertBackground
  656. searchItem.CategoryId = article.CategoryId
  657. result = append(result, searchItem)
  658. }
  659. }
  660. total = searchByMatch.Hits.TotalHits.Value
  661. }
  662. return
  663. }
  664. func EsSearchReport(indexName, keyWord string, startSize, pageSize, userId int) (result []*models.SearchItem, total int64, err error) {
  665. client := utils.Client
  666. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  667. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  668. n := 0
  669. keyWordLen := len(keyWordArr)
  670. if keyWordLen <= 0 {
  671. keyWordArr = append(keyWordArr, keyWord)
  672. keyWordLen = len(keyWordArr)
  673. }
  674. for _, v := range keyWordArr {
  675. fmt.Println(v)
  676. }
  677. utils.FileLog.Info("SearchKeyWord:%s, userId:%s", keyWordArr, strconv.Itoa(userId))
  678. for _, v := range keyWordArr {
  679. if v != "" {
  680. matchArr := make([]elastic.Query, 0)
  681. boolquery := elastic.NewBoolQuery()
  682. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  683. bodyFunctionQuery2 := elastic.NewFunctionScoreQuery()
  684. multiMatch := elastic.NewMultiMatchQuery(v, "Title").Analyzer("ik_smart")
  685. bodyFunctionQuery.Query(multiMatch)
  686. matchArr = append(matchArr, bodyFunctionQuery)
  687. multiMatch = elastic.NewMultiMatchQuery(1, "IsReport")
  688. bodyFunctionQuery2.Query(multiMatch)
  689. matchArr = append(matchArr, bodyFunctionQuery2)
  690. boolquery.Must(matchArr...)
  691. highlight := elastic.NewHighlight()
  692. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  693. highlight = highlight.Fields(elastic.NewHighlighterField("Title"))
  694. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).From(0).Size(pageSize).Query(boolquery)
  695. searchByMatch, err := request.Do(context.Background())
  696. if err != nil {
  697. return nil, 0, err
  698. }
  699. if searchByMatch != nil {
  700. if searchByMatch.Hits != nil {
  701. for _, v := range searchByMatch.Hits.Hits {
  702. var isAppend bool
  703. articleJson, err := v.Source.MarshalJSON()
  704. if err != nil {
  705. return nil, 0, err
  706. }
  707. article := new(models.CygxArticleEs)
  708. err = json.Unmarshal(articleJson, &article)
  709. if err != nil {
  710. return nil, 0, err
  711. }
  712. searchItem := new(models.SearchItem)
  713. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  714. var title string
  715. if len(v.Highlight["Title"]) > 0 {
  716. title = v.Highlight["Title"][0]
  717. } else {
  718. title = article.Title
  719. }
  720. searchItem.Title = title
  721. searchItem.PublishDate = article.PublishDate
  722. for _, v_result := range result {
  723. if v_result.ArticleId == searchItem.ArticleId {
  724. isAppend = true
  725. }
  726. }
  727. if !isAppend {
  728. result = append(result, searchItem)
  729. }
  730. }
  731. }
  732. }
  733. }
  734. n++
  735. }
  736. total = int64(len(result))
  737. return
  738. }
  739. // 分页
  740. func EsMultiMatchFunctionScoreQueryTimeSortPage(indexName, keyWord string, startSize, pageSize, userId int) (result []*models.SearchItem, total int64, err error) {
  741. client := utils.Client
  742. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  743. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  744. boolquery := elastic.NewBoolQuery()
  745. matchArr := make([]elastic.Query, 0)
  746. n := 0
  747. keyWordLen := len(keyWordArr)
  748. if keyWordLen <= 0 {
  749. keyWordArr = append(keyWordArr, keyWord)
  750. keyWordLen = len(keyWordArr)
  751. }
  752. for _, v := range keyWordArr {
  753. if v != "" {
  754. multiMatch := elastic.NewMultiMatchQuery(v, "Title", "BodyText")
  755. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  756. bodyFunctionQuery.Query(multiMatch)
  757. matchArr = append(matchArr, bodyFunctionQuery)
  758. }
  759. n++
  760. }
  761. boolquery.Should(matchArr...)
  762. highlight := elastic.NewHighlight()
  763. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  764. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  765. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).From(startSize).Size(pageSize).Query(boolquery)
  766. searchByMatch, err := request.Do(context.Background())
  767. if searchByMatch != nil {
  768. if searchByMatch.Hits != nil {
  769. for _, v := range searchByMatch.Hits.Hits {
  770. articleJson, err := v.Source.MarshalJSON()
  771. if err != nil {
  772. return nil, 0, err
  773. }
  774. article := new(models.CygxArticleEs)
  775. err = json.Unmarshal(articleJson, &article)
  776. if err != nil {
  777. return nil, 0, err
  778. }
  779. searchItem := new(models.SearchItem)
  780. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  781. if len(v.Highlight["BodyText"]) > 0 {
  782. searchItem.Body = v.Highlight["BodyText"]
  783. } else {
  784. bodyRune := []rune(article.BodyText)
  785. bodyRuneLen := len(bodyRune)
  786. if bodyRuneLen > 100 {
  787. bodyRuneLen = 100
  788. }
  789. body := string(bodyRune[:bodyRuneLen])
  790. searchItem.Body = []string{body}
  791. }
  792. var title string
  793. if len(v.Highlight["Title"]) > 0 {
  794. title = v.Highlight["Title"][0]
  795. } else {
  796. title = article.Title
  797. }
  798. searchItem.Title = title
  799. searchItem.PublishDate = article.PublishDate
  800. searchItem.ExpertBackground = article.ExpertBackground
  801. searchItem.CategoryId = article.CategoryId
  802. result = append(result, searchItem)
  803. }
  804. }
  805. total = searchByMatch.Hits.TotalHits.Value
  806. }
  807. return
  808. }
  809. func EsMultiMatchFunctionScoreQuerySortPage(indexName, keyWord string, startSize, pageSize, userId int, orderColumn string) (result []*models.SearchItem, total int64, err error) {
  810. client := utils.Client
  811. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  812. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  813. keyWordLen := len(keyWordArr)
  814. if keyWordLen <= 0 {
  815. keyWordArr = append(keyWordArr, keyWord)
  816. keyWordLen = len(keyWordArr)
  817. }
  818. var keyWords string
  819. for _, v := range keyWordArr {
  820. keyWords += v + " "
  821. }
  822. // @Param OrderColumn query int true "排序字段 ,Comprehensive综合 ,Matching匹配度 ,PublishDate 发布时间 "
  823. //keyWordWeight := GetWeight(keyWordLen)
  824. matchArr := make([]elastic.Query, 0)
  825. boolquery := elastic.NewBoolQuery()
  826. bodyFunctionQuery := elastic.NewFunctionScoreQuery()
  827. bodyFunctionQuery2 := elastic.NewFunctionScoreQuery()
  828. bodyFunctionQuery3 := elastic.NewFunctionScoreQuery()
  829. multiMatch := elastic.NewMultiMatchQuery(keyWords, "Title").Analyzer("ik_smart").Boost(100)
  830. bodyFunctionQuery.Query(multiMatch)
  831. matchArr = append(matchArr, bodyFunctionQuery)
  832. multiMatch = elastic.NewMultiMatchQuery(keyWords, "BodyText").Analyzer("ik_smart").Boost(1)
  833. bodyFunctionQuery2.Query(multiMatch)
  834. matchArr = append(matchArr, bodyFunctionQuery2)
  835. bodyFunctionQuery3.Query(multiMatch)
  836. matchArr = append(matchArr, bodyFunctionQuery3)
  837. boolquery.Should(matchArr...)
  838. highlight := elastic.NewHighlight()
  839. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  840. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  841. request := client.Search(indexName).Highlight(highlight).Sort("PublishDate", false).From(startSize).Size(pageSize).Query(boolquery)
  842. if orderColumn == "Matching" {
  843. request = client.Search(indexName).Highlight(highlight).From(startSize).Size(pageSize).Query(boolquery)
  844. }
  845. searchByMatch, err := request.Do(context.Background())
  846. if err != nil {
  847. return nil, 0, err
  848. }
  849. if searchByMatch != nil {
  850. if searchByMatch.Hits != nil {
  851. for _, v := range searchByMatch.Hits.Hits {
  852. var isAppend bool
  853. articleJson, err := v.Source.MarshalJSON()
  854. if err != nil {
  855. return nil, 0, err
  856. }
  857. article := new(models.CygxArticleEs)
  858. err = json.Unmarshal(articleJson, &article)
  859. if err != nil {
  860. return nil, 0, err
  861. }
  862. searchItem := new(models.SearchItem)
  863. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  864. if len(v.Highlight["BodyText"]) > 0 {
  865. searchItem.Body = v.Highlight["BodyText"]
  866. } else {
  867. bodyRune := []rune(article.BodyText)
  868. bodyRuneLen := len(bodyRune)
  869. if bodyRuneLen > 100 {
  870. bodyRuneLen = 100
  871. }
  872. body := string(bodyRune[:bodyRuneLen])
  873. searchItem.Body = []string{body}
  874. }
  875. var title string
  876. if len(v.Highlight["Title"]) > 0 {
  877. title = v.Highlight["Title"][0]
  878. } else {
  879. title = article.Title
  880. }
  881. searchItem.Title = title
  882. searchItem.PublishDate = article.PublishDate
  883. searchItem.ExpertBackground = article.ExpertBackground
  884. searchItem.CategoryId = article.CategoryId
  885. for _, v_result := range result {
  886. if v_result.ArticleId == searchItem.ArticleId {
  887. isAppend = true
  888. }
  889. }
  890. if !isAppend {
  891. result = append(result, searchItem)
  892. }
  893. }
  894. }
  895. }
  896. total += searchByMatch.Hits.TotalHits.Value
  897. return
  898. }
  899. //func init23423() {
  900. // EsArticleSearch("立高食品", 0, 10, "34")
  901. //}
  902. func EsArticleSearch(keyWord string, startSize, pageSize int, orderColumn string, ikType int) (result []*models.SearchItem, total int64, err error) {
  903. indexName := utils.IndexName
  904. client := utils.Client
  905. keyWordArr, err := GetIndustryMapNameSliceV3(keyWord)
  906. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  907. keyWordLen := len(keyWordArr)
  908. if keyWordLen <= 0 {
  909. keyWordArr = append(keyWordArr, keyWord)
  910. keyWordLen = len(keyWordArr)
  911. }
  912. fmt.Println(keyWordArr)
  913. //如果没有联想词,而且查询的还是联想词就返回
  914. if ikType == 2 && keyWordLen == 1 {
  915. return
  916. }
  917. //Es 的高级查询有 自定义排序 文档一时半会儿撸不懂,先做多次查询手动过滤 2023.2.2
  918. //ikType 查询方式 ,0:查所有 、 1:查询键入词 、 2:查询除了查询键入词之外的联想词
  919. mustMap := make([]interface{}, 0)
  920. shouldMap := make(map[string]interface{}, 0)
  921. shouldMapquery := make([]interface{}, 0)
  922. mustNotMap := make([]interface{}, 0)
  923. shouldNotMap := make(map[string]interface{}, 0)
  924. shouldNotMapquery := make([]interface{}, 0)
  925. // @Param OrderColumn query int true "排序字段 ,Comprehensive综合 ,Matching匹配度 ,PublishDate 发布时间 "
  926. //keyWordWeight := GetWeight(keyWordLen)
  927. var boost int
  928. //lenkeyWordArr := len(keyWordArr)
  929. for k, v := range keyWordArr {
  930. if k == 0 {
  931. boost = 2 * 1000
  932. } else {
  933. boost = 1
  934. }
  935. //如果是 2:查询除了查询键入词之外的联想词
  936. if k == 0 && ikType == 2 {
  937. if v != "" {
  938. shouldNotMapquery = append(shouldNotMapquery, map[string]interface{}{
  939. "function_score": map[string]interface{}{
  940. "query": map[string]interface{}{
  941. "multi_match": map[string]interface{}{
  942. //"boost": (lenkeyWordArr - k) * boost, //给查询的值赋予权重
  943. "boost": boost, //给查询的值赋予权重
  944. "fields": []interface{}{"Title"},
  945. "query": v,
  946. },
  947. },
  948. },
  949. })
  950. shouldNotMapquery = append(shouldNotMapquery, map[string]interface{}{
  951. "function_score": map[string]interface{}{
  952. "query": map[string]interface{}{
  953. "multi_match": map[string]interface{}{
  954. "boost": boost, //给查询的值赋予权重
  955. "fields": []interface{}{"Abstract"},
  956. "query": v,
  957. },
  958. },
  959. },
  960. })
  961. shouldNotMapquery = append(shouldNotMapquery, map[string]interface{}{
  962. "function_score": map[string]interface{}{
  963. "query": map[string]interface{}{
  964. "multi_match": map[string]interface{}{
  965. "boost": boost, //给查询的值赋予权重
  966. "fields": []interface{}{"Annotation"},
  967. "query": v,
  968. },
  969. },
  970. },
  971. })
  972. shouldNotMapquery = append(shouldNotMapquery, map[string]interface{}{
  973. "function_score": map[string]interface{}{
  974. "query": map[string]interface{}{
  975. "multi_match": map[string]interface{}{
  976. //"boost": (lenkeyWordArr-k)*boost - 1, //给查询的值赋予权重
  977. "boost": boost, //给查询的值赋予权重
  978. "fields": []interface{}{"BodyText"},
  979. "query": v,
  980. },
  981. },
  982. },
  983. })
  984. }
  985. continue
  986. }
  987. //如果是 1:查询键入词
  988. if k > 0 && ikType == 1 {
  989. continue
  990. }
  991. if v != "" {
  992. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  993. "function_score": map[string]interface{}{
  994. "query": map[string]interface{}{
  995. "multi_match": map[string]interface{}{
  996. //"boost": (lenkeyWordArr - k) * boost, //给查询的值赋予权重
  997. "boost": boost, //给查询的值赋予权重
  998. "fields": []interface{}{"Title"},
  999. "query": v,
  1000. },
  1001. },
  1002. },
  1003. })
  1004. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  1005. "function_score": map[string]interface{}{
  1006. "query": map[string]interface{}{
  1007. "multi_match": map[string]interface{}{
  1008. "boost": boost, //给查询的值赋予权重
  1009. "fields": []interface{}{"Abstract"},
  1010. "query": v,
  1011. },
  1012. },
  1013. },
  1014. })
  1015. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  1016. "function_score": map[string]interface{}{
  1017. "query": map[string]interface{}{
  1018. "multi_match": map[string]interface{}{
  1019. "boost": boost, //给查询的值赋予权重
  1020. "fields": []interface{}{"Annotation"},
  1021. "query": v,
  1022. },
  1023. },
  1024. },
  1025. })
  1026. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  1027. "function_score": map[string]interface{}{
  1028. "query": map[string]interface{}{
  1029. "multi_match": map[string]interface{}{
  1030. //"boost": (lenkeyWordArr-k)*boost - 1, //给查询的值赋予权重
  1031. "boost": boost, //给查询的值赋予权重
  1032. "fields": []interface{}{"BodyText"},
  1033. "query": v,
  1034. },
  1035. },
  1036. },
  1037. })
  1038. }
  1039. }
  1040. shouldMap = map[string]interface{}{
  1041. "should": shouldMapquery,
  1042. }
  1043. shouldNotMap = map[string]interface{}{
  1044. "should": shouldNotMapquery,
  1045. }
  1046. //排序
  1047. sortMap := make([]interface{}, 0)
  1048. //时间
  1049. sortMap = append(sortMap, map[string]interface{}{
  1050. "PublishDate": map[string]interface{}{
  1051. "order": "desc",
  1052. },
  1053. })
  1054. //sortMap = append(sortMap, map[string]interface{}{
  1055. // "_score": map[string]interface{}{
  1056. // "order": "desc",
  1057. // },
  1058. //})
  1059. //高亮
  1060. highlightMap := make(map[string]interface{}, 0)
  1061. highlightMap = map[string]interface{}{
  1062. "fields": map[string]interface{}{
  1063. "BodyText": map[string]interface{}{},
  1064. "Title": map[string]interface{}{},
  1065. "Abstract": map[string]interface{}{},
  1066. "Annotation": map[string]interface{}{},
  1067. },
  1068. //样式 红色
  1069. "post_tags": []interface{}{"</font>"},
  1070. "pre_tags": []interface{}{"<font color='red'>"},
  1071. "fragment_size": 50,
  1072. }
  1073. mustMap = append(mustMap, map[string]interface{}{
  1074. "bool": shouldMap,
  1075. })
  1076. mustNotMap = append(mustNotMap, map[string]interface{}{
  1077. "bool": shouldNotMap,
  1078. })
  1079. queryMap := map[string]interface{}{
  1080. "query": map[string]interface{}{
  1081. "bool": map[string]interface{}{
  1082. "must": mustMap,
  1083. },
  1084. },
  1085. }
  1086. //把第一次键入词的筛选条件过滤掉
  1087. if ikType == 2 {
  1088. queryMap = map[string]interface{}{
  1089. "query": map[string]interface{}{
  1090. "bool": map[string]interface{}{
  1091. "must": mustMap,
  1092. "must_not": mustNotMap,
  1093. },
  1094. },
  1095. }
  1096. }
  1097. if orderColumn == "Matching" {
  1098. queryMap["sort"] = sortMap
  1099. }
  1100. queryMap["from"] = startSize
  1101. queryMap["size"] = pageSize
  1102. queryMap["highlight"] = highlightMap
  1103. jsonBytes, _ := json.Marshal(queryMap)
  1104. fmt.Println(string(jsonBytes))
  1105. //utils.FileLog.Info(string(jsonBytes))
  1106. request := client.Search(indexName).Source(queryMap) // sets the JSON request
  1107. searchByMatch, err := request.Do(context.Background())
  1108. if searchByMatch != nil {
  1109. if searchByMatch.Hits != nil {
  1110. for _, v := range searchByMatch.Hits.Hits {
  1111. var isAppend bool
  1112. articleJson, err := v.Source.MarshalJSON()
  1113. if err != nil {
  1114. return nil, 0, err
  1115. }
  1116. article := new(models.CygxArticleEs)
  1117. err = json.Unmarshal(articleJson, &article)
  1118. if err != nil {
  1119. return nil, 0, err
  1120. }
  1121. searchItem := new(models.SearchItem)
  1122. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  1123. if len(v.Highlight["Annotation"]) > 0 {
  1124. for _, vText := range v.Highlight["Annotation"] {
  1125. searchItem.Body = append(searchItem.Body, vText)
  1126. }
  1127. }
  1128. if len(v.Highlight["Abstract"]) > 0 {
  1129. for _, vText := range v.Highlight["Abstract"] {
  1130. searchItem.Body = append(searchItem.Body, vText)
  1131. }
  1132. }
  1133. if len(v.Highlight["BodyText"]) > 0 {
  1134. for _, vText := range v.Highlight["BodyText"] {
  1135. searchItem.Body = append(searchItem.Body, vText)
  1136. }
  1137. }
  1138. if len(searchItem.Body) == 0 {
  1139. bodyRune := []rune(article.BodyText)
  1140. bodyRuneLen := len(bodyRune)
  1141. if bodyRuneLen > 100 {
  1142. bodyRuneLen = 100
  1143. }
  1144. body := string(bodyRune[:bodyRuneLen])
  1145. searchItem.Body = []string{body}
  1146. }
  1147. //if len(v.Highlight["BodyText"]) > 0 {
  1148. // searchItem.Body = v.Highlight["BodyText"]
  1149. //} else {
  1150. // bodyRune := []rune(article.BodyText)
  1151. // bodyRuneLen := len(bodyRune)
  1152. // if bodyRuneLen > 100 {
  1153. // bodyRuneLen = 100
  1154. // }
  1155. // body := string(bodyRune[:bodyRuneLen])
  1156. // searchItem.Body = []string{body}
  1157. //}
  1158. var title string
  1159. if len(v.Highlight["Title"]) > 0 {
  1160. title = v.Highlight["Title"][0]
  1161. } else {
  1162. title = article.Title
  1163. }
  1164. searchItem.Title = title
  1165. searchItem.PublishDate = article.PublishDate
  1166. searchItem.ExpertBackground = article.ExpertBackground
  1167. searchItem.CategoryId = article.CategoryId
  1168. for _, v_result := range result {
  1169. if v_result.ArticleId == searchItem.ArticleId {
  1170. isAppend = true
  1171. }
  1172. }
  1173. if !isAppend {
  1174. result = append(result, searchItem)
  1175. }
  1176. }
  1177. }
  1178. total = searchByMatch.Hits.TotalHits.Value
  1179. }
  1180. return
  1181. }
  1182. func EsArticleSearchBody(keyWord string, startSize, pageSize int, orderColumn string, searchType int) (result []*models.SearchItem, total int64, err error) {
  1183. if keyWord == "" {
  1184. return
  1185. }
  1186. indexName := utils.IndexName
  1187. client := utils.Client
  1188. //Es 的高级查询有 自定义排序 文档一时半会儿撸不懂,先做多次查询手动过滤 2023.2.2
  1189. //ikType 查询方式 ,0:查所有 、 1:查询键入词 、 2:查询除了查询键入词之外的联想词
  1190. mustMap := make([]interface{}, 0)
  1191. shouldMap := make(map[string]interface{}, 0)
  1192. shouldMapquery := make([]interface{}, 0)
  1193. mustNotMap := make([]interface{}, 0)
  1194. shouldNotMap := make(map[string]interface{}, 0)
  1195. shouldNotMapquery := make([]interface{}, 0)
  1196. // @Param OrderColumn query int true "排序字段 ,Comprehensive综合 ,Matching匹配度 ,PublishDate 发布时间 "
  1197. //keyWordWeight := GetWeight(keyWordLen)
  1198. var boost int
  1199. //如果是 2:查询标题,摘要,核心观点的词
  1200. if searchType == 1 {
  1201. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  1202. "function_score": map[string]interface{}{
  1203. "query": map[string]interface{}{
  1204. "multi_match": map[string]interface{}{
  1205. "boost": boost, //给查询的值赋予权重
  1206. "fields": []interface{}{"Title"},
  1207. "query": keyWord,
  1208. },
  1209. },
  1210. },
  1211. })
  1212. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  1213. "function_score": map[string]interface{}{
  1214. "query": map[string]interface{}{
  1215. "multi_match": map[string]interface{}{
  1216. "boost": boost, //给查询的值赋予权重
  1217. "fields": []interface{}{"Abstract"},
  1218. "query": keyWord,
  1219. },
  1220. },
  1221. },
  1222. })
  1223. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  1224. "function_score": map[string]interface{}{
  1225. "query": map[string]interface{}{
  1226. "multi_match": map[string]interface{}{
  1227. "boost": boost, //给查询的值赋予权重
  1228. "fields": []interface{}{"Annotation"},
  1229. "query": keyWord,
  1230. },
  1231. },
  1232. },
  1233. })
  1234. }
  1235. //如果是 2:查询body的相关词
  1236. if searchType == 2 {
  1237. shouldNotMapquery = append(shouldNotMapquery, map[string]interface{}{
  1238. "function_score": map[string]interface{}{
  1239. "query": map[string]interface{}{
  1240. "multi_match": map[string]interface{}{
  1241. "boost": boost, //给查询的值赋予权重
  1242. "fields": []interface{}{"Title"},
  1243. "query": keyWord,
  1244. },
  1245. },
  1246. },
  1247. })
  1248. shouldNotMapquery = append(shouldNotMapquery, map[string]interface{}{
  1249. "function_score": map[string]interface{}{
  1250. "query": map[string]interface{}{
  1251. "multi_match": map[string]interface{}{
  1252. "boost": boost, //给查询的值赋予权重
  1253. "fields": []interface{}{"Abstract"},
  1254. "query": keyWord,
  1255. },
  1256. },
  1257. },
  1258. })
  1259. shouldNotMapquery = append(shouldNotMapquery, map[string]interface{}{
  1260. "function_score": map[string]interface{}{
  1261. "query": map[string]interface{}{
  1262. "multi_match": map[string]interface{}{
  1263. "boost": boost, //给查询的值赋予权重
  1264. "fields": []interface{}{"Annotation"},
  1265. "query": keyWord,
  1266. },
  1267. },
  1268. },
  1269. })
  1270. //shouldNotMapquery = append(shouldNotMapquery, map[string]interface{}{
  1271. // "function_score": map[string]interface{}{
  1272. // "query": map[string]interface{}{
  1273. // "multi_match": map[string]interface{}{
  1274. // //"boost": (lenkeyWordArr-k)*boost - 1, //给查询的值赋予权重
  1275. // "boost": boost, //给查询的值赋予权重
  1276. // "fields": []interface{}{"BodyText"},
  1277. // "query": keyWord,
  1278. // },
  1279. // },
  1280. // },
  1281. //})
  1282. shouldMapquery = append(shouldMapquery, map[string]interface{}{
  1283. "function_score": map[string]interface{}{
  1284. "query": map[string]interface{}{
  1285. "multi_match": map[string]interface{}{
  1286. //"boost": (lenkeyWordArr-k)*boost - 1, //给查询的值赋予权重
  1287. "boost": boost, //给查询的值赋予权重
  1288. "fields": []interface{}{"BodyText"},
  1289. "query": keyWord,
  1290. },
  1291. },
  1292. },
  1293. })
  1294. }
  1295. shouldMap = map[string]interface{}{
  1296. "should": shouldMapquery,
  1297. }
  1298. shouldNotMap = map[string]interface{}{
  1299. "should": shouldNotMapquery,
  1300. }
  1301. //排序
  1302. sortMap := make([]interface{}, 0)
  1303. //时间
  1304. sortMap = append(sortMap, map[string]interface{}{
  1305. "PublishDate": map[string]interface{}{
  1306. "order": "desc",
  1307. },
  1308. })
  1309. //高亮
  1310. highlightMap := make(map[string]interface{}, 0)
  1311. highlightMap = map[string]interface{}{
  1312. "fields": map[string]interface{}{
  1313. "BodyText": map[string]interface{}{},
  1314. "Title": map[string]interface{}{},
  1315. "Abstract": map[string]interface{}{},
  1316. "Annotation": map[string]interface{}{},
  1317. },
  1318. //样式 红色
  1319. "post_tags": []interface{}{"</font>"},
  1320. "pre_tags": []interface{}{"<font color='red'>"},
  1321. "fragment_size": 50,
  1322. }
  1323. mustMap = append(mustMap, map[string]interface{}{
  1324. "bool": shouldMap,
  1325. })
  1326. mustNotMap = append(mustNotMap, map[string]interface{}{
  1327. "bool": shouldNotMap,
  1328. })
  1329. queryMap := map[string]interface{}{
  1330. "query": map[string]interface{}{
  1331. "bool": map[string]interface{}{
  1332. "must": mustMap,
  1333. },
  1334. },
  1335. }
  1336. //把第一次的筛选条件过滤掉
  1337. if searchType == 2 {
  1338. queryMap = map[string]interface{}{
  1339. "query": map[string]interface{}{
  1340. "bool": map[string]interface{}{
  1341. "must": mustMap,
  1342. "must_not": mustNotMap,
  1343. },
  1344. },
  1345. }
  1346. }
  1347. if orderColumn == "Matching" {
  1348. queryMap["sort"] = sortMap
  1349. }
  1350. queryMap["from"] = startSize
  1351. queryMap["size"] = pageSize
  1352. queryMap["highlight"] = highlightMap
  1353. jsonBytes, _ := json.Marshal(queryMap)
  1354. fmt.Println(string(jsonBytes))
  1355. //utils.FileLog.Info(string(jsonBytes))
  1356. request := client.Search(indexName).Source(queryMap) // sets the JSON request
  1357. searchByMatch, err := request.Do(context.Background())
  1358. if searchByMatch != nil {
  1359. if searchByMatch.Hits != nil {
  1360. for _, v := range searchByMatch.Hits.Hits {
  1361. var isAppend bool
  1362. articleJson, err := v.Source.MarshalJSON()
  1363. if err != nil {
  1364. return nil, 0, err
  1365. }
  1366. article := new(models.CygxArticleEs)
  1367. err = json.Unmarshal(articleJson, &article)
  1368. if err != nil {
  1369. return nil, 0, err
  1370. }
  1371. searchItem := new(models.SearchItem)
  1372. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  1373. if len(v.Highlight["Annotation"]) > 0 {
  1374. for _, vText := range v.Highlight["Annotation"] {
  1375. searchItem.Body = append(searchItem.Body, vText)
  1376. }
  1377. }
  1378. if len(v.Highlight["Abstract"]) > 0 {
  1379. for _, vText := range v.Highlight["Abstract"] {
  1380. searchItem.Body = append(searchItem.Body, vText)
  1381. }
  1382. }
  1383. if len(v.Highlight["BodyText"]) > 0 {
  1384. for _, vText := range v.Highlight["BodyText"] {
  1385. searchItem.Body = append(searchItem.Body, vText)
  1386. }
  1387. }
  1388. if len(searchItem.Body) == 0 {
  1389. bodyRune := []rune(article.BodyText)
  1390. bodyRuneLen := len(bodyRune)
  1391. if bodyRuneLen > 100 {
  1392. bodyRuneLen = 100
  1393. }
  1394. body := string(bodyRune[:bodyRuneLen])
  1395. searchItem.Body = []string{body}
  1396. }
  1397. //if len(v.Highlight["BodyText"]) > 0 {
  1398. // searchItem.Body = v.Highlight["BodyText"]
  1399. //} else {
  1400. // bodyRune := []rune(article.BodyText)
  1401. // bodyRuneLen := len(bodyRune)
  1402. // if bodyRuneLen > 100 {
  1403. // bodyRuneLen = 100
  1404. // }
  1405. // body := string(bodyRune[:bodyRuneLen])
  1406. // searchItem.Body = []string{body}
  1407. //}
  1408. var title string
  1409. if len(v.Highlight["Title"]) > 0 {
  1410. title = v.Highlight["Title"][0]
  1411. } else {
  1412. title = article.Title
  1413. }
  1414. searchItem.Title = title
  1415. searchItem.PublishDate = article.PublishDate
  1416. searchItem.ExpertBackground = article.ExpertBackground
  1417. searchItem.CategoryId = article.CategoryId
  1418. for _, v_result := range result {
  1419. if v_result.ArticleId == searchItem.ArticleId {
  1420. isAppend = true
  1421. }
  1422. }
  1423. if !isAppend {
  1424. result = append(result, searchItem)
  1425. }
  1426. }
  1427. }
  1428. total = searchByMatch.Hits.TotalHits.Value
  1429. }
  1430. return
  1431. }