在云原生环境下,存储日志大多采用elastic集群。
当前需求是根据多组index
和id
查询日志。
elastic
语句示例如下:
POST /_mget
{
"docs": [
{
"_index": "index001",
"_id": "1"
},
{
"_index": "index002",
"_id": "2"
}
]
}
通常情况下我们都是采用search
的方法去查询,根据已知的信息,比如说pod_name
、namespace
、instance
、timestamp
等信息,采用的golang
代码库是github.com/elastic/go-elasticsearch/v7
。
如果要满足上述需求,需要变更查询方法,改为Mget
,经过一番尝试后,决定弃用该方式,总之就是一句话–不会!
但是问题总是要解决的,所以在全网搜索+多次试错后,终于找到了一个非常好用的方法。前提是需要变更依赖库为github.com/olivere/elastic/v7
。
详细代码如下:
func main() {
//下面关于es的信息需要替换
url := "http://10.xx.xx.xx"
username := "username"
password := "password"
// 待查询数据
indexMap := make(map[string]string,0)
indexMap["index001"] = "1"
indexMap["index002"] = "2"
// 创建es客户端
esClient, _ := elastic.NewClient(elastic.SetURL(url), elastic.SetBasicAuth(username, password))
mgetsvc := esClient.MultiGet()
// 增加es查询的信息
for index, id := range scLocList {
mgetsvc.Add(elastic.NewMultiGetItem().Index(index).Id(id))
}
// 执行查询
rsp, err := mgetsvc.Do(ctx)
logData := rsp.Docs
fmt.Println(logData)
}
上述查询可以简单快捷的实现mget
的查询,希望可以对学习使用golang
查询elastic
的同学有所帮助。