elastic.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. // EsDeleteDataV2 删除es中的数据
  181. func EsDeleteDataV2(indexName, docId string) (err error) {
  182. defer func() {
  183. if err != nil {
  184. fmt.Println("EsDeleteEdbInfoData Err:", err.Error())
  185. }
  186. }()
  187. client := utils.EsClient
  188. resp, err := client.Delete().Index(indexName).Id(docId).Do(context.Background())
  189. fmt.Println(resp)
  190. if err != nil {
  191. return
  192. }
  193. if resp.Status == 0 {
  194. fmt.Println("删除成功")
  195. } else {
  196. fmt.Println("AddData", resp.Status, resp.Result)
  197. }
  198. return
  199. }
  200. // EsAddOrEditDataInterface 新增/修改es中的数据
  201. func EsAddOrEditDataInterface(indexName, docId string, item interface{}) (err error) {
  202. defer func() {
  203. if err != nil {
  204. fmt.Println("EsAddOrEditData Err:", err.Error())
  205. }
  206. }()
  207. client := utils.EsClient
  208. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
  209. if err != nil {
  210. fmt.Println("新增失败:", err.Error())
  211. return err
  212. }
  213. fmt.Println(resp)
  214. if resp.Status == 0 {
  215. fmt.Println("新增成功", resp.Result)
  216. err = nil
  217. } else {
  218. fmt.Println("AddData", resp.Status, resp.Result)
  219. }
  220. return
  221. }
  222. // SearchMyChartInfoData 查询es中的我的图表数据
  223. func SearchMyChartInfoData(indexName, keywordStr string, adminId int, noPermissionChartIdList []int, from, size int) (list []*data_manage.MyChartList, total int64, err error) {
  224. list = make([]*data_manage.MyChartList, 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 adminId > 0 {
  245. mustMap = append(mustMap, map[string]interface{}{
  246. "term": map[string]interface{}{
  247. "AdminId": adminId,
  248. //"Frequency.keyword": "月度",
  249. },
  250. })
  251. }
  252. //关键字匹配
  253. //shouldMap := map[string]interface{}{
  254. // "should": []interface{}{
  255. // map[string]interface{}{
  256. // "match": map[string]interface{}{
  257. // "ChartName": keywordStr,
  258. // //"Frequency.keyword": "月度",
  259. // },
  260. // },
  261. // // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  262. // map[string]interface{}{
  263. // "match": map[string]interface{}{
  264. // "ChartName": map[string]interface{}{
  265. // "query": keywordStr,
  266. // "operator": "and",
  267. // },
  268. // //"Frequency.keyword": "月度",
  269. // },
  270. // },
  271. // map[string]interface{}{
  272. // "match": map[string]interface{}{
  273. // "ChartNameEn": keywordStr,
  274. // //"Frequency.keyword": "月度",
  275. // },
  276. // },
  277. // // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  278. // map[string]interface{}{
  279. // "match": map[string]interface{}{
  280. // "ChartNameEn": map[string]interface{}{
  281. // "query": keywordStr,
  282. // "operator": "and",
  283. // },
  284. // //"Frequency.keyword": "月度",
  285. // },
  286. // },
  287. // },
  288. //}
  289. // 默认使用中文名字字段去匹配
  290. keywordNameKey := `ChartName`
  291. // 如果没有中文,则使用英文名称字段去匹配
  292. if !utils.ContainsChinese(keywordStr) {
  293. keywordNameKey = `ChartNameEn`
  294. }
  295. shouldMap := map[string]interface{}{
  296. "should": []interface{}{
  297. map[string]interface{}{
  298. "match": map[string]interface{}{
  299. keywordNameKey: keywordStr,
  300. //"Frequency.keyword": "月度",
  301. },
  302. },
  303. // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  304. map[string]interface{}{
  305. "match": map[string]interface{}{
  306. keywordNameKey: map[string]interface{}{
  307. "query": keywordStr,
  308. "operator": "and",
  309. },
  310. //"Frequency.keyword": "月度",
  311. },
  312. },
  313. },
  314. }
  315. mustMap = append(mustMap, map[string]interface{}{
  316. "bool": shouldMap,
  317. })
  318. // noPermissionEdbInfoIdList 无权限指标id
  319. if len(noPermissionChartIdList) > 0 {
  320. mustNotMap = append(mustNotMap, map[string]interface{}{
  321. "terms": map[string]interface{}{
  322. "ChartInfoId": noPermissionChartIdList,
  323. //"Frequency.keyword": "月度",
  324. },
  325. })
  326. }
  327. queryMap := map[string]interface{}{
  328. "query": map[string]interface{}{
  329. "bool": map[string]interface{}{
  330. "must": mustMap,
  331. "must_not": mustNotMap,
  332. //"should": shouldMap,
  333. },
  334. },
  335. }
  336. //根据条件数量统计
  337. requestTotalHits := client.Count(indexName).BodyJson(queryMap)
  338. total, err = requestTotalHits.Do(context.Background())
  339. if err != nil {
  340. return
  341. }
  342. // 分页查询
  343. queryMap["from"] = from
  344. queryMap["size"] = size
  345. jsonBytes, _ := json.Marshal(queryMap)
  346. fmt.Println(string(jsonBytes))
  347. request := client.Search(indexName).Highlight(highlight).Source(queryMap) // sets the JSON request
  348. //requestJson, err := json.Marshal(request)
  349. //if err != nil {
  350. // fmt.Println("requestJson err:", err)
  351. //}
  352. //fmt.Println("requestJson ", string(requestJson))
  353. searchMap := make(map[string]string)
  354. searchResp, err := request.Do(context.Background())
  355. if err != nil {
  356. return
  357. }
  358. fmt.Println(searchResp)
  359. fmt.Println(searchResp.Status)
  360. if searchResp.Status != 0 {
  361. return
  362. }
  363. if searchResp.Hits != nil {
  364. for _, v := range searchResp.Hits.Hits {
  365. if _, ok := searchMap[v.Id]; !ok {
  366. itemJson, tmpErr := v.Source.MarshalJSON()
  367. if tmpErr != nil {
  368. err = tmpErr
  369. fmt.Println("movieJson err:", err)
  370. return
  371. }
  372. chartInfoItem := new(data_manage.MyChartList)
  373. tmpErr = json.Unmarshal(itemJson, &chartInfoItem)
  374. if err != nil {
  375. fmt.Println("json.Unmarshal chartInfoJson err:", err)
  376. err = tmpErr
  377. return
  378. }
  379. if len(v.Highlight["ChartName"]) > 0 {
  380. chartInfoItem.ChartName = v.Highlight["ChartName"][0]
  381. }
  382. list = append(list, chartInfoItem)
  383. searchMap[v.Id] = v.Id
  384. }
  385. }
  386. }
  387. //for _, v := range result {
  388. // fmt.Println(v)
  389. //}
  390. return
  391. }