elastic.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. package elastic
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "eta_gn/eta_api/models"
  7. "eta_gn/eta_api/models/data_manage"
  8. "eta_gn/eta_api/utils"
  9. "fmt"
  10. "strconv"
  11. "strings"
  12. "github.com/olivere/elastic/v7"
  13. )
  14. // indexName:索引名称
  15. // mappingJson:表结构
  16. func EsCreateIndex(indexName, mappingJson string) (err error) {
  17. client := utils.EsClient
  18. //定义表结构
  19. exists, err := client.IndexExists(indexName).Do(context.Background()) //<5>
  20. if err != nil {
  21. return
  22. }
  23. if !exists {
  24. resp, err := client.CreateIndex(indexName).BodyJson(mappingJson).Do(context.Background())
  25. //BodyJson(bodyJson).Do(context.Background())
  26. if err != nil {
  27. fmt.Println("CreateIndex Err:" + err.Error())
  28. return err
  29. }
  30. fmt.Println(resp.Index, resp.ShardsAcknowledged, resp.Acknowledged)
  31. } else {
  32. fmt.Println(indexName + " 已存在")
  33. }
  34. return
  35. }
  36. // EsDeleteIndex 删除索引
  37. func EsDeleteIndex(indexName string) (err error) {
  38. client := utils.EsClient
  39. //定义表结构
  40. exists, err := client.IndexExists(indexName).Do(context.Background()) //<5>
  41. if err != nil {
  42. return
  43. }
  44. if exists {
  45. resp, err := client.DeleteIndex(indexName).Do(context.Background())
  46. if err != nil {
  47. fmt.Println("DeleteIndex Err:" + err.Error())
  48. return err
  49. }
  50. fmt.Println(resp.Acknowledged)
  51. } else {
  52. fmt.Println(indexName + " 不存在")
  53. }
  54. return
  55. }
  56. // 删除数据
  57. func EsDeleteData(indexName, docId string) (err error) {
  58. client := utils.EsClient
  59. resp, err := client.Delete().Index(indexName).Id(docId).Do(context.Background())
  60. fmt.Println(resp)
  61. if err != nil {
  62. return
  63. }
  64. if resp.Status == 0 {
  65. fmt.Println("删除成功")
  66. } else {
  67. fmt.Println("AddData", resp.Status, resp.Result)
  68. }
  69. return
  70. }
  71. func MappingModify(indexName, mappingJson string) {
  72. client := utils.EsClient
  73. result, err := client.PutMapping().Index(indexName).BodyString(mappingJson).Do(context.Background())
  74. fmt.Println(err)
  75. fmt.Println(result)
  76. return
  77. }
  78. // EsAddOrEditReport 新增编辑es报告
  79. func EsAddOrEditReport(indexName, docId string, item *models.ElasticReportDetail) (err error) {
  80. defer func() {
  81. if err != nil {
  82. fmt.Println("EsAddOrEditReport Err:", err.Error())
  83. }
  84. }()
  85. client := utils.EsClient
  86. // docId为报告ID+章节ID
  87. searchById, err := client.Get().Index(indexName).Id(docId).Do(context.Background())
  88. if err != nil && !strings.Contains(err.Error(), "404") {
  89. fmt.Println("Get Err" + err.Error())
  90. return
  91. }
  92. if searchById != nil && searchById.Found {
  93. resp, err := client.Update().Index(indexName).Id(docId).Doc(map[string]interface{}{
  94. "ReportId": item.ReportId,
  95. "ReportChapterId": item.ReportChapterId,
  96. "Title": item.Title,
  97. "Abstract": item.Abstract,
  98. "BodyContent": item.BodyContent,
  99. "PublishTime": item.PublishTime,
  100. "PublishState": item.PublishState,
  101. "Author": item.Author,
  102. "ClassifyIdFirst": item.ClassifyIdFirst,
  103. "ClassifyNameFirst": item.ClassifyNameFirst,
  104. "ClassifyIdSecond": item.ClassifyIdSecond,
  105. "ClassifyNameSecond": item.ClassifyNameSecond,
  106. "Categories": item.Categories,
  107. "StageStr": item.StageStr,
  108. }).Do(context.Background())
  109. if err != nil {
  110. return err
  111. }
  112. //fmt.Println(resp.Status, resp.Result)
  113. if resp.Status == 0 {
  114. fmt.Println("修改成功" + docId)
  115. err = nil
  116. } else {
  117. fmt.Println("EditData", resp.Status, resp.Result)
  118. }
  119. } else {
  120. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
  121. if err != nil {
  122. fmt.Println("新增失败:", err.Error())
  123. return err
  124. }
  125. if resp.Status == 0 && resp.Result == "created" {
  126. fmt.Println("新增成功" + docId)
  127. return nil
  128. } else {
  129. fmt.Println("AddData", resp.Status, resp.Result)
  130. }
  131. }
  132. return
  133. }
  134. // AnalyzeResp 分词接口返回结构体
  135. type AnalyzeResp struct {
  136. Tokens []struct {
  137. EndOffset int64 `json:"end_offset"`
  138. Position int64 `json:"position"`
  139. StartOffset int64 `json:"start_offset"`
  140. Token string `json:"token"`
  141. Type string `json:"type"`
  142. } `json:"tokens"`
  143. }
  144. // Analyze 根据输入的文字获取分词后的文字
  145. func Analyze(content string) (contentList []string, err error) {
  146. defer func() {
  147. if err != nil {
  148. fmt.Println("Analyze Err:", err.Error())
  149. }
  150. }()
  151. client := utils.EsClient
  152. queryMap := map[string]string{
  153. "text": content,
  154. "analyzer": "ik_max_word",
  155. }
  156. res, err := client.PerformRequest(
  157. context.Background(),
  158. elastic.PerformRequestOptions{
  159. Method: "GET",
  160. Path: "/_analyze",
  161. Body: queryMap,
  162. Stream: false,
  163. },
  164. )
  165. if res.StatusCode == 200 {
  166. var analyzeResp AnalyzeResp
  167. tmpErr := json.Unmarshal(res.Body, &analyzeResp)
  168. if tmpErr != nil {
  169. err = errors.New("返回数据转结构体失败:" + tmpErr.Error())
  170. return
  171. }
  172. for _, v := range analyzeResp.Tokens {
  173. contentList = append(contentList, v.Token)
  174. }
  175. } else {
  176. err = errors.New("分词失败,返回code异常:" + strconv.Itoa(res.StatusCode))
  177. }
  178. return
  179. }
  180. // EsAddOrEditChartInfoData 新增/修改es中的图表数据
  181. func EsAddOrEditChartInfoData(indexName, docId string, item *data_manage.ChartInfo) (err error) {
  182. defer func() {
  183. if err != nil {
  184. fmt.Println("EsAddOrEditData Err:", err.Error())
  185. }
  186. }()
  187. client := utils.EsClient
  188. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
  189. if err != nil {
  190. fmt.Println("新增失败:", err.Error())
  191. return err
  192. }
  193. fmt.Println(resp)
  194. if resp.Status == 0 {
  195. fmt.Println("新增成功", resp.Result)
  196. err = nil
  197. } else {
  198. fmt.Println("AddData", resp.Status, resp.Result)
  199. }
  200. return
  201. }
  202. // EsDeleteDataV2 删除es中的数据
  203. func EsDeleteDataV2(indexName, docId string) (err error) {
  204. defer func() {
  205. if err != nil {
  206. fmt.Println("EsDeleteEdbInfoData Err:", err.Error())
  207. }
  208. }()
  209. client := utils.EsClient
  210. resp, err := client.Delete().Index(indexName).Id(docId).Do(context.Background())
  211. fmt.Println(resp)
  212. if err != nil {
  213. return
  214. }
  215. if resp.Status == 0 {
  216. fmt.Println("删除成功")
  217. } else {
  218. fmt.Println("AddData", resp.Status, resp.Result)
  219. }
  220. return
  221. }
  222. // SearchChartInfoData 查询es中的图表数据
  223. func SearchChartInfoData(indexName, keywordStr string, showSysId int, sourceList []int, noPermissionChartIdList []int, from, size int) (list []*data_manage.ChartInfo, total int64, err error) {
  224. list = make([]*data_manage.ChartInfo, 0)
  225. defer func() {
  226. if err != nil {
  227. fmt.Println("EsAddOrEditData Err:", err.Error())
  228. }
  229. }()
  230. client := utils.EsClient
  231. //queryString := elastic.NewQueryStringQuery(keywordStr)
  232. //boolQueryJson, err := json.Marshal(queryString)
  233. //if err != nil {
  234. // fmt.Println("boolQueryJson err:", err)
  235. //} else {
  236. // fmt.Println("boolQueryJson ", string(boolQueryJson))
  237. //}
  238. highlight := elastic.NewHighlight()
  239. highlight = highlight.Fields(elastic.NewHighlighterField("ChartName"))
  240. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  241. mustMap := make([]interface{}, 0)
  242. mustNotMap := make([]interface{}, 0)
  243. //指标来源
  244. if showSysId > 0 {
  245. mustMap = append(mustMap, map[string]interface{}{
  246. "term": map[string]interface{}{
  247. "SysUserId": showSysId,
  248. //"Frequency.keyword": "月度",
  249. },
  250. })
  251. }
  252. mustMap = append(mustMap, map[string]interface{}{
  253. "terms": map[string]interface{}{
  254. "Source": sourceList,
  255. },
  256. })
  257. //关键字匹配
  258. //shouldMap := map[string]interface{}{
  259. // "should": []interface{}{
  260. // map[string]interface{}{
  261. // "match": map[string]interface{}{
  262. // "ChartName": keywordStr,
  263. // //"Frequency.keyword": "月度",
  264. // },
  265. // },
  266. // // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  267. // map[string]interface{}{
  268. // "match": map[string]interface{}{
  269. // "ChartName": map[string]interface{}{
  270. // "query": keywordStr,
  271. // "operator": "and",
  272. // },
  273. // //"Frequency.keyword": "月度",
  274. // },
  275. // },
  276. // map[string]interface{}{
  277. // "match": map[string]interface{}{
  278. // "ChartNameEn": keywordStr,
  279. // //"Frequency.keyword": "月度",
  280. // },
  281. // },
  282. // // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  283. // map[string]interface{}{
  284. // "match": map[string]interface{}{
  285. // "ChartNameEn": map[string]interface{}{
  286. // "query": keywordStr,
  287. // "operator": "and",
  288. // },
  289. // //"Frequency.keyword": "月度",
  290. // },
  291. // },
  292. // },
  293. //}
  294. // 默认使用中文名字字段去匹配
  295. keywordNameKey := `ChartName`
  296. // 如果没有中文,则使用英文名称字段去匹配
  297. if !utils.ContainsChinese(keywordStr) {
  298. keywordNameKey = `ChartNameEn`
  299. }
  300. shouldMap := map[string]interface{}{
  301. "should": []interface{}{
  302. map[string]interface{}{
  303. "match": map[string]interface{}{
  304. keywordNameKey: keywordStr,
  305. //"Frequency.keyword": "月度",
  306. },
  307. },
  308. // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  309. map[string]interface{}{
  310. "match": map[string]interface{}{
  311. keywordNameKey: map[string]interface{}{
  312. "query": keywordStr,
  313. "operator": "and",
  314. },
  315. //"Frequency.keyword": "月度",
  316. },
  317. },
  318. },
  319. }
  320. mustMap = append(mustMap, map[string]interface{}{
  321. "bool": shouldMap,
  322. })
  323. // noPermissionEdbInfoIdList 无权限指标id
  324. if len(noPermissionChartIdList) > 0 {
  325. mustNotMap = append(mustNotMap, map[string]interface{}{
  326. "terms": map[string]interface{}{
  327. "ChartInfoId": noPermissionChartIdList,
  328. //"Frequency.keyword": "月度",
  329. },
  330. })
  331. }
  332. queryMap := map[string]interface{}{
  333. "query": map[string]interface{}{
  334. "bool": map[string]interface{}{
  335. "must": mustMap,
  336. "must_not": mustNotMap,
  337. //"should": shouldMap,
  338. },
  339. },
  340. }
  341. //根据条件数量统计
  342. requestTotalHits := client.Count(indexName).BodyJson(queryMap)
  343. total, err = requestTotalHits.Do(context.Background())
  344. if err != nil {
  345. return
  346. }
  347. // 分页查询
  348. queryMap["from"] = from
  349. queryMap["size"] = size
  350. jsonBytes, _ := json.Marshal(queryMap)
  351. fmt.Println(string(jsonBytes))
  352. request := client.Search(indexName).Highlight(highlight).Source(queryMap) // sets the JSON request
  353. //requestJson, err := json.Marshal(request)
  354. //if err != nil {
  355. // fmt.Println("requestJson err:", err)
  356. //}
  357. //fmt.Println("requestJson ", string(requestJson))
  358. searchMap := make(map[string]string)
  359. searchResp, err := request.Do(context.Background())
  360. if err != nil {
  361. return
  362. }
  363. fmt.Println(searchResp)
  364. fmt.Println(searchResp.Status)
  365. if searchResp.Status != 0 {
  366. return
  367. }
  368. if searchResp.Hits != nil {
  369. for _, v := range searchResp.Hits.Hits {
  370. if _, ok := searchMap[v.Id]; !ok {
  371. itemJson, tmpErr := v.Source.MarshalJSON()
  372. if tmpErr != nil {
  373. err = tmpErr
  374. fmt.Println("movieJson err:", err)
  375. return
  376. }
  377. chartInfoItem := new(data_manage.ChartInfo)
  378. tmpErr = json.Unmarshal(itemJson, &chartInfoItem)
  379. if err != nil {
  380. fmt.Println("json.Unmarshal chartInfoJson err:", err)
  381. err = tmpErr
  382. return
  383. }
  384. if len(v.Highlight["ChartName"]) > 0 {
  385. chartInfoItem.ChartName = v.Highlight["ChartName"][0]
  386. }
  387. list = append(list, chartInfoItem)
  388. searchMap[v.Id] = v.Id
  389. }
  390. }
  391. }
  392. //for _, v := range result {
  393. // fmt.Println(v)
  394. //}
  395. return
  396. }
  397. // EsAddOrEditDataInterface 新增/修改es中的数据
  398. func EsAddOrEditDataInterface(indexName, docId string, item interface{}) (err error) {
  399. defer func() {
  400. if err != nil {
  401. fmt.Println("EsAddOrEditData Err:", err.Error())
  402. }
  403. }()
  404. client := utils.EsClient
  405. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
  406. if err != nil {
  407. fmt.Println("新增失败:", err.Error())
  408. return err
  409. }
  410. fmt.Println(resp)
  411. if resp.Status == 0 {
  412. fmt.Println("新增成功", resp.Result)
  413. err = nil
  414. } else {
  415. fmt.Println("AddData", resp.Status, resp.Result)
  416. }
  417. return
  418. }
  419. // SearchMyChartInfoData 查询es中的我的图表数据
  420. func SearchMyChartInfoData(indexName, keywordStr string, adminId int, noPermissionChartIdList []int, from, size int) (list []*data_manage.MyChartList, total int64, err error) {
  421. list = make([]*data_manage.MyChartList, 0)
  422. defer func() {
  423. if err != nil {
  424. fmt.Println("EsAddOrEditData Err:", err.Error())
  425. }
  426. }()
  427. client := utils.EsClient
  428. //queryString := elastic.NewQueryStringQuery(keywordStr)
  429. //boolQueryJson, err := json.Marshal(queryString)
  430. //if err != nil {
  431. // fmt.Println("boolQueryJson err:", err)
  432. //} else {
  433. // fmt.Println("boolQueryJson ", string(boolQueryJson))
  434. //}
  435. highlight := elastic.NewHighlight()
  436. highlight = highlight.Fields(elastic.NewHighlighterField("ChartName"))
  437. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  438. mustMap := make([]interface{}, 0)
  439. mustNotMap := make([]interface{}, 0)
  440. //指标来源
  441. if adminId > 0 {
  442. mustMap = append(mustMap, map[string]interface{}{
  443. "term": map[string]interface{}{
  444. "AdminId": adminId,
  445. //"Frequency.keyword": "月度",
  446. },
  447. })
  448. }
  449. //关键字匹配
  450. //shouldMap := map[string]interface{}{
  451. // "should": []interface{}{
  452. // map[string]interface{}{
  453. // "match": map[string]interface{}{
  454. // "ChartName": keywordStr,
  455. // //"Frequency.keyword": "月度",
  456. // },
  457. // },
  458. // // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  459. // map[string]interface{}{
  460. // "match": map[string]interface{}{
  461. // "ChartName": map[string]interface{}{
  462. // "query": keywordStr,
  463. // "operator": "and",
  464. // },
  465. // //"Frequency.keyword": "月度",
  466. // },
  467. // },
  468. // map[string]interface{}{
  469. // "match": map[string]interface{}{
  470. // "ChartNameEn": keywordStr,
  471. // //"Frequency.keyword": "月度",
  472. // },
  473. // },
  474. // // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  475. // map[string]interface{}{
  476. // "match": map[string]interface{}{
  477. // "ChartNameEn": map[string]interface{}{
  478. // "query": keywordStr,
  479. // "operator": "and",
  480. // },
  481. // //"Frequency.keyword": "月度",
  482. // },
  483. // },
  484. // },
  485. //}
  486. // 默认使用中文名字字段去匹配
  487. keywordNameKey := `ChartName`
  488. // 如果没有中文,则使用英文名称字段去匹配
  489. if !utils.ContainsChinese(keywordStr) {
  490. keywordNameKey = `ChartNameEn`
  491. }
  492. shouldMap := map[string]interface{}{
  493. "should": []interface{}{
  494. map[string]interface{}{
  495. "match": map[string]interface{}{
  496. keywordNameKey: keywordStr,
  497. //"Frequency.keyword": "月度",
  498. },
  499. },
  500. // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  501. map[string]interface{}{
  502. "match": map[string]interface{}{
  503. keywordNameKey: map[string]interface{}{
  504. "query": keywordStr,
  505. "operator": "and",
  506. },
  507. //"Frequency.keyword": "月度",
  508. },
  509. },
  510. },
  511. }
  512. mustMap = append(mustMap, map[string]interface{}{
  513. "bool": shouldMap,
  514. })
  515. // noPermissionEdbInfoIdList 无权限指标id
  516. if len(noPermissionChartIdList) > 0 {
  517. mustNotMap = append(mustNotMap, map[string]interface{}{
  518. "terms": map[string]interface{}{
  519. "ChartInfoId": noPermissionChartIdList,
  520. //"Frequency.keyword": "月度",
  521. },
  522. })
  523. }
  524. queryMap := map[string]interface{}{
  525. "query": map[string]interface{}{
  526. "bool": map[string]interface{}{
  527. "must": mustMap,
  528. "must_not": mustNotMap,
  529. //"should": shouldMap,
  530. },
  531. },
  532. }
  533. //根据条件数量统计
  534. requestTotalHits := client.Count(indexName).BodyJson(queryMap)
  535. total, err = requestTotalHits.Do(context.Background())
  536. if err != nil {
  537. return
  538. }
  539. // 分页查询
  540. queryMap["from"] = from
  541. queryMap["size"] = size
  542. jsonBytes, _ := json.Marshal(queryMap)
  543. fmt.Println(string(jsonBytes))
  544. request := client.Search(indexName).Highlight(highlight).Source(queryMap) // sets the JSON request
  545. //requestJson, err := json.Marshal(request)
  546. //if err != nil {
  547. // fmt.Println("requestJson err:", err)
  548. //}
  549. //fmt.Println("requestJson ", string(requestJson))
  550. searchMap := make(map[string]string)
  551. searchResp, err := request.Do(context.Background())
  552. if err != nil {
  553. return
  554. }
  555. fmt.Println(searchResp)
  556. fmt.Println(searchResp.Status)
  557. if searchResp.Status != 0 {
  558. return
  559. }
  560. if searchResp.Hits != nil {
  561. for _, v := range searchResp.Hits.Hits {
  562. if _, ok := searchMap[v.Id]; !ok {
  563. itemJson, tmpErr := v.Source.MarshalJSON()
  564. if tmpErr != nil {
  565. err = tmpErr
  566. fmt.Println("movieJson err:", err)
  567. return
  568. }
  569. chartInfoItem := new(data_manage.MyChartList)
  570. tmpErr = json.Unmarshal(itemJson, &chartInfoItem)
  571. if err != nil {
  572. fmt.Println("json.Unmarshal chartInfoJson err:", err)
  573. err = tmpErr
  574. return
  575. }
  576. if len(v.Highlight["ChartName"]) > 0 {
  577. chartInfoItem.ChartName = v.Highlight["ChartName"][0]
  578. }
  579. list = append(list, chartInfoItem)
  580. searchMap[v.Id] = v.Id
  581. }
  582. }
  583. }
  584. //for _, v := range result {
  585. // fmt.Println(v)
  586. //}
  587. return
  588. }