elastic.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. "github.com/olivere/elastic/v7"
  11. "strconv"
  12. "strings"
  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. // 删除数据
  37. func EsDeleteData(indexName, docId string) (err error) {
  38. client := utils.EsClient
  39. resp, err := client.Delete().Index(indexName).Id(docId).Do(context.Background())
  40. fmt.Println(resp)
  41. if err != nil {
  42. return
  43. }
  44. if resp.Status == 0 {
  45. fmt.Println("删除成功")
  46. } else {
  47. fmt.Println("AddData", resp.Status, resp.Result)
  48. }
  49. return
  50. }
  51. func MappingModify(indexName, mappingJson string) {
  52. client := utils.EsClient
  53. result, err := client.PutMapping().Index(indexName).BodyString(mappingJson).Do(context.Background())
  54. fmt.Println(err)
  55. fmt.Println(result)
  56. return
  57. }
  58. // EsAddOrEditReport 新增编辑es报告
  59. func EsAddOrEditReport(indexName, docId string, item *models.ElasticReportDetail) (err error) {
  60. defer func() {
  61. if err != nil {
  62. fmt.Println("EsAddOrEditReport Err:", err.Error())
  63. }
  64. }()
  65. client := utils.EsClient
  66. // docId为报告ID+章节ID
  67. searchById, err := client.Get().Index(indexName).Id(docId).Do(context.Background())
  68. if err != nil && !strings.Contains(err.Error(), "404") {
  69. fmt.Println("Get Err" + err.Error())
  70. return
  71. }
  72. if searchById != nil && searchById.Found {
  73. resp, err := client.Update().Index(indexName).Id(docId).Doc(map[string]interface{}{
  74. "ReportId": item.ReportId,
  75. "ReportChapterId": item.ReportChapterId,
  76. "Title": item.Title,
  77. "Abstract": item.Abstract,
  78. "BodyContent": item.BodyContent,
  79. "PublishTime": item.PublishTime,
  80. "PublishState": item.PublishState,
  81. "Author": item.Author,
  82. "ClassifyIdFirst": item.ClassifyIdFirst,
  83. "ClassifyNameFirst": item.ClassifyNameFirst,
  84. "ClassifyIdSecond": item.ClassifyIdSecond,
  85. "ClassifyNameSecond": item.ClassifyNameSecond,
  86. "Categories": item.Categories,
  87. "StageStr": item.StageStr,
  88. }).Do(context.Background())
  89. if err != nil {
  90. return err
  91. }
  92. //fmt.Println(resp.Status, resp.Result)
  93. if resp.Status == 0 {
  94. fmt.Println("修改成功" + docId)
  95. err = nil
  96. } else {
  97. fmt.Println("EditData", resp.Status, resp.Result)
  98. }
  99. } else {
  100. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
  101. if err != nil {
  102. fmt.Println("新增失败:", err.Error())
  103. return err
  104. }
  105. if resp.Status == 0 && resp.Result == "created" {
  106. fmt.Println("新增成功" + docId)
  107. return nil
  108. } else {
  109. fmt.Println("AddData", resp.Status, resp.Result)
  110. }
  111. }
  112. return
  113. }
  114. // AnalyzeResp 分词接口返回结构体
  115. type AnalyzeResp struct {
  116. Tokens []struct {
  117. EndOffset int64 `json:"end_offset"`
  118. Position int64 `json:"position"`
  119. StartOffset int64 `json:"start_offset"`
  120. Token string `json:"token"`
  121. Type string `json:"type"`
  122. } `json:"tokens"`
  123. }
  124. // Analyze 根据输入的文字获取分词后的文字
  125. func Analyze(content string) (contentList []string, err error) {
  126. defer func() {
  127. if err != nil {
  128. fmt.Println("Analyze Err:", err.Error())
  129. }
  130. }()
  131. client := utils.EsClient
  132. queryMap := map[string]string{
  133. "text": content,
  134. "analyzer": "ik_max_word",
  135. }
  136. res, err := client.PerformRequest(
  137. context.Background(),
  138. elastic.PerformRequestOptions{
  139. Method: "GET",
  140. Path: "/_analyze",
  141. Body: queryMap,
  142. Stream: false,
  143. },
  144. )
  145. if res.StatusCode == 200 {
  146. var analyzeResp AnalyzeResp
  147. tmpErr := json.Unmarshal(res.Body, &analyzeResp)
  148. if tmpErr != nil {
  149. err = errors.New("返回数据转结构体失败:" + tmpErr.Error())
  150. return
  151. }
  152. for _, v := range analyzeResp.Tokens {
  153. contentList = append(contentList, v.Token)
  154. }
  155. } else {
  156. err = errors.New("分词失败,返回code异常:" + strconv.Itoa(res.StatusCode))
  157. }
  158. return
  159. }
  160. // EsDeleteDataV2 删除es中的数据
  161. func EsDeleteDataV2(indexName, docId string) (err error) {
  162. defer func() {
  163. if err != nil {
  164. fmt.Println("EsDeleteEdbInfoData Err:", err.Error())
  165. }
  166. }()
  167. client := utils.EsClient
  168. resp, err := client.Delete().Index(indexName).Id(docId).Do(context.Background())
  169. fmt.Println(resp)
  170. if err != nil {
  171. return
  172. }
  173. if resp.Status == 0 {
  174. fmt.Println("删除成功")
  175. } else {
  176. fmt.Println("AddData", resp.Status, resp.Result)
  177. }
  178. return
  179. }
  180. // EsAddOrEditDataInterface 新增/修改es中的数据
  181. func EsAddOrEditDataInterface(indexName, docId string, item interface{}) (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. // SearchMyChartInfoData 查询es中的我的图表数据
  203. func SearchMyChartInfoData(indexName, keywordStr string, adminId int, noPermissionChartIdList []int, from, size int) (list []*data_manage.MyChartList, total int64, err error) {
  204. list = make([]*data_manage.MyChartList, 0)
  205. defer func() {
  206. if err != nil {
  207. fmt.Println("EsAddOrEditData Err:", err.Error())
  208. }
  209. }()
  210. client := utils.EsClient
  211. //queryString := elastic.NewQueryStringQuery(keywordStr)
  212. //boolQueryJson, err := json.Marshal(queryString)
  213. //if err != nil {
  214. // fmt.Println("boolQueryJson err:", err)
  215. //} else {
  216. // fmt.Println("boolQueryJson ", string(boolQueryJson))
  217. //}
  218. highlight := elastic.NewHighlight()
  219. highlight = highlight.Fields(elastic.NewHighlighterField("ChartName"))
  220. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  221. mustMap := make([]interface{}, 0)
  222. mustNotMap := make([]interface{}, 0)
  223. //指标来源
  224. if adminId > 0 {
  225. mustMap = append(mustMap, map[string]interface{}{
  226. "term": map[string]interface{}{
  227. "AdminId": adminId,
  228. //"Frequency.keyword": "月度",
  229. },
  230. })
  231. }
  232. //关键字匹配
  233. //shouldMap := map[string]interface{}{
  234. // "should": []interface{}{
  235. // map[string]interface{}{
  236. // "match": map[string]interface{}{
  237. // "ChartName": keywordStr,
  238. // //"Frequency.keyword": "月度",
  239. // },
  240. // },
  241. // // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  242. // map[string]interface{}{
  243. // "match": map[string]interface{}{
  244. // "ChartName": map[string]interface{}{
  245. // "query": keywordStr,
  246. // "operator": "and",
  247. // },
  248. // //"Frequency.keyword": "月度",
  249. // },
  250. // },
  251. // map[string]interface{}{
  252. // "match": map[string]interface{}{
  253. // "ChartNameEn": keywordStr,
  254. // //"Frequency.keyword": "月度",
  255. // },
  256. // },
  257. // // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  258. // map[string]interface{}{
  259. // "match": map[string]interface{}{
  260. // "ChartNameEn": map[string]interface{}{
  261. // "query": keywordStr,
  262. // "operator": "and",
  263. // },
  264. // //"Frequency.keyword": "月度",
  265. // },
  266. // },
  267. // },
  268. //}
  269. // 默认使用中文名字字段去匹配
  270. keywordNameKey := `ChartName`
  271. // 如果没有中文,则使用英文名称字段去匹配
  272. if !utils.ContainsChinese(keywordStr) {
  273. keywordNameKey = `ChartNameEn`
  274. }
  275. shouldMap := map[string]interface{}{
  276. "should": []interface{}{
  277. map[string]interface{}{
  278. "match": map[string]interface{}{
  279. keywordNameKey: keywordStr,
  280. //"Frequency.keyword": "月度",
  281. },
  282. },
  283. // 因为关键词被分了,所以需要用下面的语句来让他 整个词 查询,从而加重整词的权重
  284. map[string]interface{}{
  285. "match": map[string]interface{}{
  286. keywordNameKey: map[string]interface{}{
  287. "query": keywordStr,
  288. "operator": "and",
  289. },
  290. //"Frequency.keyword": "月度",
  291. },
  292. },
  293. },
  294. }
  295. mustMap = append(mustMap, map[string]interface{}{
  296. "bool": shouldMap,
  297. })
  298. // noPermissionEdbInfoIdList 无权限指标id
  299. if len(noPermissionChartIdList) > 0 {
  300. mustNotMap = append(mustNotMap, map[string]interface{}{
  301. "terms": map[string]interface{}{
  302. "ChartInfoId": noPermissionChartIdList,
  303. //"Frequency.keyword": "月度",
  304. },
  305. })
  306. }
  307. queryMap := map[string]interface{}{
  308. "query": map[string]interface{}{
  309. "bool": map[string]interface{}{
  310. "must": mustMap,
  311. "must_not": mustNotMap,
  312. //"should": shouldMap,
  313. },
  314. },
  315. }
  316. //根据条件数量统计
  317. requestTotalHits := client.Count(indexName).BodyJson(queryMap)
  318. total, err = requestTotalHits.Do(context.Background())
  319. if err != nil {
  320. return
  321. }
  322. // 分页查询
  323. queryMap["from"] = from
  324. queryMap["size"] = size
  325. jsonBytes, _ := json.Marshal(queryMap)
  326. fmt.Println(string(jsonBytes))
  327. request := client.Search(indexName).Highlight(highlight).Source(queryMap) // sets the JSON request
  328. //requestJson, err := json.Marshal(request)
  329. //if err != nil {
  330. // fmt.Println("requestJson err:", err)
  331. //}
  332. //fmt.Println("requestJson ", string(requestJson))
  333. searchMap := make(map[string]string)
  334. searchResp, err := request.Do(context.Background())
  335. if err != nil {
  336. return
  337. }
  338. fmt.Println(searchResp)
  339. fmt.Println(searchResp.Status)
  340. if searchResp.Status != 0 {
  341. return
  342. }
  343. if searchResp.Hits != nil {
  344. for _, v := range searchResp.Hits.Hits {
  345. if _, ok := searchMap[v.Id]; !ok {
  346. itemJson, tmpErr := v.Source.MarshalJSON()
  347. if tmpErr != nil {
  348. err = tmpErr
  349. fmt.Println("movieJson err:", err)
  350. return
  351. }
  352. chartInfoItem := new(data_manage.MyChartList)
  353. tmpErr = json.Unmarshal(itemJson, &chartInfoItem)
  354. if err != nil {
  355. fmt.Println("json.Unmarshal chartInfoJson err:", err)
  356. err = tmpErr
  357. return
  358. }
  359. if len(v.Highlight["ChartName"]) > 0 {
  360. chartInfoItem.ChartName = v.Highlight["ChartName"][0]
  361. }
  362. list = append(list, chartInfoItem)
  363. searchMap[v.Id] = v.Id
  364. }
  365. }
  366. }
  367. //for _, v := range result {
  368. // fmt.Println(v)
  369. //}
  370. return
  371. }