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)
}
}