edb_info_elastic.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. package data
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/olivere/elastic/v7"
  7. "hongze/hz_crm_api/models/data_manage"
  8. "hongze/hz_crm_api/utils"
  9. "log"
  10. "os"
  11. "strconv"
  12. "strings"
  13. )
  14. const (
  15. ES_URL = "http://es-cn-nif227b580019rgw6.public.elasticsearch.aliyuncs.com:9200" //<1>
  16. ES_USERNAME = "elastic" //<2>
  17. ES_PASSWORD = "hongze@2021" //<3>
  18. )
  19. func NewClient() (client *elastic.Client, err error) {
  20. errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
  21. file := ""
  22. if utils.RunMode == "release" {
  23. file = `./rdlucklog/eslog.log`
  24. } else {
  25. file = `./rdlucklog/eslog.log`
  26. }
  27. logFile, _ := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
  28. client, err = elastic.NewClient(
  29. elastic.SetURL(ES_URL),
  30. elastic.SetBasicAuth(ES_USERNAME, ES_PASSWORD),
  31. elastic.SetTraceLog(log.New(logFile, "ES-TRACE: ", 0)),
  32. elastic.SetSniff(false), elastic.SetErrorLog(errorlog))
  33. return
  34. }
  35. func CreateEdbInfoIndex() {
  36. indexName := utils.DATA_INDEX_NAME
  37. mappingJson := `{
  38. "mappings": {
  39. "dynamic": true,
  40. "properties": {
  41. "EdbInfoId": {
  42. "type": "integer"
  43. },
  44. "SourceName": {
  45. "type": "text",
  46. "term_vector": "with_positions_offsets",
  47. "analyzer": "ik_smart"
  48. },
  49. "EdbCode": {
  50. "type": "text",
  51. "term_vector": "with_positions_offsets",
  52. "analyzer": "ik_smart"
  53. },
  54. "EdbName": {
  55. "type": "text",
  56. "term_vector": "with_positions_offsets",
  57. "analyzer": "ik_smart"
  58. },
  59. "Frequency": {
  60. "type": "text",
  61. "term_vector": "with_positions_offsets",
  62. "analyzer": "ik_smart"
  63. },
  64. "UniqueCode": {
  65. "type": "text",
  66. "term_vector": "with_positions_offsets"
  67. },
  68. "Unit": {
  69. "type": "text",
  70. "term_vector": "with_positions_offsets"
  71. }
  72. }
  73. }
  74. }`
  75. EsCreateIndex(indexName, mappingJson)
  76. }
  77. // indexName:索引名称
  78. // mappingJson:表结构
  79. func EsCreateIndex(indexName, mappingJson string) (err error) {
  80. client, err := NewClient()
  81. if err != nil {
  82. return
  83. }
  84. //定义表结构
  85. exists, err := client.IndexExists(indexName).Do(context.Background()) //<5>
  86. if err != nil {
  87. return
  88. }
  89. if !exists {
  90. resp, err := client.CreateIndex(indexName).BodyJson(mappingJson).Do(context.Background())
  91. //BodyJson(bodyJson).Do(context.Background())
  92. if err != nil {
  93. fmt.Println("CreateIndex Err:" + err.Error())
  94. return err
  95. }
  96. fmt.Println(resp.Index, resp.ShardsAcknowledged, resp.Acknowledged)
  97. } else {
  98. fmt.Println(indexName + " 已存在")
  99. }
  100. return
  101. }
  102. func AddAllEdbInfo() {
  103. allList, err := data_manage.GetEdbInfoAllList()
  104. if err != nil {
  105. fmt.Println("GetArticleAll Err:", err.Error())
  106. return
  107. }
  108. indexName := "hz_data_lib_v1"
  109. for _, v := range allList {
  110. EsAddOrEditEdbInfo(indexName, strconv.Itoa(v.EdbInfoId), v)
  111. fmt.Println(v.EdbInfoId)
  112. }
  113. }
  114. // 新增和修改数据
  115. func EsAddOrEditEdbInfo(indexName, docId string, item *data_manage.EdbInfo) (err error) {
  116. defer func() {
  117. if err != nil {
  118. fmt.Println("EsAddOrEditEdbInfo Err:", err.Error())
  119. }
  120. }()
  121. client, err := NewClient()
  122. if err != nil {
  123. return
  124. }
  125. searchById, err := client.Get().Index(indexName).Id(docId).Do(context.Background())
  126. if err != nil && !strings.Contains(err.Error(), "404") {
  127. fmt.Println("Get Err" + err.Error())
  128. return
  129. }
  130. if searchById != nil && searchById.Found {
  131. resp, err := client.Update().Index(indexName).Id(docId).Doc(map[string]interface{}{
  132. "EdbInfoId": item.EdbInfoId,
  133. "EdbCode": item.EdbCode,
  134. "EdbName": item.EdbName,
  135. "Frequency": item.Frequency,
  136. "SourceName": item.SourceName,
  137. "UniqueCode": item.UniqueCode,
  138. "Unit": item.Unit,
  139. }).Do(context.Background())
  140. if err != nil {
  141. return err
  142. }
  143. fmt.Println(resp.Status, resp.Result)
  144. if resp.Status == 0 {
  145. fmt.Println("修改成功")
  146. } else {
  147. fmt.Println("EditData", resp.Status, resp.Result)
  148. }
  149. } else {
  150. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
  151. if err != nil {
  152. fmt.Println("新增失败:", err.Error())
  153. return err
  154. }
  155. if resp.Status == 0 && resp.Result == "created" {
  156. fmt.Println("新增成功")
  157. err = nil
  158. } else {
  159. fmt.Println("AddData", resp.Status, resp.Result)
  160. }
  161. }
  162. return
  163. }
  164. // 删除数据
  165. func EsDeleteEdbInfo(docId int) (err error) {
  166. indexName := utils.DATA_INDEX_NAME
  167. client, err := NewClient()
  168. if err != nil {
  169. return
  170. }
  171. resp, err := client.Delete().Index(indexName).Id(strconv.Itoa(docId)).Do(context.Background())
  172. fmt.Println(resp)
  173. if err != nil {
  174. return
  175. }
  176. if resp.Status == 0 {
  177. fmt.Println("删除成功")
  178. } else {
  179. fmt.Println("AddData", resp.Status, resp.Result)
  180. }
  181. return
  182. }
  183. func MappingModify(indexName, mappingJson string) {
  184. client, err := NewClient()
  185. if err != nil {
  186. return
  187. }
  188. result, err := client.PutMapping().Index(indexName).BodyString(mappingJson).Do(context.Background())
  189. fmt.Println(err)
  190. fmt.Println(result)
  191. return
  192. }
  193. // 搜索指标信息
  194. func EsSearchEdbInfo(indexName, keyWord string, filterSource int) (result []*data_manage.EdbInfoList, err error) {
  195. client, err := NewClient()
  196. if keyWord != "" {
  197. keyWordArr := strings.Split(keyWord, " ")
  198. existMap := make(map[int]string)
  199. for _, searchKey := range keyWordArr {
  200. matchArr := make([]elastic.Query, 0)
  201. boolquery := elastic.NewBoolQuery()
  202. multiMatch := elastic.NewMultiMatchQuery(searchKey, "EdbName", "EdbCode").Analyzer("ik_smart")
  203. matchArr = append(matchArr, multiMatch)
  204. if filterSource == 2 {
  205. matchPhrase := elastic.NewMatchPhraseQuery("Frequency", "月度")
  206. matchArr = append(matchArr, matchPhrase)
  207. }
  208. boolquery.Must(matchArr...)
  209. //request := client.Search(indexName).Sort("CreateTime", false).Query(boolquery)
  210. request := client.Search(indexName).Query(boolquery)
  211. searchByMatch, err := request.Do(context.Background())
  212. if err != nil {
  213. return nil, err
  214. }
  215. if searchByMatch != nil {
  216. if searchByMatch.Hits != nil {
  217. for _, v := range searchByMatch.Hits.Hits {
  218. edbInfoJson, err := v.Source.MarshalJSON()
  219. if err != nil {
  220. return nil, err
  221. }
  222. edbInfo := new(data_manage.EdbInfoList)
  223. err = json.Unmarshal(edbInfoJson, &edbInfo)
  224. if err != nil {
  225. return nil, err
  226. }
  227. if _, ok := existMap[edbInfo.EdbInfoId]; !ok {
  228. result = append(result, edbInfo)
  229. }
  230. existMap[edbInfo.EdbInfoId] = edbInfo.EdbCode
  231. }
  232. }
  233. }
  234. }
  235. }
  236. return
  237. }