golang elastic search olivere 总结之一 (CRUD的使用方法)
本文将介绍golang的elastic search库(github.com/olivere/elastic/v7 基于7版本)并与elastic search进行对照
以index为es,type为test 为例子
1.创建/ 更新
(索引存在则更新,不存在则创建)
ES:
http://localhost:9200/:index/:type/option:id [post]
(id 可选)
http://localhost:9200/es/test/1 [post]
{
"category":"language",
"content":"golang"
}
Golang:
var client *elastic.Client
type Language struct {
Content string `json:"content"`
}
func Create(){
e1 := Language{Content:"golang"}
put1, err := client.Index().
Index("es").
Id("1").
BodyJson(e1).
Do(context.Background())
if err != nil {
panic(err)
}
}
2.检索索引
ES:
http://localhost:9200/:index/:type/:id [get]
http://localhost:9200/es/test/1 [get]
Golang:
func Get(){
query, err := client.Get().Index("es").Id("1").Do(context.Background())
if err != nil {
panic(err)
}
if query.Found {
var result Language
err:=json.Unmarshal(query.Source,&result)
if err!=nil{
fmt.Println(err)
}
fmt.Println(result.Content)
}
}
3.删除
删除id 为“1”的key
ES:
http://localhost:9200/:index/:type/:id [delete]
http://localhost:9200/es/test/1 [delete]
Golang:
func Delete(){
client.Delete().Index("es").Id("1").Do(context.Background())
}