elastic.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. package services
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/olivere/elastic/v7"
  7. "hongze/hongze_cygx/models"
  8. "log"
  9. "os"
  10. "strconv"
  11. )
  12. func NewClient() (client *elastic.Client, err error) {
  13. errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
  14. file := "./rdlucklog/eslog.log"
  15. logFile, _ := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
  16. client, err = elastic.NewClient(
  17. elastic.SetURL(ES_URL),
  18. elastic.SetBasicAuth(ES_USERNAME, ES_PASSWORD),
  19. elastic.SetTraceLog(log.New(logFile, "ES-TRACE: ", 0)),
  20. elastic.SetSniff(false), elastic.SetErrorLog(errorlog))
  21. return
  22. }
  23. //indexName:索引名称
  24. //mappingJson:表结构
  25. func EsCreateIndex(indexName, mappingJson string) (err error) {
  26. client, err := NewClient()
  27. if err != nil {
  28. return
  29. }
  30. //定义表结构
  31. exists, err := client.IndexExists(indexName).Do(context.Background()) //<5>
  32. if err != nil {
  33. return
  34. }
  35. if !exists {
  36. resp, err := client.CreateIndex(indexName).BodyJson(mappingJson).Do(context.Background())
  37. //BodyJson(bodyJson).Do(context.Background())
  38. if err != nil {
  39. fmt.Println("CreateIndex Err:" + err.Error())
  40. return err
  41. }
  42. fmt.Println(resp.Index, resp.ShardsAcknowledged, resp.Acknowledged)
  43. } else {
  44. fmt.Println(indexName + " 已存在")
  45. }
  46. return
  47. }
  48. //新增数据
  49. func EsAddData(indexName, docId string, item interface{}) (err error) {
  50. client, err := NewClient()
  51. if err != nil {
  52. return
  53. }
  54. resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
  55. if err != nil {
  56. return
  57. }
  58. if resp.Status == 0 && resp.Result == "created" {
  59. fmt.Println("新增成功")
  60. } else {
  61. fmt.Println("AddData", resp.Status, resp.Result)
  62. }
  63. return
  64. }
  65. //删除数据
  66. func EsDeleteData(indexName, docId string) (err error) {
  67. client, err := NewClient()
  68. if err != nil {
  69. return
  70. }
  71. resp, err := client.Delete().Index(indexName).Id(docId).Do(context.Background())
  72. if err != nil {
  73. return
  74. }
  75. if resp.Status == 0 {
  76. fmt.Println("删除成功")
  77. } else {
  78. fmt.Println("AddData", resp.Status, resp.Result)
  79. }
  80. return
  81. }
  82. func MappingModify(indexName, mappingJson string) {
  83. client, err := NewClient()
  84. if err != nil {
  85. return
  86. }
  87. result, err := client.PutMapping().Index(indexName).BodyString(mappingJson).Do(context.Background())
  88. fmt.Println(err)
  89. fmt.Println(result)
  90. return
  91. }
  92. func EsMatchQuery(indexName, keyWord string) (result []*models.SearchItem, err error) {
  93. client, err := NewClient()
  94. pageSize := 20
  95. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  96. fmt.Println(keyWordArr)
  97. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  98. fmt.Println("-------------------------------")
  99. fmt.Println(keyWordArr)
  100. searchMap := make(map[int]int)
  101. boolquery := elastic.NewBoolQuery()
  102. keyLen := len(keyWordArr)
  103. n := float64(keyLen)
  104. matchArr := make([]elastic.Query, 0)
  105. matchq1 := elastic.NewMatchQuery("Title", keyWord).Boost(n + 1).Analyzer("ik_smart")
  106. matchq2 := elastic.NewMatchQuery("BodyText", keyWord).Boost(n + 1).Analyzer("ik_smart")
  107. matchArr = append(matchArr, matchq1)
  108. matchArr = append(matchArr, matchq2)
  109. for _, v := range keyWordArr {
  110. if v != "" {
  111. matchq1 := elastic.NewMatchQuery("Title", v).Boost(n).Analyzer("ik_smart")
  112. matchq2 := elastic.NewMatchQuery("BodyText", v).Boost(n).Analyzer("ik_smart")
  113. matchArr = append(matchArr, matchq1)
  114. matchArr = append(matchArr, matchq2)
  115. }
  116. n--
  117. }
  118. boolquery.Should(matchArr...)
  119. highlight := elastic.NewHighlight()
  120. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  121. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  122. request := client.Search(indexName).Highlight(highlight).Size(pageSize).Query(boolquery)
  123. searchByMatch, err := request.Do(context.Background())
  124. if searchByMatch.Hits != nil {
  125. for _, v := range searchByMatch.Hits.Hits {
  126. articleJson, err := v.Source.MarshalJSON()
  127. if err != nil {
  128. return nil, err
  129. }
  130. article := new(models.CygxArticle)
  131. err = json.Unmarshal(articleJson, &article)
  132. if err != nil {
  133. return nil, err
  134. }
  135. if _, ok := searchMap[article.ArticleId]; !ok {
  136. searchItem := new(models.SearchItem)
  137. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  138. if len(v.Highlight["BodyText"]) > 0 {
  139. searchItem.Body = v.Highlight["BodyText"]
  140. } else {
  141. bodyRune := []rune(article.BodyText)
  142. bodyRuneLen:=len(bodyRune)
  143. if bodyRuneLen>100 {
  144. bodyRuneLen=100
  145. }
  146. body:= string(bodyRune[:bodyRuneLen])
  147. fmt.Println(body)
  148. searchItem.Body = []string{body}
  149. }
  150. var title string
  151. if len(v.Highlight["Title"]) > 0 {
  152. title = v.Highlight["Title"][0]
  153. } else {
  154. title = article.Title
  155. }
  156. searchItem.Title = title
  157. searchItem.PublishDate = article.PublishDate
  158. result = append(result, searchItem)
  159. searchMap[article.ArticleId] = article.ArticleId
  160. }
  161. }
  162. }
  163. return
  164. }
  165. func EsMatchPhraseQuery(indexName, keyWord string) (result []*models.SearchItem, err error) {
  166. client, err := NewClient()
  167. pageSize := 20
  168. keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
  169. fmt.Println(keyWordArr)
  170. keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
  171. fmt.Println("-------------------------------")
  172. fmt.Println(keyWordArr)
  173. searchMap := make(map[int]int)
  174. boolquery := elastic.NewBoolQuery()
  175. //keyLen := len(keyWordArr)
  176. //n := float64(keyLen)
  177. matchArr := make([]elastic.Query, 0)
  178. //matchq1 := elastic.NewMatchQuery("Title", keyWord).Boost(n + 1).Analyzer("ik_smart")
  179. //matchq2 := elastic.NewMatchQuery("BodyText", keyWord).Boost(n + 1).Analyzer("ik_smart")
  180. matchq1 := elastic.NewMatchPhraseQuery("Title", keyWord) //.Analyzer("ik_smart")
  181. matchq2 := elastic.NewMatchPhraseQuery("BodyText", keyWord)
  182. matchArr = append(matchArr, matchq1)
  183. matchArr = append(matchArr, matchq2)
  184. //matchArr = append(matchArr, matchq2)
  185. //for _, v := range keyWordArr {
  186. // if v != "" {
  187. // matchq1 := elastic.NewMatchQuery("Title", v).Boost(n).Analyzer("ik_smart")
  188. // matchq2 := elastic.NewMatchQuery("BodyText", v).Boost(n).Analyzer("ik_smart")
  189. // matchArr = append(matchArr, matchq1)
  190. // matchArr = append(matchArr, matchq2)
  191. // }
  192. // n--
  193. //}
  194. //boolquery.Should(matchArr...)
  195. boolquery.Should(matchArr...)
  196. highlight := elastic.NewHighlight()
  197. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  198. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  199. request := client.Search(indexName).Highlight(highlight).Size(pageSize).Query(boolquery)
  200. searchByMatch, err := request.Do(context.Background())
  201. fmt.Println("err:", err, searchByMatch)
  202. return
  203. if searchByMatch.Hits != nil {
  204. for _, v := range searchByMatch.Hits.Hits {
  205. articleJson, err := v.Source.MarshalJSON()
  206. if err != nil {
  207. return nil, err
  208. }
  209. article := new(models.CygxArticle)
  210. err = json.Unmarshal(articleJson, &article)
  211. if err != nil {
  212. return nil, err
  213. }
  214. if _, ok := searchMap[article.ArticleId]; !ok {
  215. searchItem := new(models.SearchItem)
  216. searchItem.ArticleId, _ = strconv.Atoi(v.Id)
  217. searchItem.Body = v.Highlight["BodyText"]
  218. var title string
  219. if len(v.Highlight["Title"]) > 0 {
  220. title = v.Highlight["Title"][0]
  221. } else {
  222. title = article.Title
  223. }
  224. searchItem.Title = title
  225. searchItem.PublishDate = article.PublishDate
  226. result = append(result, searchItem)
  227. searchMap[article.ArticleId] = article.ArticleId
  228. }
  229. }
  230. }
  231. return
  232. }