go中elasticsearch sdk 常用基础操作
1、创建客户端
func getCli() *es.Client{
cli :=es.SetURL("http://127.0.0.1:9200")
client, err :=es.NewClient(es.SetSniff(enabled), cli)
if err !=nil {
panic(err)
}
}
2、定义数据结构
type ParamModel struct {
Id int64 `json:"id"`
Content string `son:"content"`
.....
}
3、数据解析器
func ParserFlOrder(res *es.SearchResult) (out interface{}) {
temp :=ParamModel{}
list :=make([]ParamModel, 0)
for _, item :=range res.Each(reflect.TypeOf(temp)) {
list =append(list, item.(ParamModel))
}
return list
}
4、查询所用数据
func querySearchList(name string, page, size int, fn func(re *es.SearchResult, ) (out interface{})) (interface{}, error) {
client :=getCli()
ser := client.Search(name)
if page >0 {
ser = ser.From((page -1) * size)
}
if size >0 {
ser = ser.Size(size)
}
res, err := ser.Do(context.Background())
if err !=nil {
cfg.LogErr("err:", err)
return nil, err
}
out := fn(res)
return out, nil
}
5、通过Id查询数据
func queryById(name, id string, obj interface{}) error{
client :=getCli()
resp, err := client.Get().Index(name).Id(id).Do(context.Background())
if err != nil {
cfg.LogErr("err:", err)
return err
}
err = json.Unmarshal(resp.Source, &obj)
return err
}
6、更新数据
func updateById(name, id string, obj interface{})error {
client :=getCli()
resp, err := client.Update().Index(name).Id(id).Doc(obj).Do(context.Background())
if err !=nil {
cfg.LogErr("err:", err)
return err
}
cfg.LogInfo("resp:", resp)
return nil
}
7、删除数据
func delById(name string, idstring)error {
client :=getCli()
resp, err := client.Delete().Index(name).Id(id).Do(context.Background())
if err !=nil {
cfg.LogErr("err:", err)
}
cfg.LogInfo("resp:", resp)
return nil
}
8、批量写入数据
func addList(name string, list []ParamModel) {
client :=getCli()
bulkRequest := client.Bulk()
for _, v :=range list {
req :=es.NewBulkIndexRequest().Index(name).Id(v.Id).Doc(v)
bulkRequest = bulkRequest.Add(req)
}
bulkResponse, err := bulkRequest.Do(context.Background())
if err !=nil {
cfg.LogErr("err:", err)
}
if bulkResponse !=nil {
cfg.LogErr("err:", err)
}
}
有疑问加站长微信联系(非本文作者)