菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
369
0

go 操作elaticsearch

原创
05/13 14:22
阅读数 81271

olivere/elastic 包

github.com/olivere/elastic

doc:

https://pkg.go.dev/github.com/olivere/elastic?utm_source=godoc

package main
  
import (
    "context"
    "fmt"
    "github.com/olivere/elastic"
)
  
创建索引:
func main(){
    Client, err := elastic.NewClient(elastic.SetURL("http://192.168.7.6:9200"))
    fmt.Println(Client, err)
    name := "people2"
    Client.CreateIndex(name).Do(context.Background())
}
 
插入数据
func main(){
    Client, err := elastic.NewClient(elastic.SetURL("http://192.168.7.6:9200"))
    fmt.Println(Client, err)
    name := "people2"
    data := `{
    "name": "wali",
    "country": "Chian",
    "age": 30,
    "date": "1987-03-07"
    }`
    _, err = Client.Index().Index(name).Type("man1").Id("1").BodyJson(data).Do(context.Background())
  
}
  
查找数据: //通过id查找
func main(){
    Client, err := elastic.NewClient(elastic.SetURL("http://192.168.7.6:9200"))
    fmt.Println(Client, err)
    name := "people2"
    get, err := Client.Get().Index(name).Type("man1").Id("1").Do(context.Background())
    fmt.Println(get, err)
  
}
 
 
 
//修改
func main() {
    Client, err := elastic.NewClient(elastic.SetURL("http://192.168.7.6:9200"))
        res, err := client.Update().
        Index("megacorp").
        Type("employee").
        Id("2").
        Doc(map[string]interface{}{"age": 88}).
        Do(context.Background())
        if err != nil {
            println(err.Error())
        }
        fmt.Printf("update age %s\n", res.Result)
  
}
 
 
 
删除数据
func main(){
    Client, err := elastic.NewClient(elastic.SetURL("http://192.168.7.6:9200"))
    //使用结构体
        e1 := Employee{"Jane", "Smith", 32, "I like to collect rock albums", []string{"music"}}
    //创建
        put1, err := client.Index().
        Index("megacorp").
        Type("employee").
        Id("1").
        BodyJson(e1).
        Do(context.Background())
        if err != nil {
            panic(err)
        }
    //删除
    get, err := Client.Get().Index("megacorp").Type("employee").Id("1").Do(context.Background())
    fmt.Println(get, err)
}

参考:
https://www.cnblogs.com/-wenli/p/12737196.html


官方包

参考:

https://github.com/elastic/go-elasticsearch 来连接ES并进行操作。
https://www.cnblogs.com/binHome/p/12345413.html

发表评论

0/200
369 点赞
0 评论
收藏