elasticsearch.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package services
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/olivere/elastic/v7"
  7. )
  8. const (
  9. ES_URL = "http://es-cn-nif227b580019rgw6.public.elasticsearch.aliyuncs.com:9200" //<1>
  10. ES_USERNAME = "elastic" //<2>
  11. ES_PASSWORD = "hongze@2021" //<3>
  12. //Grafana pwd-> 20521bb9
  13. //Grafana username-> emon
  14. )
  15. type tracelog struct{}
  16. //实现输出
  17. func (tracelog) Printf(format string, v ...interface{}) {
  18. fmt.Printf(format, v...)
  19. }
  20. func RemoveDuplicatesAndEmpty(a []string) (ret []string) {
  21. a_len := len(a)
  22. for i := 0; i < a_len; i++ {
  23. if (i > 0 && a[i-1] == a[i]) || len(a[i]) == 0 {
  24. continue
  25. }
  26. ret = append(ret, a[i])
  27. }
  28. return
  29. }
  30. func init21123() {
  31. fmt.Println("start")
  32. client, err := elastic.NewClient(elastic.SetURL(ES_URL), elastic.SetBasicAuth(ES_USERNAME, ES_PASSWORD), elastic.SetSniff(false))
  33. if err != nil {
  34. fmt.Println("err:", err)
  35. }
  36. fmt.Println(client)
  37. keyWordStr := "医疗器械"
  38. queryString := elastic.NewQueryStringQuery(`Title:(` + keyWordStr + `)`)
  39. boolqueryJson, err := json.Marshal(queryString)
  40. fmt.Println("err:", err)
  41. fmt.Println("queryString ", string(boolqueryJson))
  42. var esIndex = "cygx_article"
  43. //boolquery.Must(elastic.NewMatchQuery("Title", keyWord), elastic.NewMatchQuery("BodyText", keyWord))
  44. highlight := elastic.NewHighlight()
  45. highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
  46. highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
  47. request := client.Search(esIndex).Highlight(highlight).Query(queryString)
  48. requestJson, err := json.Marshal(request)
  49. fmt.Println("err:", err)
  50. fmt.Println("requestJson ", string(requestJson))
  51. searchByMatch, err := request.Do(context.Background())
  52. if searchByMatch.Hits != nil {
  53. }
  54. fmt.Println(searchByMatch)
  55. fmt.Println("end")
  56. }