elastic.go 63 KB

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