elastic.go 56 KB

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