go操作elasticsearch
使用第三方库https://github.com/olivere/elastic来连接ES并进行操作。
下载与你的ES相同版本的client,例如我们这里使用的ES是7.2.1的版本,那么我们下载的client也要与之对应为github.com/olivere/elastic/v7
。
使用go.mod
来管理依赖:
module go_es
go 1.14
require github.com/olivere/elastic/v7 v7.0.16
示例:
package main
import (
"context"
"fmt"
"github.com/olivere/elastic/v7"
)
// Elasticsearch demo
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Married bool `json:"married"`
}
func main() {
client, err := elastic.NewClient(elastic.SetURL("http://localhost:9200"),elastic.SetSniff(false))//关闭sniff模式
if err != nil {
// Handle error
panic(err)
}
fmt.Println("connect to es success")
p1 := Person{Name: "rion", Age: 22, Married: false}
put1, err := client.Index().
Index("user").
BodyJson(p1).
Do(context.Background())
if err != nil {
// Handle error
panic(err)
}
fmt.Printf("Indexed user %s to index %s, type %s\n", put1.Id, put1.Index, put1.Type)
}
注意:因为是在docker中运行elasticsearch,所以需要关闭sniff模式elastic.SetSniff(false)
不然报错:
panic: no active connection found: no Elasticsearch node available
参考:https://www.bbsmax.com/A/A2dm1K1Ade/