• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

go操作Elasticsearch简单示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

go操作Elasticsearch主要有以下两个sdk

  • github.com/olivere/elastic 
  • github.com/elastic/go-elasticsearch 
  • 我们这里选择第一个
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)
}

  

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
带你十天轻松搞定 Go 微服务系列(九、链路追踪)发布时间:2022-07-10
下一篇:
vuerouter.push(),router.replace(),router.go()发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap