elastic.go 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207
  1. package elastic
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "eta/eta_api/models"
  7. "eta/eta_api/models/data_manage"
  8. "eta/eta_api/models/data_manage/excel"
  9. dataSourceModel "eta/eta_api/models/data_source"
  10. "eta/eta_api/utils"
  11. "fmt"
  12. "github.com/olivere/elastic/v7"
  13. "strconv"
  14. "strings"
  15. )
  16. // indexName:索引名称
  17. // mappingJson:表结构
  18. func EsCreateIndex(indexName, mappingJson string) (err error) {
  19. client := utils.EsClient
  20. //定义表结构
  21. exists, err := client.IndexExists(indexName).Do(context.Background()) //<5>
  22. if err != nil {
  23. return
  24. }
  25. if !exists {
  26. resp, err := client.CreateIndex(indexName).BodyJson(mappingJson).Do(context.Background())
  27. //BodyJson(bodyJson).Do(context.Background())
  28. if err != nil {
  29. fmt.Println("CreateIndex Err:" + err.Error())
  30. return err
  31. }
  32. fmt.Println(resp.Index, resp.ShardsAcknowledged, resp.Acknowledged)
  33. } else {
  34. fmt.Println(indexName + " 已存在")
  35. }
  36. return
  37. }
  38. // 删除数据
  39. func EsDeleteData(indexName, docId string) (err error) {
  40. client := utils.EsClient
  41. resp, err := client.Delete().Index(indexName).Id(docId).Do(context.Background())
  42. fmt.Println(resp)
  43. if err != nil {
  44. return
  45. }
  46. if resp.Status == 0 {
  47. fmt.Println("删除成功")
  48. } else {
  49. fmt.Println("AddData", resp.Status, resp.Result)
  50. }
  51. return
  52. }
  53. func MappingModify(indexName, mappingJson string) {
  54. client := utils.EsClient
  55. result, err := client.PutMapping().Index(indexName).BodyString(mappingJson).Do(context.Background())
  56. fmt.Println(err)
  57. fmt.Println(result)
  58. return
  59. }
  60. // EsAddOrEditEdbInfoData 新增/修改es中的指标数据
  61. func EsAddOrEditEdbInfoData(indexName, docId string, item *data_manage.EdbInfoList) (err error) {
  62. defer func() {
  63. if err != nil {
  64. fmt.Println("EsAddOrEditData Err:", err.Error())
  65. }
  66. }()
  67. client := utils.EsClient
  68. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Refresh("true").Do(context.Background())
  69. if err != nil {
  70. fmt.Println("新增失败:", err.Error())
  71. return err
  72. }
  73. fmt.Println(resp)
  74. if resp.Status == 0 {
  75. fmt.Println("新增成功", resp.Result)
  76. err = nil
  77. } else {
  78. fmt.Println("AddData", resp.Status, resp.Result)
  79. }
  80. return
  81. }
  82. // SearchEdbInfoData 查询es中的指标数据
  83. func SearchEdbInfoData(indexName, keywordStr string, from, size, filterSource, source int, edbInfoType int8, frequency string, noPermissionEdbInfoIdList []int) (total int64, list []*data_manage.EdbInfoList, err error) {
  84. list = make([]*data_manage.EdbInfoList, 0)
  85. defer func() {
  86. if err != nil {
  87. fmt.Println("EsAddOrEditData Err:", err.Error())
  88. }
  89. }()
  90. highlight := elastic.NewHighlight()
  91. highlight = highlight.Fields(elastic.NewHighlighterField("EdbCode"), elastic.NewHighlighterField("EdbName"))
  92. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  93. //var source map[string]interface{}
  94. //source := map[string]interface{}{
  95. // "query": map[string]interface{}{
  96. // "match_all": map[string]interface{}{},
  97. // },
  98. //}
  99. mustMap := make([]interface{}, 0)
  100. mustNotMap := make([]interface{}, 0)
  101. //source := map[string]interface{}{
  102. // "query": map[string]interface{}{
  103. // "bool": map[string]interface{}{
  104. // "must": map[string]interface{}{
  105. // "query_string": map[string]interface{}{
  106. // "query": keywordStr,
  107. // "fields": []string{"EdbCode", "EdbName"},
  108. // },
  109. // },
  110. // },
  111. // },
  112. //}
  113. switch filterSource {
  114. case 2:
  115. //source = map[string]interface{}{
  116. // "query": map[string]interface{}{
  117. // "bool": map[string]interface{}{
  118. // "must": map[string]interface{}{
  119. // "query_string": map[string]interface{}{
  120. // "query": keywordStr,
  121. // },
  122. // },
  123. // "filter": []interface{}{
  124. // map[string]interface{}{
  125. // "term": map[string]interface{}{
  126. // "Frequency.keyword": "月度",
  127. // },
  128. // }},
  129. // },
  130. // },
  131. //}
  132. mustMap = []interface{}{
  133. map[string]interface{}{
  134. "term": map[string]interface{}{
  135. "Frequency.keyword": "月度",
  136. //"Frequency.keyword": "月度",
  137. },
  138. },
  139. }
  140. case 3:
  141. //source = map[string]interface{}{
  142. // "query": map[string]interface{}{
  143. // "bool": map[string]interface{}{
  144. // "must": map[string]interface{}{
  145. // "query_string": map[string]interface{}{
  146. // "query": keywordStr,
  147. // },
  148. // },
  149. // "must_not": []interface{}{
  150. // map[string]interface{}{
  151. // "match": map[string]interface{}{
  152. // "Frequency.keyword": "日度",
  153. // },
  154. // }},
  155. // },
  156. // },
  157. //}
  158. ////注释掉,所有频度都可以变频 2022-08-31 14:31:28
  159. //mustNotMap = []interface{}{
  160. // map[string]interface{}{
  161. // "match": map[string]interface{}{
  162. // "Frequency.keyword": "日度",
  163. // //"Frequency.keyword": "月度",
  164. // },
  165. // },
  166. //}
  167. case 4:
  168. //source = map[string]interface{}{
  169. // "query": map[string]interface{}{
  170. // "bool": map[string]interface{}{
  171. // "must": map[string]interface{}{
  172. // "query_string": map[string]interface{}{
  173. // "query": keywordStr,
  174. // },
  175. // },
  176. // "filter": []interface{}{
  177. // map[string]interface{}{
  178. // "term": map[string]interface{}{
  179. // "EdbType": 1,
  180. // },
  181. // }},
  182. // },
  183. // },
  184. //}
  185. mustMap = []interface{}{
  186. map[string]interface{}{
  187. "term": map[string]interface{}{
  188. "EdbType": 1,
  189. },
  190. },
  191. }
  192. case 5:
  193. mustMap = []interface{}{
  194. map[string]interface{}{
  195. "term": map[string]interface{}{
  196. "Source": 6,
  197. },
  198. },
  199. }
  200. case 6:
  201. mustNotMap = []interface{}{
  202. map[string]interface{}{
  203. "match": map[string]interface{}{
  204. "Frequency.keyword": "年度",
  205. },
  206. },
  207. }
  208. }
  209. //指标来源
  210. if source > 0 {
  211. mustMap = append(mustMap, map[string]interface{}{
  212. "term": map[string]interface{}{
  213. "Source": source,
  214. //"Frequency.keyword": "月度",
  215. },
  216. })
  217. }
  218. if frequency != "" {
  219. mustMap = append(mustMap, map[string]interface{}{
  220. "term": map[string]interface{}{
  221. "Frequency.keyword": frequency,
  222. //"Frequency.keyword": "月度",
  223. },
  224. })
  225. }
  226. // noPermissionEdbInfoIdList 无权限指标id
  227. if len(noPermissionEdbInfoIdList) > 0 {
  228. mustNotMap = append(mustNotMap, map[string]interface{}{
  229. "terms": map[string]interface{}{
  230. "EdbInfoId": noPermissionEdbInfoIdList,
  231. //"Frequency.keyword": "月度",
  232. },
  233. })
  234. }
  235. // 指标类型:普通指标、预测指标(小于0 代表不区分指标是普通还是预测)
  236. if edbInfoType >= 0 {
  237. mustMap = append(mustMap, map[string]interface{}{
  238. "term": map[string]interface{}{
  239. "EdbInfoType": edbInfoType,
  240. },
  241. })
  242. }
  243. //普通指标
  244. //mustMap = append(mustMap, map[string]interface{}{
  245. // "term": map[string]interface{}{
  246. // "EdbInfoType": 0,
  247. // //"Frequency.keyword": "月度",
  248. // },
  249. //})
  250. //关键字匹配
  251. //shouldMap := map[string]interface{}{
  252. // "should": []interface{}{
  253. // map[string]interface{}{
  254. // "match": map[string]interface{}{
  255. // "EdbCode": keywordStr,
  256. // //"Frequency.keyword": "月度",
  257. // },
  258. // },
  259. // map[string]interface{}{
  260. // "match": map[string]interface{}{
  261. // "EdbName": keywordStr,
  262. // //"Frequency.keyword": "月度",
  263. // },
  264. // },
  265. // map[string]interface{}{
  266. // "match": map[string]interface{}{
  267. // "EdbNameEn": keywordStr,
  268. // //"Frequency.keyword": "月度",
  269. // },
  270. // },
  271. // },
  272. //}
  273. // 默认使用中文名字字段去匹配
  274. keywordNameKey := `EdbName`
  275. // 如果没有中文,则使用英文名称字段去匹配
  276. if !utils.ContainsChinese(keywordStr) {
  277. keywordNameKey = `EdbNameEn`
  278. }
  279. shouldMap := map[string]interface{}{
  280. "should": []interface{}{
  281. map[string]interface{}{
  282. "match": map[string]interface{}{
  283. "EdbCode": keywordStr,
  284. //"Frequency.keyword": "月度",
  285. },
  286. },
  287. map[string]interface{}{
  288. "match": map[string]interface{}{
  289. keywordNameKey: keywordStr,
  290. //"Frequency.keyword": "月度",
  291. },
  292. },
  293. },
  294. }
  295. //mustMap = append(mustMap, map[string]interface{}{
  296. // "bool": shouldMap,
  297. //})
  298. return searchEdbInfoData(indexName, mustMap, mustNotMap, shouldMap, from, size)
  299. }
  300. // SearchEdbInfoData 查询es中的指标数据
  301. func SearchEdbInfoDataByfrequency(indexName, keywordStr string, from, size int, edbInfoType int8, frequency []string, noPermissionEdbInfoIdList []int) (total int64, list []*data_manage.EdbInfoList, err error) {
  302. list = make([]*data_manage.EdbInfoList, 0)
  303. defer func() {
  304. if err != nil {
  305. fmt.Println("EsAddOrEditData Err:", err.Error())
  306. }
  307. }()
  308. mustMap := make([]interface{}, 0)
  309. mustNotMap := make([]interface{}, 0)
  310. if len(frequency) != 0 {
  311. mustMap = append(mustMap, map[string]interface{}{
  312. "terms": map[string]interface{}{
  313. "Frequency.keyword": frequency,
  314. //"Frequency.keyword": "月度",
  315. },
  316. })
  317. }
  318. // noPermissionEdbInfoIdList 无权限指标id
  319. if len(noPermissionEdbInfoIdList) > 0 {
  320. mustNotMap = append(mustNotMap, map[string]interface{}{
  321. "terms": map[string]interface{}{
  322. "EdbInfoId": noPermissionEdbInfoIdList,
  323. //"Frequency.keyword": "月度",
  324. },
  325. })
  326. }
  327. // 指标类型:普通指标、预测指标(小于0 代表不区分指标是普通还是预测)
  328. if edbInfoType >= 0 {
  329. mustMap = append(mustMap, map[string]interface{}{
  330. "term": map[string]interface{}{
  331. "EdbInfoType": edbInfoType,
  332. },
  333. })
  334. }
  335. // 默认使用中文名字字段去匹配
  336. keywordNameKey := `EdbName`
  337. // 如果没有中文,则使用英文名称字段去匹配
  338. if !utils.ContainsChinese(keywordStr) {
  339. keywordNameKey = `EdbNameEn`
  340. }
  341. shouldMap := map[string]interface{}{
  342. "should": []interface{}{
  343. map[string]interface{}{
  344. "match": map[string]interface{}{
  345. "EdbCode": keywordStr,
  346. //"Frequency.keyword": "月度",
  347. },
  348. },
  349. map[string]interface{}{
  350. "match": map[string]interface{}{
  351. keywordNameKey: keywordStr,
  352. //"Frequency.keyword": "月度",
  353. },
  354. },
  355. },
  356. }
  357. return searchEdbInfoData(indexName, mustMap, mustNotMap, shouldMap, from, size)
  358. }
  359. func SearchEdbInfoDataBak(indexName, keywordStr string, from, size, filterSource, source int, frequency string) (total int64, list []*data_manage.EdbInfoList, err error) {
  360. list = make([]*data_manage.EdbInfoList, 0)
  361. defer func() {
  362. if err != nil {
  363. fmt.Println("EsAddOrEditData Err:", err.Error())
  364. }
  365. }()
  366. client := utils.EsClient
  367. //queryString := elastic.NewQueryStringQuery(keywordStr)
  368. //boolQueryJson, err := json.Marshal(queryString)
  369. //if err != nil {
  370. // fmt.Println("boolQueryJson err:", err)
  371. //} else {
  372. // fmt.Println("boolQueryJson ", string(boolQueryJson))
  373. //}
  374. highlight := elastic.NewHighlight()
  375. highlight = highlight.Fields(elastic.NewHighlighterField("EdbCode"), elastic.NewHighlighterField("EdbName"))
  376. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  377. //query := elastic.RawStringQuery(`{"match_all":{}}`)
  378. //var source map[string]interface{}
  379. //source := map[string]interface{}{
  380. // "query": map[string]interface{}{
  381. // "match_all": map[string]interface{}{},
  382. // },
  383. //}
  384. mustMap := make([]interface{}, 0)
  385. mustNotMap := make([]interface{}, 0)
  386. //source := map[string]interface{}{
  387. // "query": map[string]interface{}{
  388. // "bool": map[string]interface{}{
  389. // "must": map[string]interface{}{
  390. // "query_string": map[string]interface{}{
  391. // "query": keywordStr,
  392. // "fields": []string{"EdbCode", "EdbName"},
  393. // },
  394. // },
  395. // },
  396. // },
  397. //}
  398. switch filterSource {
  399. case 2:
  400. //source = map[string]interface{}{
  401. // "query": map[string]interface{}{
  402. // "bool": map[string]interface{}{
  403. // "must": map[string]interface{}{
  404. // "query_string": map[string]interface{}{
  405. // "query": keywordStr,
  406. // },
  407. // },
  408. // "filter": []interface{}{
  409. // map[string]interface{}{
  410. // "term": map[string]interface{}{
  411. // "Frequency.keyword": "月度",
  412. // },
  413. // }},
  414. // },
  415. // },
  416. //}
  417. mustMap = []interface{}{
  418. map[string]interface{}{
  419. "term": map[string]interface{}{
  420. "Frequency.keyword": "月度",
  421. //"Frequency.keyword": "月度",
  422. },
  423. },
  424. }
  425. case 3:
  426. //source = map[string]interface{}{
  427. // "query": map[string]interface{}{
  428. // "bool": map[string]interface{}{
  429. // "must": map[string]interface{}{
  430. // "query_string": map[string]interface{}{
  431. // "query": keywordStr,
  432. // },
  433. // },
  434. // "must_not": []interface{}{
  435. // map[string]interface{}{
  436. // "match": map[string]interface{}{
  437. // "Frequency.keyword": "日度",
  438. // },
  439. // }},
  440. // },
  441. // },
  442. //}
  443. ////注释掉,所有频度都可以变频 2022-08-31 14:31:28
  444. //mustNotMap = []interface{}{
  445. // map[string]interface{}{
  446. // "match": map[string]interface{}{
  447. // "Frequency.keyword": "日度",
  448. // //"Frequency.keyword": "月度",
  449. // },
  450. // },
  451. //}
  452. case 4:
  453. //source = map[string]interface{}{
  454. // "query": map[string]interface{}{
  455. // "bool": map[string]interface{}{
  456. // "must": map[string]interface{}{
  457. // "query_string": map[string]interface{}{
  458. // "query": keywordStr,
  459. // },
  460. // },
  461. // "filter": []interface{}{
  462. // map[string]interface{}{
  463. // "term": map[string]interface{}{
  464. // "EdbType": 1,
  465. // },
  466. // }},
  467. // },
  468. // },
  469. //}
  470. mustMap = []interface{}{
  471. map[string]interface{}{
  472. "term": map[string]interface{}{
  473. "EdbType": 1,
  474. },
  475. },
  476. }
  477. case 5:
  478. mustMap = []interface{}{
  479. map[string]interface{}{
  480. "term": map[string]interface{}{
  481. "Source": 6,
  482. },
  483. },
  484. }
  485. case 6:
  486. mustNotMap = []interface{}{
  487. map[string]interface{}{
  488. "match": map[string]interface{}{
  489. "Frequency.keyword": "年度",
  490. },
  491. },
  492. }
  493. }
  494. //指标来源
  495. if source > 0 {
  496. mustMap = append(mustMap, map[string]interface{}{
  497. "term": map[string]interface{}{
  498. "Source": source,
  499. //"Frequency.keyword": "月度",
  500. },
  501. })
  502. }
  503. if frequency != "" {
  504. mustMap = append(mustMap, map[string]interface{}{
  505. "term": map[string]interface{}{
  506. "Frequency.keyword": frequency,
  507. //"Frequency.keyword": "月度",
  508. },
  509. })
  510. }
  511. //普通指标
  512. //mustMap = append(mustMap, map[string]interface{}{
  513. // "term": map[string]interface{}{
  514. // "EdbInfoType": 0,
  515. // //"Frequency.keyword": "月度",
  516. // },
  517. //})
  518. //关键字匹配
  519. shouldMap := map[string]interface{}{
  520. "should": []interface{}{
  521. map[string]interface{}{
  522. "match": map[string]interface{}{
  523. "EdbCode": keywordStr,
  524. //"Frequency.keyword": "月度",
  525. },
  526. },
  527. map[string]interface{}{
  528. "match": map[string]interface{}{
  529. "EdbName": keywordStr,
  530. //"Frequency.keyword": "月度",
  531. },
  532. },
  533. // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  534. map[string]interface{}{
  535. "match": map[string]interface{}{
  536. "EdbCode": map[string]interface{}{
  537. "query": keywordStr,
  538. "operator": "and",
  539. },
  540. //"Frequency.keyword": "月度",
  541. },
  542. },
  543. // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  544. map[string]interface{}{
  545. "match": map[string]interface{}{
  546. "EdbName": map[string]interface{}{
  547. "query": keywordStr,
  548. "operator": "and",
  549. },
  550. //"Frequency.keyword": "月度",
  551. },
  552. },
  553. },
  554. }
  555. mustMap = append(mustMap, map[string]interface{}{
  556. "bool": shouldMap,
  557. })
  558. queryMap := map[string]interface{}{
  559. "query": map[string]interface{}{
  560. "bool": map[string]interface{}{
  561. "must": mustMap,
  562. "must_not": mustNotMap,
  563. //"should": shouldMap,
  564. },
  565. },
  566. }
  567. //根据条件数量统计
  568. requestTotalHits := client.Count(indexName).BodyJson(queryMap)
  569. total, err = requestTotalHits.Do(context.Background())
  570. if err != nil {
  571. return
  572. }
  573. queryMap["from"] = from
  574. queryMap["size"] = size
  575. jsonBytes, _ := json.Marshal(queryMap)
  576. fmt.Println(string(jsonBytes))
  577. //queryStr := fmt.Sprintf(`{"query":{"bool":{"must":{"query_string":{"query":"%s","fields":["EdbCode","EdbName"]}}}}}`, keywordStr)
  578. //switch filterSource {
  579. //case 2:
  580. // queryStr = fmt.Sprintf(`{"query":{"bool":{"must":{"query_string":{"query":"%s","fields":["EdbCode","EdbName"]}},"filter":{"term":{"Frequency.keyword":"%s"}}}}}`, keywordStr, "月度")
  581. //case 3:
  582. // queryStr = fmt.Sprintf(`{"query":{"bool":{"must":{"query_string":{"query":"%s","fields":["EdbCode","EdbName"]}},"must_not":[{"match":{"Frequency.keyword":"%s"}}]}}}`, keywordStr, "日度")
  583. //case 4:
  584. // queryStr = fmt.Sprintf(`{"query":{"bool":{"must":{"query_string":{"query":"%s","fields":["EdbCode","EdbName"]}},"must_not":[{"match":{"EdbType":1}}]}}}`, keywordStr)
  585. //}
  586. //queryString := elastic.RawStringQuery(queryStr)
  587. //fmt.Println("queryString:", queryString)
  588. //queryString := elastic.NewMatchQuery("EdbCode", keywordStr)
  589. //request := client.Search(indexName).Highlight(highlight).From(from).Size(size).Query(queryString)
  590. request := client.Search(indexName).Highlight(highlight).Source(queryMap) // sets the JSON request
  591. //requestJson, err := json.Marshal(request)
  592. //if err != nil {
  593. // fmt.Println("requestJson err:", err)
  594. //}
  595. //fmt.Println("requestJson ", string(requestJson))
  596. searchMap := make(map[string]string)
  597. searchResp, err := request.Do(context.Background())
  598. if err != nil {
  599. return
  600. }
  601. fmt.Println(searchResp)
  602. fmt.Println(searchResp.Status)
  603. if searchResp.Status != 0 {
  604. return
  605. }
  606. if searchResp.Hits != nil {
  607. for _, v := range searchResp.Hits.Hits {
  608. if _, ok := searchMap[v.Id]; !ok {
  609. itemJson, tmpErr := v.Source.MarshalJSON()
  610. if tmpErr != nil {
  611. err = tmpErr
  612. fmt.Println("movieJson err:", err)
  613. return
  614. }
  615. edbInfoItem := new(data_manage.EdbInfoList)
  616. tmpErr = json.Unmarshal(itemJson, &edbInfoItem)
  617. if tmpErr != nil {
  618. fmt.Println("json.Unmarshal movieJson err:", tmpErr)
  619. err = tmpErr
  620. return
  621. }
  622. if len(v.Highlight["EdbCode"]) > 0 {
  623. edbInfoItem.EdbCode = v.Highlight["EdbCode"][0]
  624. }
  625. if len(v.Highlight["EdbName"]) > 0 {
  626. edbInfoItem.EdbCode = v.Highlight["EdbName"][0]
  627. }
  628. list = append(list, edbInfoItem)
  629. searchMap[v.Id] = v.Id
  630. }
  631. }
  632. }
  633. //for _, v := range result {
  634. // fmt.Println(v)
  635. //}
  636. return
  637. }
  638. // SearchAddPredictEdbInfoData 查询允许添加预测指标的数据
  639. func SearchAddPredictEdbInfoData(indexName, keywordStr string, noPermissionEdbInfoIdList []int, from, size, sysUserId int) (total int64, list []*data_manage.EdbInfoList, err error) {
  640. list = make([]*data_manage.EdbInfoList, 0)
  641. defer func() {
  642. if err != nil {
  643. fmt.Println("EsAddOrEditData Err:", err.Error())
  644. }
  645. }()
  646. highlight := elastic.NewHighlight()
  647. highlight = highlight.Fields(elastic.NewHighlighterField("EdbCode"), elastic.NewHighlighterField("EdbName"))
  648. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  649. mustMap := make([]interface{}, 0)
  650. mustNotMap := make([]interface{}, 0)
  651. mustNotMap = []interface{}{
  652. //map[string]interface{}{
  653. // "terms": map[string]interface{}{
  654. // "Frequency.keyword": []string{"日度", "周度", "月度"},
  655. // },
  656. // //"match": map[string]interface{}{
  657. // // "Frequency": []string{"日度", "周度", "月度"},
  658. // // //"Frequency.keyword": []string{"日度", "周度", "月度"},
  659. // //},
  660. //},
  661. }
  662. // 指标类型:普通指标、预算指标
  663. mustMap = append(mustMap, map[string]interface{}{
  664. "term": map[string]interface{}{
  665. "EdbInfoType": 0,
  666. },
  667. })
  668. mustMap = append(mustMap, map[string]interface{}{
  669. "terms": map[string]interface{}{
  670. "Frequency.keyword": []string{"日度", "周度", "月度"},
  671. },
  672. })
  673. // 只看我的
  674. if sysUserId > 0 {
  675. mustMap = append(mustMap, map[string]interface{}{
  676. "terms": map[string]interface{}{
  677. "SysUserId": sysUserId,
  678. },
  679. })
  680. }
  681. //关键字匹配
  682. //shouldMap := map[string]interface{}{
  683. // "should": []interface{}{
  684. // map[string]interface{}{
  685. // "match": map[string]interface{}{
  686. // "EdbCode": keywordStr,
  687. // //"Frequency.keyword": "月度",
  688. // },
  689. // },
  690. // map[string]interface{}{
  691. // "match": map[string]interface{}{
  692. // "EdbName": keywordStr,
  693. // //"Frequency.keyword": "月度",
  694. // },
  695. // },
  696. // map[string]interface{}{
  697. // "match": map[string]interface{}{
  698. // "EdbNameEn": keywordStr,
  699. // //"Frequency.keyword": "月度",
  700. // },
  701. // },
  702. // },
  703. //}
  704. // 默认使用中文名字字段去匹配
  705. keywordNameKey := `EdbName`
  706. // 如果没有中文,则使用英文名称字段去匹配
  707. if !utils.ContainsChinese(keywordStr) {
  708. keywordNameKey = `EdbNameEn`
  709. }
  710. shouldMap := map[string]interface{}{
  711. "should": []interface{}{
  712. map[string]interface{}{
  713. "match": map[string]interface{}{
  714. "EdbCode": keywordStr,
  715. //"Frequency.keyword": "月度",
  716. },
  717. },
  718. map[string]interface{}{
  719. "match": map[string]interface{}{
  720. keywordNameKey: keywordStr,
  721. //"Frequency.keyword": "月度",
  722. },
  723. },
  724. },
  725. }
  726. // noPermissionEdbInfoIdList 无权限指标id
  727. if len(noPermissionEdbInfoIdList) > 0 {
  728. mustNotMap = append(mustNotMap, map[string]interface{}{
  729. "terms": map[string]interface{}{
  730. "EdbInfoId": noPermissionEdbInfoIdList,
  731. //"Frequency.keyword": "月度",
  732. },
  733. })
  734. }
  735. return searchEdbInfoData(indexName, mustMap, mustNotMap, shouldMap, from, size)
  736. }
  737. // searchEdbInfoData 查询es中的指标数据
  738. func searchEdbInfoData(indexName string, mustMap, mustNotMap []interface{}, shouldMap map[string]interface{}, from, size int) (total int64, list []*data_manage.EdbInfoList, err error) {
  739. list = make([]*data_manage.EdbInfoList, 0)
  740. defer func() {
  741. if err != nil {
  742. fmt.Println("EsAddOrEditData Err:", err.Error())
  743. }
  744. }()
  745. client := utils.EsClient
  746. //queryString := elastic.NewQueryStringQuery(keywordStr)
  747. //boolQueryJson, err := json.Marshal(queryString)
  748. //if err != nil {
  749. // fmt.Println("boolQueryJson err:", err)
  750. //} else {
  751. // fmt.Println("boolQueryJson ", string(boolQueryJson))
  752. //}
  753. highlight := elastic.NewHighlight()
  754. highlight = highlight.Fields(elastic.NewHighlighterField("EdbCode"), elastic.NewHighlighterField("EdbName"))
  755. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  756. //query := elastic.RawStringQuery(`{"match_all":{}}`)
  757. //关键字匹配
  758. mustMap = append(mustMap, map[string]interface{}{
  759. "bool": shouldMap,
  760. })
  761. queryMap := map[string]interface{}{
  762. "query": map[string]interface{}{
  763. "bool": map[string]interface{}{
  764. "must": mustMap,
  765. "must_not": mustNotMap,
  766. //"should": shouldMap,
  767. },
  768. },
  769. }
  770. //根据条件数量统计
  771. requestTotalHits := client.Count(indexName).BodyJson(queryMap)
  772. total, err = requestTotalHits.Do(context.Background())
  773. if err != nil {
  774. return
  775. }
  776. queryMap["from"] = from
  777. queryMap["size"] = size
  778. queryMap["highlight"] = map[string]interface{}{
  779. "fields": map[string]interface{}{
  780. "EdbName": map[string]interface{}{},
  781. },
  782. "pre_tags": "<span style=\"color:#0052D9\">",
  783. "post_tags": "</span>",
  784. }
  785. jsonBytes, _ := json.Marshal(queryMap)
  786. fmt.Println(string(jsonBytes))
  787. //queryStr := fmt.Sprintf(`{"query":{"bool":{"must":{"query_string":{"query":"%s","fields":["EdbCode","EdbName"]}}}}}`, keywordStr)
  788. //switch filterSource {
  789. //case 2:
  790. // queryStr = fmt.Sprintf(`{"query":{"bool":{"must":{"query_string":{"query":"%s","fields":["EdbCode","EdbName"]}},"filter":{"term":{"Frequency.keyword":"%s"}}}}}`, keywordStr, "月度")
  791. //case 3:
  792. // queryStr = fmt.Sprintf(`{"query":{"bool":{"must":{"query_string":{"query":"%s","fields":["EdbCode","EdbName"]}},"must_not":[{"match":{"Frequency.keyword":"%s"}}]}}}`, keywordStr, "日度")
  793. //case 4:
  794. // queryStr = fmt.Sprintf(`{"query":{"bool":{"must":{"query_string":{"query":"%s","fields":["EdbCode","EdbName"]}},"must_not":[{"match":{"EdbType":1}}]}}}`, keywordStr)
  795. //}
  796. //queryString := elastic.RawStringQuery(queryStr)
  797. //fmt.Println("queryString:", queryString)
  798. //queryString := elastic.NewMatchQuery("EdbCode", keywordStr)
  799. //request := client.Search(indexName).Highlight(highlight).From(from).Size(size).Query(queryString)
  800. request := client.Search(indexName).Highlight(highlight).Source(queryMap) // sets the JSON request
  801. //requestJson, err := json.Marshal(request)
  802. //if err != nil {
  803. // fmt.Println("requestJson err:", err)
  804. //}
  805. //fmt.Println("requestJson ", string(requestJson))
  806. searchMap := make(map[string]string)
  807. searchResp, err := request.Do(context.Background())
  808. if err != nil {
  809. return
  810. }
  811. fmt.Println(searchResp)
  812. fmt.Println(searchResp.Status)
  813. if searchResp.Status != 0 {
  814. return
  815. }
  816. //total = searchResp.TotalHits()
  817. if searchResp.Hits != nil {
  818. for _, v := range searchResp.Hits.Hits {
  819. if _, ok := searchMap[v.Id]; !ok {
  820. itemJson, tmpErr := v.Source.MarshalJSON()
  821. if tmpErr != nil {
  822. err = tmpErr
  823. fmt.Println("movieJson err:", err)
  824. return
  825. }
  826. edbInfoItem := new(data_manage.EdbInfoList)
  827. tmpErr = json.Unmarshal(itemJson, &edbInfoItem)
  828. if tmpErr != nil {
  829. fmt.Println("json.Unmarshal movieJson err:", tmpErr)
  830. err = tmpErr
  831. return
  832. }
  833. if len(v.Highlight["EdbCode"]) > 0 {
  834. edbInfoItem.EdbCode = v.Highlight["EdbCode"][0]
  835. }
  836. if len(v.Highlight["EdbName"]) > 0 {
  837. // 搜索结果高亮用新字段,原EdbName直接高亮展示上会有点影响
  838. edbInfoItem.SearchText = v.Highlight["EdbName"][0]
  839. //edbInfoItem.EdbName = v.Highlight["EdbName"][0]
  840. } else {
  841. edbInfoItem.SearchText = edbInfoItem.EdbName
  842. }
  843. list = append(list, edbInfoItem)
  844. searchMap[v.Id] = v.Id
  845. }
  846. }
  847. }
  848. return
  849. }
  850. // EsDeleteEdbInfoData 删除es中的指标数据
  851. func EsDeleteEdbInfoData(indexName, docId string) (err error) {
  852. defer func() {
  853. if err != nil {
  854. fmt.Println("EsDeleteEdbInfoData Err:", err.Error())
  855. }
  856. }()
  857. client := utils.EsClient
  858. resp, err := client.Delete().Index(indexName).Id(docId).Refresh(`true`).Do(context.Background())
  859. fmt.Println(resp)
  860. if err != nil {
  861. return
  862. }
  863. if resp.Status == 0 {
  864. fmt.Println("删除成功")
  865. } else {
  866. fmt.Println("AddData", resp.Status, resp.Result)
  867. }
  868. return
  869. }
  870. // EsAddOrEditReport 新增编辑es报告
  871. func EsAddOrEditReport(indexName, docId string, item *models.ElasticReportDetail) (err error) {
  872. defer func() {
  873. if err != nil {
  874. fmt.Println("EsAddOrEditReport Err:", err.Error())
  875. }
  876. }()
  877. client := utils.EsClient
  878. // docId为报告ID+章节ID
  879. searchById, err := client.Get().Index(indexName).Id(docId).Do(context.Background())
  880. if err != nil && !strings.Contains(err.Error(), "404") {
  881. fmt.Println("Get Err" + err.Error())
  882. return
  883. }
  884. if searchById != nil && searchById.Found {
  885. resp, err := client.Update().Index(indexName).Id(docId).Doc(map[string]interface{}{
  886. "ReportId": item.ReportId,
  887. "ReportChapterId": item.ReportChapterId,
  888. "Title": item.Title,
  889. "Abstract": item.Abstract,
  890. "BodyContent": item.BodyContent,
  891. "PublishTime": item.PublishTime,
  892. "PublishState": item.PublishState,
  893. "Author": item.Author,
  894. "ClassifyIdFirst": item.ClassifyIdFirst,
  895. "ClassifyNameFirst": item.ClassifyNameFirst,
  896. "ClassifyIdSecond": item.ClassifyIdSecond,
  897. "ClassifyNameSecond": item.ClassifyNameSecond,
  898. "Categories": item.Categories,
  899. "StageStr": item.StageStr,
  900. }).Do(context.Background())
  901. if err != nil {
  902. return err
  903. }
  904. //fmt.Println(resp.Status, resp.Result)
  905. if resp.Status == 0 {
  906. fmt.Println("修改成功" + docId)
  907. err = nil
  908. } else {
  909. fmt.Println("EditData", resp.Status, resp.Result)
  910. }
  911. } else {
  912. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
  913. if err != nil {
  914. fmt.Println("新增失败:", err.Error())
  915. return err
  916. }
  917. if resp.Status == 0 && resp.Result == "created" {
  918. fmt.Println("新增成功" + docId)
  919. return nil
  920. } else {
  921. fmt.Println("AddData", resp.Status, resp.Result)
  922. }
  923. }
  924. return
  925. }
  926. // AnalyzeResp 分词接口返回结构体
  927. type AnalyzeResp struct {
  928. Tokens []struct {
  929. EndOffset int64 `json:"end_offset"`
  930. Position int64 `json:"position"`
  931. StartOffset int64 `json:"start_offset"`
  932. Token string `json:"token"`
  933. Type string `json:"type"`
  934. } `json:"tokens"`
  935. }
  936. // Analyze 根据输入的文字获取分词后的文字
  937. func Analyze(content string) (contentList []string, err error) {
  938. defer func() {
  939. if err != nil {
  940. fmt.Println("Analyze Err:", err.Error())
  941. }
  942. }()
  943. client := utils.EsClient
  944. queryMap := map[string]string{
  945. "text": content,
  946. "analyzer": "ik_max_word",
  947. }
  948. res, err := client.PerformRequest(
  949. context.Background(),
  950. elastic.PerformRequestOptions{
  951. Method: "GET",
  952. Path: "/_analyze",
  953. Body: queryMap,
  954. Stream: false,
  955. },
  956. )
  957. if res.StatusCode == 200 {
  958. var analyzeResp AnalyzeResp
  959. tmpErr := json.Unmarshal(res.Body, &analyzeResp)
  960. if tmpErr != nil {
  961. err = errors.New("返回数据转结构体失败:" + tmpErr.Error())
  962. return
  963. }
  964. for _, v := range analyzeResp.Tokens {
  965. contentList = append(contentList, v.Token)
  966. }
  967. } else {
  968. err = errors.New("分词失败,返回code异常:" + strconv.Itoa(res.StatusCode))
  969. }
  970. return
  971. }
  972. // EsAddOrEditChartInfoData 新增/修改es中的图表数据
  973. func EsAddOrEditChartInfoData(indexName, docId string, item *data_manage.ChartInfo) (err error) {
  974. defer func() {
  975. if err != nil {
  976. fmt.Println("EsAddOrEditData Err:", err.Error())
  977. }
  978. }()
  979. client := utils.EsClient
  980. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Refresh("true").Do(context.Background())
  981. if err != nil {
  982. fmt.Println("新增失败:", err.Error())
  983. return err
  984. }
  985. fmt.Println(resp)
  986. if resp.Status == 0 {
  987. fmt.Println("新增成功", resp.Result)
  988. err = nil
  989. } else {
  990. fmt.Println("AddData", resp.Status, resp.Result)
  991. }
  992. return
  993. }
  994. // EsDeleteDataV2 删除es中的数据
  995. func EsDeleteDataV2(indexName, docId string) (err error) {
  996. defer func() {
  997. if err != nil {
  998. fmt.Println("EsDeleteEdbInfoData Err:", err.Error())
  999. }
  1000. }()
  1001. client := utils.EsClient
  1002. resp, err := client.Delete().Index(indexName).Id(docId).Refresh("true").Do(context.Background())
  1003. fmt.Println(resp)
  1004. if err != nil {
  1005. return
  1006. }
  1007. if resp.Status == 0 {
  1008. fmt.Println("删除成功")
  1009. } else {
  1010. fmt.Println("AddData", resp.Status, resp.Result)
  1011. }
  1012. return
  1013. }
  1014. // SearchChartInfoData 查询es中的图表数据
  1015. func SearchChartInfoData(indexName, keywordStr string, showSysId int, sourceList []int, noPermissionChartIdList []int, from, size int) (list []*data_manage.ChartInfoMore, total int64, err error) {
  1016. list = make([]*data_manage.ChartInfoMore, 0)
  1017. defer func() {
  1018. if err != nil {
  1019. fmt.Println("EsAddOrEditData Err:", err.Error())
  1020. }
  1021. }()
  1022. client := utils.EsClient
  1023. //queryString := elastic.NewQueryStringQuery(keywordStr)
  1024. //boolQueryJson, err := json.Marshal(queryString)
  1025. //if err != nil {
  1026. // fmt.Println("boolQueryJson err:", err)
  1027. //} else {
  1028. // fmt.Println("boolQueryJson ", string(boolQueryJson))
  1029. //}
  1030. highlight := elastic.NewHighlight()
  1031. highlight = highlight.Fields(elastic.NewHighlighterField("ChartName"))
  1032. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  1033. mustMap := make([]interface{}, 0)
  1034. mustNotMap := make([]interface{}, 0)
  1035. //指标来源
  1036. if showSysId > 0 {
  1037. mustMap = append(mustMap, map[string]interface{}{
  1038. "term": map[string]interface{}{
  1039. "SysUserId": showSysId,
  1040. //"Frequency.keyword": "月度",
  1041. },
  1042. })
  1043. }
  1044. mustMap = append(mustMap, map[string]interface{}{
  1045. "terms": map[string]interface{}{
  1046. "Source": sourceList,
  1047. },
  1048. })
  1049. //关键字匹配
  1050. //shouldMap := map[string]interface{}{
  1051. // "should": []interface{}{
  1052. // map[string]interface{}{
  1053. // "match": map[string]interface{}{
  1054. // "ChartName": keywordStr,
  1055. // //"Frequency.keyword": "月度",
  1056. // },
  1057. // },
  1058. // // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  1059. // map[string]interface{}{
  1060. // "match": map[string]interface{}{
  1061. // "ChartName": map[string]interface{}{
  1062. // "query": keywordStr,
  1063. // "operator": "and",
  1064. // },
  1065. // //"Frequency.keyword": "月度",
  1066. // },
  1067. // },
  1068. // map[string]interface{}{
  1069. // "match": map[string]interface{}{
  1070. // "ChartNameEn": keywordStr,
  1071. // //"Frequency.keyword": "月度",
  1072. // },
  1073. // },
  1074. // // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  1075. // map[string]interface{}{
  1076. // "match": map[string]interface{}{
  1077. // "ChartNameEn": map[string]interface{}{
  1078. // "query": keywordStr,
  1079. // "operator": "and",
  1080. // },
  1081. // //"Frequency.keyword": "月度",
  1082. // },
  1083. // },
  1084. // },
  1085. //}
  1086. // 默认使用中文名字字段去匹配
  1087. keywordNameKey := `ChartName`
  1088. // 如果没有中文,则使用英文名称字段去匹配
  1089. if !utils.ContainsChinese(keywordStr) {
  1090. keywordNameKey = `ChartNameEn`
  1091. }
  1092. shouldMap := map[string]interface{}{
  1093. "should": []interface{}{
  1094. map[string]interface{}{
  1095. "match": map[string]interface{}{
  1096. keywordNameKey: keywordStr,
  1097. //"Frequency.keyword": "月度",
  1098. },
  1099. },
  1100. // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  1101. map[string]interface{}{
  1102. "match": map[string]interface{}{
  1103. keywordNameKey: map[string]interface{}{
  1104. "query": keywordStr,
  1105. "operator": "and",
  1106. },
  1107. //"Frequency.keyword": "月度",
  1108. },
  1109. },
  1110. },
  1111. }
  1112. mustMap = append(mustMap, map[string]interface{}{
  1113. "bool": shouldMap,
  1114. })
  1115. // noPermissionEdbInfoIdList 无权限指标id
  1116. if len(noPermissionChartIdList) > 0 {
  1117. mustNotMap = append(mustNotMap, map[string]interface{}{
  1118. "terms": map[string]interface{}{
  1119. "ChartInfoId": noPermissionChartIdList,
  1120. //"Frequency.keyword": "月度",
  1121. },
  1122. })
  1123. }
  1124. queryMap := map[string]interface{}{
  1125. "query": map[string]interface{}{
  1126. "bool": map[string]interface{}{
  1127. "must": mustMap,
  1128. "must_not": mustNotMap,
  1129. //"should": shouldMap,
  1130. },
  1131. },
  1132. }
  1133. //根据条件数量统计
  1134. requestTotalHits := client.Count(indexName).BodyJson(queryMap)
  1135. total, err = requestTotalHits.Do(context.Background())
  1136. if err != nil {
  1137. return
  1138. }
  1139. // 分页查询
  1140. queryMap["from"] = from
  1141. queryMap["size"] = size
  1142. queryMap["highlight"] = map[string]interface{}{
  1143. "fields": map[string]interface{}{
  1144. keywordNameKey: map[string]interface{}{},
  1145. },
  1146. "pre_tags": "<span style=\"color:#0052D9\">",
  1147. "post_tags": "</span>",
  1148. }
  1149. jsonBytes, _ := json.Marshal(queryMap)
  1150. fmt.Println(string(jsonBytes))
  1151. request := client.Search(indexName).Highlight(highlight).Source(queryMap) // sets the JSON request
  1152. //requestJson, err := json.Marshal(request)
  1153. //if err != nil {
  1154. // fmt.Println("requestJson err:", err)
  1155. //}
  1156. //fmt.Println("requestJson ", string(requestJson))
  1157. searchMap := make(map[string]string)
  1158. searchResp, err := request.Do(context.Background())
  1159. if err != nil {
  1160. return
  1161. }
  1162. fmt.Println(searchResp)
  1163. fmt.Println(searchResp.Status)
  1164. if searchResp.Status != 0 {
  1165. return
  1166. }
  1167. if searchResp.Hits != nil {
  1168. for _, v := range searchResp.Hits.Hits {
  1169. if _, ok := searchMap[v.Id]; !ok {
  1170. itemJson, tmpErr := v.Source.MarshalJSON()
  1171. if tmpErr != nil {
  1172. err = tmpErr
  1173. fmt.Println("movieJson err:", err)
  1174. return
  1175. }
  1176. chartInfoItem := new(data_manage.ChartInfoMore)
  1177. tmpErr = json.Unmarshal(itemJson, &chartInfoItem)
  1178. if err != nil {
  1179. fmt.Println("json.Unmarshal chartInfoJson err:", err)
  1180. err = tmpErr
  1181. return
  1182. }
  1183. if len(v.Highlight[keywordNameKey]) > 0 {
  1184. //chartInfoItem.ChartName = v.Highlight["ChartName"][0]
  1185. chartInfoItem.SearchText = v.Highlight[keywordNameKey][0]
  1186. } else {
  1187. chartInfoItem.SearchText = chartInfoItem.ChartName
  1188. }
  1189. list = append(list, chartInfoItem)
  1190. searchMap[v.Id] = v.Id
  1191. }
  1192. }
  1193. }
  1194. //for _, v := range result {
  1195. // fmt.Println(v)
  1196. //}
  1197. return
  1198. }
  1199. // EsAddOrEditDataInterface 新增/修改es中的数据
  1200. func EsAddOrEditDataInterface(indexName, docId string, item interface{}) (err error) {
  1201. defer func() {
  1202. if err != nil {
  1203. fmt.Println("EsAddOrEditData Err:", err.Error())
  1204. }
  1205. }()
  1206. client := utils.EsClient
  1207. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Refresh("true").Do(context.Background())
  1208. if err != nil {
  1209. fmt.Println("新增失败:", err.Error())
  1210. return err
  1211. }
  1212. fmt.Println(resp)
  1213. if resp.Status == 0 {
  1214. fmt.Println("新增成功", resp.Result)
  1215. err = nil
  1216. } else {
  1217. fmt.Println("AddData", resp.Status, resp.Result)
  1218. }
  1219. return
  1220. }
  1221. // SearchMyChartInfoData 查询es中的我的图表数据
  1222. func SearchMyChartInfoData(indexName, keywordStr string, adminId int, noPermissionChartIdList []int, from, size int) (list []*data_manage.MyChartList, total int64, err error) {
  1223. list = make([]*data_manage.MyChartList, 0)
  1224. defer func() {
  1225. if err != nil {
  1226. fmt.Println("EsAddOrEditData Err:", err.Error())
  1227. }
  1228. }()
  1229. client := utils.EsClient
  1230. //queryString := elastic.NewQueryStringQuery(keywordStr)
  1231. //boolQueryJson, err := json.Marshal(queryString)
  1232. //if err != nil {
  1233. // fmt.Println("boolQueryJson err:", err)
  1234. //} else {
  1235. // fmt.Println("boolQueryJson ", string(boolQueryJson))
  1236. //}
  1237. highlight := elastic.NewHighlight()
  1238. highlight = highlight.Fields(elastic.NewHighlighterField("ChartName"))
  1239. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  1240. mustMap := make([]interface{}, 0)
  1241. mustNotMap := make([]interface{}, 0)
  1242. //指标来源
  1243. if adminId > 0 {
  1244. mustMap = append(mustMap, map[string]interface{}{
  1245. "term": map[string]interface{}{
  1246. "AdminId": adminId,
  1247. //"Frequency.keyword": "月度",
  1248. },
  1249. })
  1250. }
  1251. //关键字匹配
  1252. //shouldMap := map[string]interface{}{
  1253. // "should": []interface{}{
  1254. // map[string]interface{}{
  1255. // "match": map[string]interface{}{
  1256. // "ChartName": keywordStr,
  1257. // //"Frequency.keyword": "月度",
  1258. // },
  1259. // },
  1260. // // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  1261. // map[string]interface{}{
  1262. // "match": map[string]interface{}{
  1263. // "ChartName": map[string]interface{}{
  1264. // "query": keywordStr,
  1265. // "operator": "and",
  1266. // },
  1267. // //"Frequency.keyword": "月度",
  1268. // },
  1269. // },
  1270. // map[string]interface{}{
  1271. // "match": map[string]interface{}{
  1272. // "ChartNameEn": keywordStr,
  1273. // //"Frequency.keyword": "月度",
  1274. // },
  1275. // },
  1276. // // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  1277. // map[string]interface{}{
  1278. // "match": map[string]interface{}{
  1279. // "ChartNameEn": map[string]interface{}{
  1280. // "query": keywordStr,
  1281. // "operator": "and",
  1282. // },
  1283. // //"Frequency.keyword": "月度",
  1284. // },
  1285. // },
  1286. // },
  1287. //}
  1288. // 默认使用中文名字字段去匹配
  1289. keywordNameKey := `ChartName`
  1290. // 如果没有中文,则使用英文名称字段去匹配
  1291. if !utils.ContainsChinese(keywordStr) {
  1292. keywordNameKey = `ChartNameEn`
  1293. }
  1294. shouldMap := map[string]interface{}{
  1295. "should": []interface{}{
  1296. map[string]interface{}{
  1297. "match": map[string]interface{}{
  1298. keywordNameKey: keywordStr,
  1299. //"Frequency.keyword": "月度",
  1300. },
  1301. },
  1302. // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  1303. map[string]interface{}{
  1304. "match": map[string]interface{}{
  1305. keywordNameKey: map[string]interface{}{
  1306. "query": keywordStr,
  1307. "operator": "and",
  1308. },
  1309. //"Frequency.keyword": "月度",
  1310. },
  1311. },
  1312. },
  1313. }
  1314. mustMap = append(mustMap, map[string]interface{}{
  1315. "bool": shouldMap,
  1316. })
  1317. // noPermissionEdbInfoIdList 无权限指标id
  1318. if len(noPermissionChartIdList) > 0 {
  1319. mustNotMap = append(mustNotMap, map[string]interface{}{
  1320. "terms": map[string]interface{}{
  1321. "ChartInfoId": noPermissionChartIdList,
  1322. //"Frequency.keyword": "月度",
  1323. },
  1324. })
  1325. }
  1326. queryMap := map[string]interface{}{
  1327. "query": map[string]interface{}{
  1328. "bool": map[string]interface{}{
  1329. "must": mustMap,
  1330. "must_not": mustNotMap,
  1331. //"should": shouldMap,
  1332. },
  1333. },
  1334. }
  1335. //根据条件数量统计
  1336. requestTotalHits := client.Count(indexName).BodyJson(queryMap)
  1337. total, err = requestTotalHits.Do(context.Background())
  1338. if err != nil {
  1339. return
  1340. }
  1341. // 分页查询
  1342. queryMap["from"] = from
  1343. queryMap["size"] = size
  1344. queryMap["highlight"] = map[string]interface{}{
  1345. "fields": map[string]interface{}{
  1346. keywordNameKey: map[string]interface{}{},
  1347. },
  1348. "pre_tags": "<span style=\"color:#0052D9\">",
  1349. "post_tags": "</span>",
  1350. }
  1351. jsonBytes, _ := json.Marshal(queryMap)
  1352. fmt.Println(string(jsonBytes))
  1353. request := client.Search(indexName).Highlight(highlight).Source(queryMap) // sets the JSON request
  1354. //requestJson, err := json.Marshal(request)
  1355. //if err != nil {
  1356. // fmt.Println("requestJson err:", err)
  1357. //}
  1358. //fmt.Println("requestJson ", string(requestJson))
  1359. searchMap := make(map[string]string)
  1360. searchResp, err := request.Do(context.Background())
  1361. if err != nil {
  1362. return
  1363. }
  1364. fmt.Println(searchResp)
  1365. fmt.Println(searchResp.Status)
  1366. if searchResp.Status != 0 {
  1367. return
  1368. }
  1369. if searchResp.Hits != nil {
  1370. for _, v := range searchResp.Hits.Hits {
  1371. if _, ok := searchMap[v.Id]; !ok {
  1372. itemJson, tmpErr := v.Source.MarshalJSON()
  1373. if tmpErr != nil {
  1374. err = tmpErr
  1375. fmt.Println("movieJson err:", err)
  1376. return
  1377. }
  1378. chartInfoItem := new(data_manage.MyChartList)
  1379. tmpErr = json.Unmarshal(itemJson, &chartInfoItem)
  1380. if err != nil {
  1381. fmt.Println("json.Unmarshal chartInfoJson err:", err)
  1382. err = tmpErr
  1383. return
  1384. }
  1385. if len(v.Highlight[keywordNameKey]) > 0 {
  1386. //chartInfoItem.ChartName = v.Highlight["ChartName"][0]
  1387. chartInfoItem.SearchText = v.Highlight[keywordNameKey][0]
  1388. } else {
  1389. chartInfoItem.SearchText = chartInfoItem.ChartName
  1390. }
  1391. list = append(list, chartInfoItem)
  1392. searchMap[v.Id] = v.Id
  1393. }
  1394. }
  1395. }
  1396. //for _, v := range result {
  1397. // fmt.Println(v)
  1398. //}
  1399. return
  1400. }
  1401. // SearchEdbInfoDataByAdminId 查询es中的指标数据
  1402. func SearchEdbInfoDataByAdminId(indexName, keywordStr string, from, size, filterSource, source int, edbInfoType uint8, frequency string, adminId int) (total int64, list []*data_manage.EdbInfoList, err error) {
  1403. list = make([]*data_manage.EdbInfoList, 0)
  1404. defer func() {
  1405. if err != nil {
  1406. fmt.Println("EsAddOrEditData Err:", err.Error())
  1407. }
  1408. }()
  1409. highlight := elastic.NewHighlight()
  1410. highlight = highlight.Fields(elastic.NewHighlighterField("EdbCode"), elastic.NewHighlighterField("EdbName"))
  1411. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  1412. //var source map[string]interface{}
  1413. //source := map[string]interface{}{
  1414. // "query": map[string]interface{}{
  1415. // "match_all": map[string]interface{}{},
  1416. // },
  1417. //}
  1418. mustMap := make([]interface{}, 0)
  1419. mustNotMap := make([]interface{}, 0)
  1420. //source := map[string]interface{}{
  1421. // "query": map[string]interface{}{
  1422. // "bool": map[string]interface{}{
  1423. // "must": map[string]interface{}{
  1424. // "query_string": map[string]interface{}{
  1425. // "query": keywordStr,
  1426. // "fields": []string{"EdbCode", "EdbName"},
  1427. // },
  1428. // },
  1429. // },
  1430. // },
  1431. //}
  1432. switch filterSource {
  1433. case 2:
  1434. //source = map[string]interface{}{
  1435. // "query": map[string]interface{}{
  1436. // "bool": map[string]interface{}{
  1437. // "must": map[string]interface{}{
  1438. // "query_string": map[string]interface{}{
  1439. // "query": keywordStr,
  1440. // },
  1441. // },
  1442. // "filter": []interface{}{
  1443. // map[string]interface{}{
  1444. // "term": map[string]interface{}{
  1445. // "Frequency.keyword": "月度",
  1446. // },
  1447. // }},
  1448. // },
  1449. // },
  1450. //}
  1451. mustMap = []interface{}{
  1452. map[string]interface{}{
  1453. "term": map[string]interface{}{
  1454. "Frequency.keyword": "月度",
  1455. //"Frequency.keyword": "月度",
  1456. },
  1457. },
  1458. }
  1459. case 3:
  1460. //source = map[string]interface{}{
  1461. // "query": map[string]interface{}{
  1462. // "bool": map[string]interface{}{
  1463. // "must": map[string]interface{}{
  1464. // "query_string": map[string]interface{}{
  1465. // "query": keywordStr,
  1466. // },
  1467. // },
  1468. // "must_not": []interface{}{
  1469. // map[string]interface{}{
  1470. // "match": map[string]interface{}{
  1471. // "Frequency.keyword": "日度",
  1472. // },
  1473. // }},
  1474. // },
  1475. // },
  1476. //}
  1477. ////注释掉,所有频度都可以变频 2022-08-31 14:31:28
  1478. //mustNotMap = []interface{}{
  1479. // map[string]interface{}{
  1480. // "match": map[string]interface{}{
  1481. // "Frequency.keyword": "日度",
  1482. // //"Frequency.keyword": "月度",
  1483. // },
  1484. // },
  1485. //}
  1486. case 4:
  1487. //source = map[string]interface{}{
  1488. // "query": map[string]interface{}{
  1489. // "bool": map[string]interface{}{
  1490. // "must": map[string]interface{}{
  1491. // "query_string": map[string]interface{}{
  1492. // "query": keywordStr,
  1493. // },
  1494. // },
  1495. // "filter": []interface{}{
  1496. // map[string]interface{}{
  1497. // "term": map[string]interface{}{
  1498. // "EdbType": 1,
  1499. // },
  1500. // }},
  1501. // },
  1502. // },
  1503. //}
  1504. mustMap = []interface{}{
  1505. map[string]interface{}{
  1506. "term": map[string]interface{}{
  1507. "EdbType": 1,
  1508. },
  1509. },
  1510. }
  1511. case 5:
  1512. mustMap = []interface{}{
  1513. map[string]interface{}{
  1514. "term": map[string]interface{}{
  1515. "Source": 6,
  1516. },
  1517. },
  1518. }
  1519. case 6:
  1520. mustNotMap = []interface{}{
  1521. map[string]interface{}{
  1522. "match": map[string]interface{}{
  1523. "Frequency.keyword": "年度",
  1524. },
  1525. },
  1526. }
  1527. }
  1528. //指标来源
  1529. if source > 0 {
  1530. mustMap = append(mustMap, map[string]interface{}{
  1531. "term": map[string]interface{}{
  1532. "Source": source,
  1533. //"Frequency.keyword": "月度",
  1534. },
  1535. })
  1536. }
  1537. if frequency != "" {
  1538. mustMap = append(mustMap, map[string]interface{}{
  1539. "term": map[string]interface{}{
  1540. "Frequency.keyword": frequency,
  1541. //"Frequency.keyword": "月度",
  1542. },
  1543. })
  1544. }
  1545. // 指标类型:普通指标、预算指标
  1546. mustMap = append(mustMap, map[string]interface{}{
  1547. "term": map[string]interface{}{
  1548. "EdbInfoType": edbInfoType,
  1549. },
  1550. })
  1551. //普通指标
  1552. //mustMap = append(mustMap, map[string]interface{}{
  1553. // "term": map[string]interface{}{
  1554. // "EdbInfoType": 0,
  1555. // //"Frequency.keyword": "月度",
  1556. // },
  1557. //})
  1558. //关键字匹配
  1559. //shouldMap := map[string]interface{}{
  1560. // "should": []interface{}{
  1561. // map[string]interface{}{
  1562. // "match": map[string]interface{}{
  1563. // "EdbCode": keywordStr,
  1564. // //"Frequency.keyword": "月度",
  1565. // },
  1566. // },
  1567. // map[string]interface{}{
  1568. // "match": map[string]interface{}{
  1569. // "EdbName": keywordStr,
  1570. // //"Frequency.keyword": "月度",
  1571. // },
  1572. // },
  1573. // },
  1574. //}
  1575. // 默认使用中文名字字段去匹配
  1576. keywordNameKey := `EdbName`
  1577. // 如果没有中文,则使用英文名称字段去匹配
  1578. if !utils.ContainsChinese(keywordStr) {
  1579. keywordNameKey = `EdbNameEn`
  1580. }
  1581. shouldMap := map[string]interface{}{
  1582. "should": []interface{}{
  1583. map[string]interface{}{
  1584. "match": map[string]interface{}{
  1585. "EdbCode": keywordStr,
  1586. //"Frequency.keyword": "月度",
  1587. },
  1588. },
  1589. map[string]interface{}{
  1590. "match": map[string]interface{}{
  1591. keywordNameKey: keywordStr,
  1592. //"Frequency.keyword": "月度",
  1593. },
  1594. },
  1595. },
  1596. }
  1597. mustMap = append(mustMap, map[string]interface{}{
  1598. "bool": shouldMap,
  1599. })
  1600. //创建人
  1601. if adminId > 0 {
  1602. mustMap = append(mustMap, map[string]interface{}{
  1603. "term": map[string]interface{}{
  1604. "SysUserId": adminId,
  1605. },
  1606. })
  1607. }
  1608. return searchEdbInfoData(indexName, mustMap, mustNotMap, shouldMap, from, size)
  1609. }
  1610. // EsAddOrEditExcelInfoData 新增/修改es中的表格数据
  1611. func EsAddOrEditExcelInfoData(indexName, docId string, item *excel.ExcelInfo) (err error) {
  1612. defer func() {
  1613. if err != nil {
  1614. tips := fmt.Sprintf("EsAddOrEditExcelInfoData err: %v", err)
  1615. utils.FileLog.Info(tips)
  1616. }
  1617. }()
  1618. client := utils.EsClient
  1619. resp, e := client.Index().Index(indexName).Id(docId).BodyJson(item).Refresh("true").Do(context.Background())
  1620. if e != nil {
  1621. err = fmt.Errorf("resp err, %v", e)
  1622. return
  1623. }
  1624. if resp.Status != 0 {
  1625. err = fmt.Errorf("result err, status: %d, result: %s", resp.Status, resp.Result)
  1626. return
  1627. }
  1628. err = nil
  1629. fmt.Println("excel write to es success", resp.Result)
  1630. return
  1631. }
  1632. // SearchExcelInfoData 查询es中的表格
  1633. func SearchExcelInfoData(indexName, keyword string, source, adminId int, queryIds, exceptIds []int, from, size int) (total int64, list []*excel.SearchExcelInfo, err error) {
  1634. list = make([]*excel.SearchExcelInfo, 0)
  1635. defer func() {
  1636. if err != nil {
  1637. tips := fmt.Sprintf("SearchExcelInfoData err: %v", err)
  1638. utils.FileLog.Info(tips)
  1639. }
  1640. }()
  1641. client := utils.EsClient
  1642. mustMap := make([]interface{}, 0)
  1643. mustNotMap := make([]interface{}, 0)
  1644. mustMap = append(mustMap, map[string]interface{}{
  1645. "term": map[string]interface{}{
  1646. "IsDelete": 0,
  1647. },
  1648. })
  1649. // 表格名称
  1650. shouldMap := make(map[string]interface{}, 0)
  1651. if keyword != "" {
  1652. shouldMap["should"] = []interface{}{
  1653. map[string]interface{}{
  1654. "match": map[string]interface{}{
  1655. "ExcelName": keyword,
  1656. },
  1657. },
  1658. }
  1659. //shouldMap := map[string]interface{}{
  1660. // "should": []interface{}{
  1661. // map[string]interface{}{
  1662. // "match": map[string]interface{}{
  1663. // "ExcelName": keyword,
  1664. // },
  1665. // },
  1666. // },
  1667. //}
  1668. }
  1669. // 表格来源
  1670. if source > 0 {
  1671. mustMap = append(mustMap, map[string]interface{}{
  1672. "term": map[string]interface{}{
  1673. "Source": source,
  1674. },
  1675. })
  1676. }
  1677. // 创建人
  1678. if adminId > 0 {
  1679. mustMap = append(mustMap, map[string]interface{}{
  1680. "term": map[string]interface{}{
  1681. "SysUserId": adminId,
  1682. },
  1683. })
  1684. }
  1685. // 查询和排除的表格IDs
  1686. if len(queryIds) > 0 {
  1687. mustMap = append(mustMap, map[string]interface{}{
  1688. "terms": map[string]interface{}{
  1689. "ExcelInfoId": queryIds,
  1690. },
  1691. })
  1692. }
  1693. if len(exceptIds) > 0 {
  1694. mustNotMap = append(mustNotMap, map[string]interface{}{
  1695. "terms": map[string]interface{}{
  1696. "ExcelInfoId": exceptIds,
  1697. },
  1698. })
  1699. }
  1700. // 关键字匹配
  1701. mustMap = append(mustMap, map[string]interface{}{
  1702. "bool": shouldMap,
  1703. })
  1704. queryMap := map[string]interface{}{
  1705. "query": map[string]interface{}{
  1706. "bool": map[string]interface{}{
  1707. "must": mustMap,
  1708. "must_not": mustNotMap,
  1709. //"should": shouldMap,
  1710. },
  1711. },
  1712. }
  1713. //jsonBytes, _ := json.Marshal(queryMap)
  1714. //fmt.Println(string(jsonBytes))
  1715. // 根据条件数量统计
  1716. requestTotalHits := client.Count(indexName).BodyJson(queryMap)
  1717. t, e := requestTotalHits.Do(context.Background())
  1718. if e != nil {
  1719. err = fmt.Errorf("total hits err: %v", e)
  1720. return
  1721. }
  1722. total = t
  1723. // 表格名称高亮,分页
  1724. highlightKeyName := "ExcelName"
  1725. queryMap["highlight"] = map[string]interface{}{
  1726. "fields": map[string]interface{}{
  1727. highlightKeyName: map[string]interface{}{},
  1728. },
  1729. "pre_tags": "<span style=\"color:#0052D9\">",
  1730. "post_tags": "</span>",
  1731. }
  1732. queryMap["from"] = from
  1733. queryMap["size"] = size
  1734. //jsonBytes, _ := json.Marshal(queryMap)
  1735. //fmt.Println(string(jsonBytes))
  1736. request := client.Search(indexName).Source(queryMap)
  1737. searchResp, e := request.Do(context.Background())
  1738. if e != nil {
  1739. err = fmt.Errorf("search do err: %v", e)
  1740. return
  1741. }
  1742. //fmt.Println(searchResp)
  1743. if searchResp.Status != 0 {
  1744. return
  1745. }
  1746. if searchResp.Hits == nil {
  1747. return
  1748. }
  1749. searchMap := make(map[string]string)
  1750. for _, v := range searchResp.Hits.Hits {
  1751. if _, ok := searchMap[v.Id]; ok {
  1752. continue
  1753. }
  1754. j, e := v.Source.MarshalJSON()
  1755. if e != nil {
  1756. err = fmt.Errorf("hits json err: %v", e)
  1757. return
  1758. }
  1759. item := new(excel.SearchExcelInfo)
  1760. if e = json.Unmarshal(j, &item); e != nil {
  1761. err = fmt.Errorf("hits json unmarshal err: %v", e)
  1762. return
  1763. }
  1764. if len(v.Highlight[highlightKeyName]) > 0 {
  1765. item.SearchText = v.Highlight[highlightKeyName][0]
  1766. } else {
  1767. item.SearchText = item.ExcelName
  1768. }
  1769. list = append(list, item)
  1770. searchMap[v.Id] = v.Id
  1771. }
  1772. return
  1773. }
  1774. // EsAddOrEditDataSourceIndex 新增/修改es中的数据源指标
  1775. func EsAddOrEditDataSourceIndex(indexName, docId string, item *dataSourceModel.SearchDataSource) (err error) {
  1776. defer func() {
  1777. if err != nil {
  1778. tips := fmt.Sprintf("EsAddOrEditDataSourceIndex err: %v", err)
  1779. utils.FileLog.Info(tips)
  1780. }
  1781. }()
  1782. client := utils.EsClient
  1783. resp, e := client.Index().Index(indexName).Id(docId).BodyJson(item).Refresh("true").Do(context.Background())
  1784. if e != nil {
  1785. err = fmt.Errorf("resp err, %v", e)
  1786. return
  1787. }
  1788. if resp.Status != 0 {
  1789. err = fmt.Errorf("result err, status: %d, result: %s", resp.Status, resp.Result)
  1790. return
  1791. }
  1792. err = nil
  1793. fmt.Println("data source write to es success", resp.Result)
  1794. return
  1795. }
  1796. // SearchDataSourceIndex 查询es中的数据源
  1797. func SearchDataSourceIndex(indexName, keyword string, source, subSource int, classifyIds, adminIds []int, frequency []string, from, size int) (total int64, list []*dataSourceModel.SearchDataSourceItem, err error) {
  1798. list = make([]*dataSourceModel.SearchDataSourceItem, 0)
  1799. defer func() {
  1800. if err != nil {
  1801. tips := fmt.Sprintf("SearchDataSourceIndex err: %v", err)
  1802. utils.FileLog.Info(tips)
  1803. }
  1804. }()
  1805. client := utils.EsClient
  1806. mustMap := make([]interface{}, 0)
  1807. mustNotMap := make([]interface{}, 0)
  1808. mustMap = append(mustMap, map[string]interface{}{
  1809. "term": map[string]interface{}{
  1810. "IsDeleted": 0,
  1811. },
  1812. })
  1813. // 指标编码/名称
  1814. shouldMap := make(map[string]interface{}, 0)
  1815. if keyword != "" {
  1816. shouldMap["should"] = []interface{}{
  1817. map[string]interface{}{
  1818. "match": map[string]interface{}{
  1819. "IndexCode": keyword,
  1820. },
  1821. },
  1822. map[string]interface{}{
  1823. "match": map[string]interface{}{
  1824. "IndexName": keyword,
  1825. },
  1826. },
  1827. }
  1828. //queryFields := []string{"IndexName.keyword", "IndexName.ik", "IndexName.ngram", "IndexCode.keyword", "IndexCode.ngram"}
  1829. //mustMap = append(mustMap, map[string]interface{}{
  1830. // "multi_match": map[string]interface{}{
  1831. // "query": keyword,
  1832. // "fields": queryFields,
  1833. // },
  1834. //})
  1835. }
  1836. // 来源/子来源
  1837. if source > 0 {
  1838. mustMap = append(mustMap, map[string]interface{}{
  1839. "term": map[string]interface{}{
  1840. "Source": source,
  1841. },
  1842. })
  1843. }
  1844. if subSource > 0 {
  1845. mustMap = append(mustMap, map[string]interface{}{
  1846. "term": map[string]interface{}{
  1847. "SubSource": subSource,
  1848. },
  1849. })
  1850. }
  1851. // 分类
  1852. if len(classifyIds) > 0 {
  1853. mustMap = append(mustMap, map[string]interface{}{
  1854. "term": map[string]interface{}{
  1855. "ClassifyId": classifyIds,
  1856. },
  1857. })
  1858. }
  1859. // 创建人
  1860. if len(adminIds) > 0 {
  1861. mustMap = append(mustMap, map[string]interface{}{
  1862. "term": map[string]interface{}{
  1863. "SysUserId": adminIds,
  1864. },
  1865. })
  1866. }
  1867. // 频度
  1868. if len(frequency) > 0 {
  1869. mustMap = append(mustMap, map[string]interface{}{
  1870. "term": map[string]interface{}{
  1871. "Frequency": frequency,
  1872. },
  1873. })
  1874. }
  1875. // 关键字匹配
  1876. mustMap = append(mustMap, map[string]interface{}{
  1877. "bool": shouldMap,
  1878. })
  1879. queryMap := map[string]interface{}{
  1880. "query": map[string]interface{}{
  1881. "bool": map[string]interface{}{
  1882. "must": mustMap,
  1883. "must_not": mustNotMap,
  1884. //"should": shouldMap,
  1885. },
  1886. },
  1887. }
  1888. //tj, _ := json.Marshal(queryMap)
  1889. //utils.FileLog.Info(string(tj))
  1890. // 根据条件数量统计
  1891. requestTotalHits := client.Count(indexName).BodyJson(queryMap)
  1892. t, e := requestTotalHits.Do(context.Background())
  1893. if e != nil {
  1894. err = fmt.Errorf("total hits err: %v", e)
  1895. return
  1896. }
  1897. total = t
  1898. // 表格名称高亮,分页
  1899. highlightKeyName := "IndexName"
  1900. //highlightIk := "IndexName.ik"
  1901. //highlightKeyword := "IndexName.keyword"
  1902. queryMap["highlight"] = map[string]interface{}{
  1903. "fields": map[string]interface{}{
  1904. highlightKeyName: map[string]interface{}{},
  1905. //highlightIk: map[string]interface{}{},
  1906. //highlightKeyword: map[string]interface{}{},
  1907. },
  1908. "pre_tags": "<span style=\"color:#0052D9\">",
  1909. "post_tags": "</span>",
  1910. }
  1911. queryMap["from"] = from
  1912. queryMap["size"] = size
  1913. qj, _ := json.Marshal(queryMap)
  1914. utils.FileLog.Info(string(qj))
  1915. request := client.Search(indexName).Source(queryMap)
  1916. searchResp, e := request.Do(context.Background())
  1917. if e != nil {
  1918. err = fmt.Errorf("search do err: %v", e)
  1919. return
  1920. }
  1921. rj, _ := json.Marshal(searchResp)
  1922. utils.FileLog.Info(string(rj))
  1923. if searchResp.Status != 0 {
  1924. return
  1925. }
  1926. if searchResp.Hits == nil {
  1927. return
  1928. }
  1929. searchMap := make(map[string]string)
  1930. for _, v := range searchResp.Hits.Hits {
  1931. if _, ok := searchMap[v.Id]; ok {
  1932. continue
  1933. }
  1934. j, e := v.Source.MarshalJSON()
  1935. if e != nil {
  1936. err = fmt.Errorf("hits json err: %v", e)
  1937. return
  1938. }
  1939. item := new(dataSourceModel.SearchDataSourceItem)
  1940. if e = json.Unmarshal(j, &item); e != nil {
  1941. err = fmt.Errorf("hits json unmarshal err: %v", e)
  1942. return
  1943. }
  1944. if len(v.Highlight[highlightKeyName]) > 0 {
  1945. item.SearchText = v.Highlight[highlightKeyName][0]
  1946. }
  1947. // 优先取keyword的高亮,其次是ik分词之后的高亮
  1948. //if len(v.Highlight) > 0 {
  1949. // if len(v.Highlight[highlightKeyword]) > 0 {
  1950. // item.SearchText = v.Highlight[highlightKeyword][0]
  1951. // }
  1952. // if len(v.Highlight[highlightKeyword]) == 0 && len(v.Highlight[highlightIk]) > 0 {
  1953. // item.SearchText = v.Highlight[highlightIk][0]
  1954. // }
  1955. //}
  1956. if item.SearchText == "" {
  1957. item.SearchText = item.IndexName
  1958. }
  1959. list = append(list, item)
  1960. searchMap[v.Id] = v.Id
  1961. }
  1962. return
  1963. }
  1964. // CreateEsIndex 创建ES索引
  1965. func CreateEsIndex(indexName, jsonMapping string) (exists bool, err error) {
  1966. defer func() {
  1967. if err != nil {
  1968. tips := fmt.Sprintf("CreateEsIndex err: %v", err)
  1969. utils.FileLog.Info(tips)
  1970. }
  1971. }()
  1972. client := utils.EsClient
  1973. // 校验是否存在
  1974. exist, e := client.IndexExists(indexName).Do(context.Background())
  1975. if e != nil {
  1976. err = fmt.Errorf("check exists err: %v", e)
  1977. return
  1978. }
  1979. exists = exist
  1980. if exists {
  1981. fmt.Printf("索引已存在: %s, 跳过\n", indexName)
  1982. return
  1983. }
  1984. // 创建索引及映射
  1985. createIndex, e := client.CreateIndex(indexName).BodyJson(jsonMapping).Do(context.Background())
  1986. if e != nil {
  1987. err = fmt.Errorf("create index err: %v", e)
  1988. return
  1989. }
  1990. fmt.Printf("create index success: %s\n", createIndex.Index)
  1991. return
  1992. }
  1993. // ClearEsIndex 清空指定索引的所有数据
  1994. func ClearEsIndex(indexName string) (err error) {
  1995. defer func() {
  1996. if err != nil {
  1997. tips := fmt.Sprintf("ClearEsIndex err: %v", err)
  1998. utils.FileLog.Info(tips)
  1999. }
  2000. }()
  2001. client := utils.EsClient
  2002. // 校验索引是否存在
  2003. exists, e := client.IndexExists(indexName).Do(context.Background())
  2004. if e != nil {
  2005. err = fmt.Errorf("check index exists err: %v", e)
  2006. return
  2007. }
  2008. if !exists {
  2009. err = fmt.Errorf("index does not exist: %s", indexName)
  2010. return
  2011. }
  2012. query := elastic.NewMatchAllQuery()
  2013. res, e := client.DeleteByQuery().
  2014. Index(indexName).
  2015. Query(query).
  2016. ProceedOnVersionConflict(). // 忽略版本冲突
  2017. Do(context.Background())
  2018. if e != nil {
  2019. err = fmt.Errorf("delete by query err: %v", e)
  2020. return
  2021. }
  2022. fmt.Printf("Cleared index: %s, Deleted documents count: %d\n", indexName, res.Deleted)
  2023. return
  2024. }