1. 项目地址:
    https://github.com/elastic/go-elasticsearch/
  2. 使用:
    package main
    import (
     "bytes"
     "context"
     "encoding/json"
     "fmt"
     "github.com/elastic/go-elasticsearch/v8"
     "strconv"
    )
    type ES struct {
     EsObj *elasticsearch.Client
     GroupByField string
     AggsField string
     Sql map[string]interface{}
    }
    func (this *ES) Init(hosts []string,username string,password string)  {
     config := elasticsearch.Config{
         Addresses: hosts,
         Username: username,
         Password: password,
     }
     es, err := elasticsearch.NewClient(config)
     if err != nil{
         fmt.Println(err)
     }
     this.EsObj = es
    }
    // 添加/更新 index
    func (this *ES) Index(index string,id string,body map[string]interface{}) []interface{} {
     ret := []interface{}{}
     var buf bytes.Buffer
     if err := json.NewEncoder(&buf).Encode(body); err != nil {
         ret = []interface{}{0,err}
     }
     res, err := this.EsObj.Index(index, &buf, this.EsObj.Index.WithDocumentID(id))
     if err != nil {
         ret = []interface{}{0,err}
     }
     defer res.Body.Close()
     r := map[string]interface{}{}
     json.NewDecoder(res.Body).Decode(&r)
     if res.StatusCode == 200 || res.StatusCode == 201{
         ret = []interface{}{1,r["result"]}
     }else{
         ret = []interface{}{0,r}
     }
     return ret
    }
    // 根据 id 获取内容
    func (this *ES) Get(index string,id string) []interface{} {
     ret := []interface{}{}
     res, err := this.EsObj.Get(index, id)
     if err != nil {
         ret = []interface{}{0, err}
     }
     defer res.Body.Close()
     r := map[string]interface{}{}
     json.NewDecoder(res.Body).Decode(&r)
     if res.StatusCode == 200 || res.StatusCode == 201{
         ret = []interface{}{1,r["_source"]}
     }else{
         ret = []interface{}{0,r}
     }
     return ret
    }
    func (this *ES) Order(data map[string]interface{}) *ES {
     this.Sql["sort"] = data
     return this
    }
    func (this *ES) MatchAll() *ES {
     this.Sql["query"] = map[string]map[string]string{
         "match_all": {},
     }
     return this
    }
    func (this *ES) Page(page int,size int) *ES {
     from := (page - 1) * size
     this.Sql["from"] = from
     this.Sql["size"] = size
     return this
    }
    func (this *ES) Match(data map[string]interface{}) *ES {
     this.Sql["query"] = map[string]interface{}{
         "match": data,
     }
     return this
    }
    func (this *ES) MatchPhrase(data map[string]interface{}) *ES {
     this.Sql["query"] = map[string]interface{}{
         "match_phrase": data,
     }
     return this
    }
    func (this *ES) MustMatch(data map[string]interface{}) *ES {
     this.Sql["query"] = map[string]interface{}{
         "bool": map[string]interface{}{
             "must": []map[string]interface{}{
                 {
                     "match": data,
                 },
             },
         },
     }
     return this
    }
    func (this *ES) MustNotMatch(data map[string]interface{}) *ES {
     this.Sql["query"] = map[string]interface{}{
         "bool": map[string]interface{}{
             "must_not": []map[string]interface{}{
                 {
                     "match": data,
                 },
             },
         },
     }
     return this
    }
    func (this *ES) Range(data map[string]interface{}) *ES {
     this.Sql["query"] = map[string]interface{}{
         "bool": map[string]interface{}{
             "must": map[string]interface{}{
                 "match_all": map[string]interface{}{},
             },
             "filter": map[string]interface{}{
                 "range": data,
             },
         },
     }
     return this
    }
    // ***************** 聚合搜索: BEGIN ***************** //
    func (this *ES) Aggs(group_byfield string,operator string,aggs_field string,sort string) *ES {
     if operator == ""{
         this.Sql["aggs"] = map[string]interface{}{
             this.GroupByField: map[string]interface{}{
                 "terms": map[string]interface{}{
                     "field": group_byfield + ".keyword",
                 },
             },
         }
     } else if sort == ""{
         this.Sql["aggs"] = map[string]interface{}{
             this.GroupByField: map[string]interface{}{
                 "terms": map[string]interface{}{
                     "field": group_byfield + ".keyword",
                 },
                 "aggs": map[string]interface{}{
                     this.AggsField: map[string]interface{}{
                         operator: map[string]interface{}{
                             "field": aggs_field,
                         },
                     },
                 },
             },
         }
     } else {
         this.Sql["aggs"] = map[string]interface{}{
             this.GroupByField: map[string]interface{}{
                 "terms": map[string]interface{}{
                     "field": group_byfield + ".keyword",
                     "order": map[string]interface{}{
                         this.AggsField: sort,
                     },
                 },
                 "aggs": map[string]interface{}{
                     this.AggsField: map[string]interface{}{
                         operator: map[string]interface{}{
                             "field": aggs_field,
                         },
                     },
                 },
             },
         }
     }
     this.Sql["size"] = 0
     return this
    }
    // ****************** 聚合搜索: END ****************** //
    // 根据 关键词 在指定 key 中 搜索内容
    func (this *ES) Search(index string) []interface{} {
     fmt.Println(this.Sql)
     ret := []interface{}{}
     res, err := this.EsObj.Info()
     if err != nil{
         ret = []interface{}{0,err}
     }
     var buf bytes.Buffer
     if err := json.NewEncoder(&buf).Encode(this.Sql); err != nil {
         ret = []interface{}{0,err}
     }
     res, err = this.EsObj.Search(
         this.EsObj.Search.WithContext(context.Background()),
         this.EsObj.Search.WithIndex(index),
         this.EsObj.Search.WithBody(&buf),
         this.EsObj.Search.WithTrackTotalHits(true),
         this.EsObj.Search.WithPretty(),
     )
     if err != nil {
         ret = []interface{}{0,err}
     }
     defer res.Body.Close()
     r := map[string]interface{}{}
     json.NewDecoder(res.Body).Decode(&r)
     if res.StatusCode == 200 || res.StatusCode == 201{
         ret = []interface{}{1,r}
     }else{
         ret = []interface{}{0,r}
     }
     return ret
    }
    // 删除指定 ID
    func (this *ES) DeleteId(index string,id string) []interface{} {
     ret := []interface{}{}
     res, err := this.EsObj.Delete(index, id)
     if err != nil {
         ret = []interface{}{0,err}
     }
     defer res.Body.Close()
     r := map[string]interface{}{}
     json.NewDecoder(res.Body).Decode(&r)
     if res.StatusCode == 200 || res.StatusCode == 201{
         ret = []interface{}{1,r}
     }else{
         ret = []interface{}{0,r}
     }
     return ret
    }
    // 删除指定索引
    func (this *ES) DeleteIndex(index string) []interface{} {
     ret := []interface{}{}
     deleteParams := []string{index}
     res, err := this.EsObj.Indices.Delete(deleteParams)
     if err != nil {
         ret = []interface{}{0,err}
     }
     defer res.Body.Close()
     r := map[string]interface{}{}
     json.NewDecoder(res.Body).Decode(&r)
     if res.StatusCode == 200 || res.StatusCode == 201{
         ret = []interface{}{1,r}
     }else{
         ret = []interface{}{0,r}
     }
     return ret
    }
    // 辅助函数:返回实例化后的 ES 对象(自动执行 ES.Init())
    func NewES(hosts []string,username string,password string) ES {
     es := ES{
         GroupByField: "group_by_field",
         AggsField: "aggs_field",
         Sql: make(map[string]interface{}),
     }
     es.Init(hosts,username,password)
     return es
    }
    func main() {
     hosts := []string{"http://192.168.1.13:9200"}
     username := "elastic"
     password := "admin123"
     es := NewES(hosts,username,password)
     for i := 1;i <= 100;i ++ {
         str_i := strconv.Itoa(i)
         ret1 := es.Index("mydb",str_i, map[string]interface{}{
             "k1": "早起的鸟儿有虫吃! - " + str_i,
             "k2": "太阳从东方升起! - " + str_i,
             "k3": i * 10,
         })
         fmt.Println(ret1)
     }
     ret2 := es.Index("mydb","101", map[string]interface{}{
         "k1": "张三",
         "k2": "武汉",
         "k3": 1010,
     })
     fmt.Println(ret2)
     ret3 := es.Get("mydb","1")
     fmt.Println(ret3)
     // 1. match_all / order
     ret4 := es.MatchAll().Order(map[string]interface{}{"k3": "desc"}).Search("mydb")
     fmt.Println(ret4)
     // 2. match_all / order / page
     ret5 := es.MatchAll().Order(map[string]interface{}{"k3": "desc"}).Page(1,3).Search("mydb")
     fmt.Println(ret5)
     // 3. match
     ret6 := es.Match(map[string]interface{}{"k1": "张"}).Search("mydb")
     fmt.Println(ret6)
     // 4. match_phrase
     ret7 := es.MatchPhrase(map[string]interface{}{"k1": "张"}).Search("mydb")
     fmt.Println(ret7)
     // 5. must / must_not
     ret8 := es.MustMatch(map[string]interface{}{"k1": "张"}).MustNotMatch(map[string]interface{}{"k2": "太"}).Search("mydb")
     fmt.Println(ret8)
     // 6. range
     ret9 := es.Range(map[string]interface{}{"k3": map[string]interface{}{"gte": 200,"lte": 300}}).Search("mydb")
     fmt.Println(ret9)
     // 7. group_by
     ret10 := es.Aggs("k1","","","").Search("mydb")
     fmt.Println(ret10)
     // 8. group_by / aggs
     ret11 := es.Aggs("k1","avg","k3","").Search("mydb")
     fmt.Println(ret11)
     // 9. group_by / aggs / group_by_order
     ret12 := es.Aggs("k1","avg","k3","desc").Search("mydb")
     fmt.Println(ret12)
     ret13 := es.DeleteId("mydb","1")
     fmt.Println(ret13)
     ret14 := es.DeleteIndex("mydb")
     fmt.Println(ret14)
    }
文档更新时间: 2021-11-26 10:59   作者:lee