golang elasticsearch Client的使用

elasticsearch 的client ,通过 NewClient 建立连接,通过  NewClient 中的 Set.URL设置访问的地址,SetSniff设置集群

获得连接 后,通过 Index 方法插入数据,插入后可以通过 Get 方法获得数据(最后的测试用例中会使用 elasticsearch client 的Get 方法)

func Save(item interface{}) {
    client, err := elastic.NewClient(
		elastic.SetURL("http://192.168.174.128:9200/"),
		// Must turn off sniff in docker
		elastic.SetSniff(false),
	)

	if err != nil {
		panic(err)
	}

	resp, err := client.Index().
		Index("dating_profile").
		Type("zhenai").
		BodyJson(item).
		Do(context.Background()) //contex需要context 包
	if err != nil {
		panic(err)
	}

	fmt.Printf("%+v", resp)

}

测试程序,自行定义一个数据结构 Profile 进行测试

func TestSave(t *testing.T) {
	profile := model.Profile{
		Age:        34,
		Height:     162,
		Weight:     57,
		Income:     "3001-5000元",
		Gender:     "女",
		Name:       "安静的雪",
		XingZuo:    "牡羊座",
		Occupation: "人事/行政",
		Marriage:   "离异",
		House:      "已购房",
		Hukou:      "山东菏泽",
		Education:  "大学本科",
		Car:        "未购车",
	}

	Save(profile)
}

go test 成功

通过 Get 方法查看数据是否存在elasticsearch 中

 

我们在test中panic,在函数中讲错误返回。在从elastisearch中 取出存入的数据,与我们定义的数据进行比较,所以save中需要将插入数据的Id返回出来

func Save(item interface{}) (id string, err error) {
	client, err := elastic.NewClient(
		elastic.SetURL("http://192.168.174.128:9200/"),
		// Must turn off sniff in docker
		elastic.SetSniff(false),
	)

	if err != nil {
		return "", err
	}

	resp, err := client.Index().
		Index("dating_profile").
		Type("zhenai").
		BodyJson(item).
		Do(context.Background())
	if err != nil {
		return "", err
	}

	return resp.Id, nil

}

测试用例

package persist

import (
	"context"
	"encoding/json"
	"my_crawler_single/model"
	"testing"

	elastic "gopkg.in/olivere/elastic.v5"
)

func TestSave(t *testing.T) {
	expected := model.Profile{
		Age:        34,
		Height:     162,
		Weight:     57,
		Income:     "3001-5000元",
		Gender:     "女",
		Name:       "安静的雪",
		XingZuo:    "牡羊座",
		Occupation: "人事/行政",
		Marriage:   "离异",
		House:      "已购房",
		Hukou:      "山东菏泽",
		Education:  "大学本科",
		Car:        "未购车",
	}

	id, err := Save(expected)
	if err != nil {
		panic(err)
	}

	client, err := elastic.NewClient(
		elastic.SetURL("http://192.168.174.128:9200/"),
		elastic.SetSniff(false),
	)
	if err != nil {
		panic(err)
	}

	resp, err := client.Get().
		Index("dating_profile").
		Type("zhenai").
		Id(id). //查找指定id的那一条数据
		Do(context.Background())
	if err != nil {
		panic(err)
	}

	t.Logf("%+v", resp)
	//从打印得知,数据在resp.Source中,从rest client的截图也可以知道

	var actual model.Profile
	//查看 *resp.Source 可知其数据类型为[]byte
	err = json.Unmarshal(*resp.Source, &actual)
	if err != nil {
		panic(err)
	}

	if actual != expected {
		t.Errorf("got %v;expected %v", actual, expected)
	}
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值