直接上代码
package main
import (
"bytes"
"context"
"fmt"
"github.com/olivere/elastic/v7"
"log"
)
const IndexName = "test_index"
func main() {
IsDocExists("xxx", IndexName)
}
//获取Es客户端
func GetEsClient() *elastic.Client {
var buf bytes.Buffer
client, err := elastic.NewClient(
elastic.SetURL("http://127.0.0.1:9200/"),
//docker
elastic.SetSniff(false),
elastic.SetInfoLog(log.New(&buf, "ES-INFO: ", 0)),
elastic.SetTraceLog(log.New(&buf, "ES-TRACE: ", 0)),
elastic.SetErrorLog(log.New(&buf, "ES-ERROR: ", 0)),
)
if err != nil {
return nil
}
return client
}
//查看某文档是否存在,给定文档ID查询
func IsDocExists(id, index string) bool {
client := GetEsClient()
defer client.Stop()
exist, _ := client.Exists().Index(index).Id(id).Do(context.Background())
if !exist {
log.Println("ID may be incorrect! ", id)
return false
}
return true
}
//获取文档
func GetDoc(id, index string) (*elastic.GetResult, error) {
client := GetEsClient()
defer client.Stop()
if !IsDocExists(id, index) {
return nil, fmt.Errorf("id不存在")
}
esResponse, err := client.Get().Index(index).Id(id).Do(context.Background())
if err != nil {
return nil, err
}
return esResponse, nil
}
//添加文档
func AddDoc(id, doc string, index string) (*elastic.IndexResponse, error) {
client := GetEsClient()
defer client.Stop()
if IsDocExists(id, index) {
return nil, fmt.Errorf("id不存在")
}
rsp, err := client.Index().Index(index).Id(id).BodyJson(doc).Do(context.Background())
if err != nil {
return nil, err
}
return rsp, nil
}
//更新文档
func UpdateDoc(updateField *map[string]interface{}, id, index string) (*elastic.UpdateResponse, error) {
client := GetEsClient()
defer client.Stop()
if !IsDocExists(id, index) {
return nil, fmt.Errorf("id不存在")
}
rsp, err := client.Update().Index(index).Id(id).Doc(updateField).Do(context.Background())
if err != nil {
fmt.Println(err)
return nil, err
}
return rsp, nil
}
//删除文档
func DeleteDoc(id, index string) (*elastic.DeleteResponse, error) {
client := GetEsClient()
defer client.Stop()
rsp, err := client.Delete().Index(index).Id(id).Do(context.Background())
if err != nil {
return nil, err
}
return rsp, nil
}



