elastic.go 63 KB

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