elastic.go 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440
  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).Refresh("true").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": keyword,
  1821. },
  1822. },
  1823. map[string]interface{}{
  1824. "match": map[string]interface{}{
  1825. "IndexName": keyword,
  1826. },
  1827. },
  1828. }
  1829. //queryFields := []string{"IndexName.keyword", "IndexName.ik", "IndexName.ngram", "IndexCode.keyword", "IndexCode.ngram"}
  1830. //mustMap = append(mustMap, map[string]interface{}{
  1831. // "multi_match": map[string]interface{}{
  1832. // "query": keyword,
  1833. // "fields": queryFields,
  1834. // },
  1835. //})
  1836. }
  1837. // 来源/子来源
  1838. if source > 0 {
  1839. mustMap = append(mustMap, map[string]interface{}{
  1840. "term": map[string]interface{}{
  1841. "Source": source,
  1842. },
  1843. })
  1844. }
  1845. if subSource > 0 {
  1846. mustMap = append(mustMap, map[string]interface{}{
  1847. "term": map[string]interface{}{
  1848. "SubSource": subSource,
  1849. },
  1850. })
  1851. }
  1852. // 分类
  1853. if len(classifyIds) > 0 {
  1854. mustMap = append(mustMap, map[string]interface{}{
  1855. "term": map[string]interface{}{
  1856. "ClassifyId": classifyIds,
  1857. },
  1858. })
  1859. }
  1860. // 创建人
  1861. if len(adminIds) > 0 {
  1862. mustMap = append(mustMap, map[string]interface{}{
  1863. "term": map[string]interface{}{
  1864. "SysUserId": adminIds,
  1865. },
  1866. })
  1867. }
  1868. // 频度
  1869. if len(frequency) > 0 {
  1870. mustMap = append(mustMap, map[string]interface{}{
  1871. "term": map[string]interface{}{
  1872. "Frequency": frequency,
  1873. },
  1874. })
  1875. }
  1876. // 关键字匹配
  1877. mustMap = append(mustMap, map[string]interface{}{
  1878. "bool": shouldMap,
  1879. })
  1880. queryMap := map[string]interface{}{
  1881. "query": map[string]interface{}{
  1882. "bool": map[string]interface{}{
  1883. "must": mustMap,
  1884. "must_not": mustNotMap,
  1885. //"should": shouldMap,
  1886. },
  1887. },
  1888. }
  1889. //tj, _ := json.Marshal(queryMap)
  1890. //utils.FileLog.Info(string(tj))
  1891. // 根据条件数量统计
  1892. requestTotalHits := client.Count(indexName).BodyJson(queryMap)
  1893. t, e := requestTotalHits.Do(context.Background())
  1894. if e != nil {
  1895. err = fmt.Errorf("total hits err: %v", e)
  1896. return
  1897. }
  1898. total = t
  1899. // 表格名称高亮,分页
  1900. highlightKeyName := "IndexName"
  1901. //highlightIk := "IndexName.ik"
  1902. //highlightKeyword := "IndexName.keyword"
  1903. queryMap["highlight"] = map[string]interface{}{
  1904. "fields": map[string]interface{}{
  1905. highlightKeyName: map[string]interface{}{},
  1906. //highlightIk: map[string]interface{}{},
  1907. //highlightKeyword: map[string]interface{}{},
  1908. },
  1909. "pre_tags": "<span style=\"color:#0052D9\">",
  1910. "post_tags": "</span>",
  1911. }
  1912. queryMap["from"] = from
  1913. queryMap["size"] = size
  1914. qj, _ := json.Marshal(queryMap)
  1915. utils.FileLog.Info(string(qj))
  1916. request := client.Search(indexName).Source(queryMap)
  1917. searchResp, e := request.Do(context.Background())
  1918. if e != nil {
  1919. err = fmt.Errorf("search do err: %v", e)
  1920. return
  1921. }
  1922. rj, _ := json.Marshal(searchResp)
  1923. utils.FileLog.Info(string(rj))
  1924. if searchResp.Status != 0 {
  1925. return
  1926. }
  1927. if searchResp.Hits == nil {
  1928. return
  1929. }
  1930. searchMap := make(map[string]string)
  1931. for _, v := range searchResp.Hits.Hits {
  1932. if _, ok := searchMap[v.Id]; ok {
  1933. continue
  1934. }
  1935. j, e := v.Source.MarshalJSON()
  1936. if e != nil {
  1937. err = fmt.Errorf("hits json err: %v", e)
  1938. return
  1939. }
  1940. item := new(dataSourceModel.SearchDataSourceItem)
  1941. if e = json.Unmarshal(j, &item); e != nil {
  1942. err = fmt.Errorf("hits json unmarshal err: %v", e)
  1943. return
  1944. }
  1945. if len(v.Highlight[highlightKeyName]) > 0 {
  1946. item.SearchText = v.Highlight[highlightKeyName][0]
  1947. }
  1948. // 优先取keyword的高亮,其次是ik分词之后的高亮
  1949. //if len(v.Highlight) > 0 {
  1950. // if len(v.Highlight[highlightKeyword]) > 0 {
  1951. // item.SearchText = v.Highlight[highlightKeyword][0]
  1952. // }
  1953. // if len(v.Highlight[highlightKeyword]) == 0 && len(v.Highlight[highlightIk]) > 0 {
  1954. // item.SearchText = v.Highlight[highlightIk][0]
  1955. // }
  1956. //}
  1957. if item.SearchText == "" {
  1958. item.SearchText = item.IndexName
  1959. }
  1960. list = append(list, item)
  1961. searchMap[v.Id] = v.Id
  1962. }
  1963. return
  1964. }
  1965. // CreateEsIndex 创建ES索引
  1966. func CreateEsIndex(indexName, jsonMapping string) (exists bool, err error) {
  1967. defer func() {
  1968. if err != nil {
  1969. tips := fmt.Sprintf("CreateEsIndex err: %v", err)
  1970. utils.FileLog.Info(tips)
  1971. }
  1972. }()
  1973. client := utils.EsClient
  1974. // 校验是否存在
  1975. exist, e := client.IndexExists(indexName).Do(context.Background())
  1976. if e != nil {
  1977. err = fmt.Errorf("check exists err: %v", e)
  1978. return
  1979. }
  1980. exists = exist
  1981. if exists {
  1982. fmt.Printf("索引已存在: %s, 跳过\n", indexName)
  1983. return
  1984. }
  1985. // 创建索引及映射
  1986. createIndex, e := client.CreateIndex(indexName).BodyJson(jsonMapping).Do(context.Background())
  1987. if e != nil {
  1988. err = fmt.Errorf("create index err: %v", e)
  1989. return
  1990. }
  1991. fmt.Printf("create index success: %s\n", createIndex.Index)
  1992. return
  1993. }
  1994. // ClearEsIndex 清空指定索引的所有数据
  1995. func ClearEsIndex(indexName string) (err error) {
  1996. defer func() {
  1997. if err != nil {
  1998. tips := fmt.Sprintf("ClearEsIndex err: %v", err)
  1999. utils.FileLog.Info(tips)
  2000. }
  2001. }()
  2002. client := utils.EsClient
  2003. // 校验索引是否存在
  2004. exists, e := client.IndexExists(indexName).Do(context.Background())
  2005. if e != nil {
  2006. err = fmt.Errorf("check index exists err: %v", e)
  2007. return
  2008. }
  2009. if !exists {
  2010. err = fmt.Errorf("index does not exist: %s", indexName)
  2011. return
  2012. }
  2013. query := elastic.NewMatchAllQuery()
  2014. res, e := client.DeleteByQuery().
  2015. Index(indexName).
  2016. Query(query).
  2017. ProceedOnVersionConflict(). // 忽略版本冲突
  2018. Do(context.Background())
  2019. if e != nil {
  2020. err = fmt.Errorf("delete by query err: %v", e)
  2021. return
  2022. }
  2023. fmt.Printf("Cleared index: %s, Deleted documents count: %d\n", indexName, res.Deleted)
  2024. return
  2025. }
  2026. // SearchDataSourceIndexWithScroll 使用scroll API查询es中的数据源
  2027. func SearchDataSourceIndexWithScroll(indexName, keyword string, source, subSource int, classifyIds, adminIds []int, frequency []string, size int) (scrollId string, list []*dataSourceModel.SearchDataSourceItem, err error) {
  2028. list = make([]*dataSourceModel.SearchDataSourceItem, 0)
  2029. defer func() {
  2030. if err != nil {
  2031. tips := fmt.Sprintf("SearchDataSourceIndexWithScroll err: %v", err)
  2032. utils.FileLog.Info(tips)
  2033. }
  2034. }()
  2035. client := utils.EsClient
  2036. mustMap := make([]interface{}, 0)
  2037. mustNotMap := make([]interface{}, 0)
  2038. mustMap = append(mustMap, map[string]interface{}{
  2039. "term": map[string]interface{}{
  2040. "IsDeleted": 0,
  2041. },
  2042. })
  2043. // 指标编码/名称
  2044. shouldMap := make(map[string]interface{}, 0)
  2045. if keyword != "" {
  2046. shouldMap["should"] = []interface{}{
  2047. map[string]interface{}{
  2048. "match": map[string]interface{}{
  2049. "IndexCode": keyword,
  2050. },
  2051. },
  2052. map[string]interface{}{
  2053. "match": map[string]interface{}{
  2054. "IndexName": keyword,
  2055. },
  2056. },
  2057. }
  2058. }
  2059. // 来源/子来源
  2060. if source > 0 {
  2061. mustMap = append(mustMap, map[string]interface{}{
  2062. "term": map[string]interface{}{
  2063. "Source": source,
  2064. },
  2065. })
  2066. }
  2067. if subSource > 0 {
  2068. mustMap = append(mustMap, map[string]interface{}{
  2069. "term": map[string]interface{}{
  2070. "SubSource": subSource,
  2071. },
  2072. })
  2073. }
  2074. // 分类
  2075. if len(classifyIds) > 0 {
  2076. mustMap = append(mustMap, map[string]interface{}{
  2077. "term": map[string]interface{}{
  2078. "ClassifyId": classifyIds,
  2079. },
  2080. })
  2081. }
  2082. // 创建人
  2083. if len(adminIds) > 0 {
  2084. mustMap = append(mustMap, map[string]interface{}{
  2085. "term": map[string]interface{}{
  2086. "SysUserId": adminIds,
  2087. },
  2088. })
  2089. }
  2090. // 频度
  2091. if len(frequency) > 0 {
  2092. mustMap = append(mustMap, map[string]interface{}{
  2093. "term": map[string]interface{}{
  2094. "Frequency": frequency,
  2095. },
  2096. })
  2097. }
  2098. // 关键字匹配
  2099. mustMap = append(mustMap, map[string]interface{}{
  2100. "bool": shouldMap,
  2101. })
  2102. queryMap := map[string]interface{}{
  2103. "query": map[string]interface{}{
  2104. "bool": map[string]interface{}{
  2105. "must": mustMap,
  2106. "must_not": mustNotMap,
  2107. },
  2108. },
  2109. }
  2110. // 表格名称高亮
  2111. highlightKeyName := "IndexName"
  2112. queryMap["highlight"] = map[string]interface{}{
  2113. "fields": map[string]interface{}{
  2114. highlightKeyName: map[string]interface{}{},
  2115. },
  2116. "pre_tags": "<span style=\"color:#0052D9\">",
  2117. "post_tags": "</span>",
  2118. }
  2119. queryMap["size"] = size
  2120. // 使用scroll API
  2121. request := client.Scroll(indexName).Body(queryMap).Scroll("5m")
  2122. searchResp, e := request.Do(context.Background())
  2123. if e != nil {
  2124. err = fmt.Errorf("search do err: %v", e)
  2125. return
  2126. }
  2127. if searchResp.Status != 0 {
  2128. return
  2129. }
  2130. if searchResp.Hits == nil {
  2131. return
  2132. }
  2133. scrollId = searchResp.ScrollId
  2134. searchMap := make(map[string]string)
  2135. for _, v := range searchResp.Hits.Hits {
  2136. if _, ok := searchMap[v.Id]; ok {
  2137. continue
  2138. }
  2139. j, e := v.Source.MarshalJSON()
  2140. if e != nil {
  2141. err = fmt.Errorf("hits json err: %v", e)
  2142. return
  2143. }
  2144. item := new(dataSourceModel.SearchDataSourceItem)
  2145. if e = json.Unmarshal(j, &item); e != nil {
  2146. err = fmt.Errorf("hits json unmarshal err: %v", e)
  2147. return
  2148. }
  2149. if len(v.Highlight[highlightKeyName]) > 0 {
  2150. item.SearchText = v.Highlight[highlightKeyName][0]
  2151. }
  2152. if item.SearchText == "" {
  2153. item.SearchText = item.IndexName
  2154. }
  2155. list = append(list, item)
  2156. searchMap[v.Id] = v.Id
  2157. }
  2158. return
  2159. }
  2160. // ScrollDataSourceIndex 使用scroll API获取下一页数据
  2161. func ScrollDataSourceIndex(scrollId string) (nextScrollId string, list []*dataSourceModel.SearchDataSourceItem, err error) {
  2162. list = make([]*dataSourceModel.SearchDataSourceItem, 0)
  2163. defer func() {
  2164. if err != nil {
  2165. tips := fmt.Sprintf("ScrollDataSourceIndex err: %v", err)
  2166. utils.FileLog.Info(tips)
  2167. }
  2168. }()
  2169. client := utils.EsClient
  2170. // 使用scroll API获取下一页
  2171. request := client.Scroll().ScrollId(scrollId).Scroll("5m")
  2172. searchResp, e := request.Do(context.Background())
  2173. if e != nil {
  2174. if errors.Is(e, io.EOF) {
  2175. // 结束了,没有更多的数据了
  2176. return
  2177. }
  2178. err = fmt.Errorf("scroll do err: %v", e)
  2179. return
  2180. }
  2181. if searchResp.Status != 0 {
  2182. return
  2183. }
  2184. if searchResp.Hits == nil {
  2185. return
  2186. }
  2187. //理论上 scrollId 在整个 Scroll 生命周期中是固定不变的。
  2188. //不过为了代码可读性和未来可能的扩展性,仍保留 nextScrollId = searchResp.ScrollId 这一行代码,这样即使逻辑迁移或改动,也不会出错。
  2189. nextScrollId = searchResp.ScrollId
  2190. searchMap := make(map[string]string)
  2191. for _, v := range searchResp.Hits.Hits {
  2192. if _, ok := searchMap[v.Id]; ok {
  2193. continue
  2194. }
  2195. j, e := v.Source.MarshalJSON()
  2196. if e != nil {
  2197. err = fmt.Errorf("hits json err: %v", e)
  2198. return
  2199. }
  2200. item := new(dataSourceModel.SearchDataSourceItem)
  2201. if e = json.Unmarshal(j, &item); e != nil {
  2202. err = fmt.Errorf("hits json unmarshal err: %v", e)
  2203. return
  2204. }
  2205. if len(v.Highlight["IndexName"]) > 0 {
  2206. item.SearchText = v.Highlight["IndexName"][0]
  2207. }
  2208. if item.SearchText == "" {
  2209. item.SearchText = item.IndexName
  2210. }
  2211. list = append(list, item)
  2212. searchMap[v.Id] = v.Id
  2213. }
  2214. return
  2215. }
  2216. // ClearScrollDataSourceIndex
  2217. // @Description: 清除scroll查询
  2218. // @author: Roc
  2219. // @datetime 2025-05-08 10:17:01
  2220. // @param scrollId string
  2221. // @return nextScrollId string
  2222. // @return list []*dataSourceModel.SearchDataSourceItem
  2223. // @return err error
  2224. func ClearScrollDataSourceIndex(scrollId string) (nextScrollId string, list []*dataSourceModel.SearchDataSourceItem, err error) {
  2225. list = make([]*dataSourceModel.SearchDataSourceItem, 0)
  2226. defer func() {
  2227. if err != nil {
  2228. tips := fmt.Sprintf("ScrollDataSourceIndex err: %v", err)
  2229. utils.FileLog.Info(tips)
  2230. }
  2231. }()
  2232. client := utils.EsClient
  2233. // 使用scroll API获取下一页
  2234. request := client.ClearScroll().ScrollId(scrollId)
  2235. _, err = request.Do(context.Background())
  2236. return
  2237. }