简介

go-elasticsearch是elasticsearch官方的Go版本客户端,兼容多个版本。

查看ES版本号

package main

import (
"context"
"log"
"strings"

elasticsearch "github.com/elastic/go-elasticsearch/v6"
"github.com/elastic/go-elasticsearch/v6/esapi"
)

func main() {
cfg := elasticsearch.Config{
Addresses: []string{
"http://user:pass@192.168.1.1:9200",
},
}
es, _ := elasticsearch.NewClient(cfg)
log.Println(elasticsearch.Version)
res, _ := es.Info()
defer res.Body.Close()
log.Print(res)
}

查询单个文档

// 查询单个文档 GET /index/_doc/1
req := esapi.GetRequest{
Index: "index",
DocumentType: "_doc",
DocumentID: "13",
}
res, err := req.Do(context.Background(), es)
if err != nil {
log.Fatalf("Error:%s", err)
}
log.Print(res)

查询多个文档

// 查询多个文档
req1 := esapi.MgetRequest{
Index: "index",
DocumentType: "_doc",
Body: strings.NewReader(`{"docs":[{"_id":"111"},{"_id":"222"}]}`),
}
res, err = req1.Do(context.Background(), es)
if err != nil {
log.Fatalf("Error:%s", err)
}
log.Print(res)

搜索

// 搜索
req2 := esapi.SearchRequest{
Index: []string{"index"},
Body: strings.NewReader(`{"query":{"match":{"content":"老师"}}}`),
}
res, err := req2.Do(context.Background(), es)
if err != nil {
log.Fatalf("Error:%s", err)
}
log.Print(res)

聚合

// 聚合
req2 := esapi.SearchRequest{
Index: []string{"index"},
Body: strings.NewReader(`{
"aggs":
{"2":
{"date_histogram":{"field":"@timestamp","interval":"1d","time_zone":"Asia/Shanghai","min_doc_count":1}}
},
"query": {"bool":{"must":[
{"match_all":{}},
{"range": {"@timestamp":{"gte": 1666512528818,"lte": 1671696528818,"format": "epoch_millis"
}}}
]}}
}`),
}
res, err := req2.Do(context.Background(), es)
if err != nil {
log.Fatalf("Error:%s", err)
}
log.Print(res)