go es练习

下载安装包:

go get github.com/olivere/elastic

注:下载的版本与es安装的版本一致,我的版本是v7.10.0

解决golang使用elastic连接elasticsearch时自动转换连接地址

使用olivere/elastic连接elasticsearch时,发现连接地址明明输入的时候是公网地址,但是连接时会自动转换成内网地址或者docker中的ip地址,导致服务连接不上。
// 自动转换成docker中的ip导致无法连接服务
time=“2019-02-15T20:04:26+08:00” level=error msg=“Head http://172.17.0.2:9200: context deadline exceeded”
解决

client, _ := elastic.NewClient(
  // ...
  // 将sniff设置为false后,便不会自动转换地址
   elastic.SetSniff(false),
)

练习

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/olivere/elastic"
	"reflect"
	"strconv"
)

var client  *elastic.Client

func init(){
	c, err := elastic.NewClient(elastic.SetSniff(false),elastic.SetURL("http://127.0.0.1:9200"))
	if err != nil{
		fmt.Println(err)
	}
	_, _, err = c.Ping("http://127.0.0.1:9200").Do(context.Background())
	if err != nil {
		fmt.Println(err)
	}
	_, err = c.ElasticsearchVersion("http://127.0.0.1:9200")
	if err != nil {
		fmt.Println(err)
	}
	client = new(elastic.Client)
	client = c
}

type Subject struct {
	ID     int      `json:"id"`
	Title  string   `json:"title"`
	Genres []string `json:"genres"`
	Years  int      `json:"years"`
}


func createIndex(){
	flag,_ := client.IndexExists("love").Do(context.Background())
	if !flag{
		client.CreateIndex("love").Do(context.Background())
	}
}

func createContent(){
	// 结构体写入
	subject := Subject{
		ID:     1,
		Title:  "肖恩克的救赎",
		Genres: []string{"犯罪", "剧情"},
		Years: 8,
	}

	doc, err := client.Index().
		Index("love").
		Id(strconv.Itoa(subject.ID)).
		BodyJson(subject).
		Refresh("wait_for").        //操作发生后立即刷新相关的主要和副本分片(而不是整个索引)
		Do(context.Background())

	if err != nil {
		panic(err)
	}
	fmt.Printf("Indexed with id=%v, type=%s\n", doc.Id, doc.Type)

	// 字符串写入
	subjct2 := `{"id":2,"title":"盗梦空间","genres":["悬疑","剧情"],"years":5}`
	doc2,err := client.Index().
		Index("love").
		Id("2").
		BodyJson(subjct2).
		Refresh("wait_for").
		Do(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Printf("Indexed with id=%v, type=%s\n", doc2.Id, doc2.Type)
}

// 查询一个
func getById(){
	data,err := client.Get().Index("love").Id("1").Do(context.Background())
	if err != nil{
		panic(err)
	}
	if data.Found{
		byteData,_ := data.Source.MarshalJSON()
		fmt.Println(string(byteData))
	}
}

func updateContent(){
	doc,_ := client.Update().
		Index("love").
		Id("1").
		Doc(map[string]interface{}{"title":"cocofree"}).  // 如果其他字段不写默认置为空字符串
		Do(context.Background())
	fmt.Println(doc.Id)
}

func deleteContent(){
	res,_ := client.Delete().Index("love").Id("1").Do(context.Background())
	fmt.Printf("delete result %s\n", res.Result)
}

// 查询所有
func searchAllByQuery(){
	res,_ := client.Search().Index("love").Do(context.Background())
	var subject Subject
	for _,item := range res.Each(reflect.TypeOf(subject)){
		t := item.(Subject)
		fmt.Printf("%#v\n", t)
	}
}

// 条件查询(字段相等)
func searchByQuery1(){
	q := elastic.NewQueryStringQuery("title:盗梦空间")
	res,_ := client.Search().Index("love").Query(q).Do(context.Background())
	var subject Subject
	for _,item := range res.Each(reflect.TypeOf(subject)){
		t := item.(Subject)
		fmt.Printf("%#v\n",t)
	}
}

// 条件查询(字段相等)
func searchByQuery2(){
	//查询条件
	searchSource := elastic.NewSearchSource()
	searchSource.Query(elastic.NewMatchQuery("title","盗梦空间"))

	// 查询
	res,_ := client.Search().Index("love").SearchSource(searchSource).Do(context.Background())
	var subject Subject
	for _,item := range res.Each(reflect.TypeOf(subject)){
		t := item.(Subject)
		fmt.Printf("%#v\n",t)
	}
}

// 模糊匹配
func searchByQuery3(){
	match := elastic.NewMatchPhraseQuery("title","梦")
	res,_ := client.Search().Index("love").Query(match).Do(context.Background())
	var subject Subject
	for _,item := range res.Each(reflect.TypeOf(subject)){
		t := item.(Subject)
		fmt.Printf("%#v\n",t)
	}
}

// 条件查询
func searchByQuery4(){
	q := elastic.NewBoolQuery()
	q.Must(elastic.NewMatchQuery("title","盗梦空间"))
	q.Filter(elastic.NewRangeQuery("years").Gt(5))
	res,_ := client.Search().Index("love").Query(q).Do(context.Background())
	// 打印
	var subject Subject
	for _,item := range res.Each(reflect.TypeOf(subject)){
		t := item.(Subject)
		fmt.Printf("%#v\n",t)
	}
}

// 另一种打印方式
func searchByQuery5(){
	q := elastic.NewBoolQuery()
	q.Filter(elastic.NewRangeQuery("years").Gt(1))
	res,_ := client.
		Search().
		Index("love").
		Query(q).
		Sort("years",true).   //按某个字段排序
		From(0).                      // offset
		Size(10).                       // limit
		Do(context.Background())
	// 打印
	if res.Hits.TotalHits.Value > 0 {
		for _,hit := range res.Hits.Hits{
			var subject Subject
			json.Unmarshal(hit.Source,&subject)
			fmt.Println(subject)
		}
	}
}

func main(){
	// 通过id进行增删改查
	// createIndex()
	// createContent()
	// getById()
	// updateContent()
	// deleteContent()

	// 通过查询条件进行删改查
	createContent()
	// searchAllByQuery()
	// searchByQuery1()
	// searchByQuery2()
	// searchByQuery3()
	// searchByQuery4()
	searchByQuery5()
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值