1.初始化连接
var client *elastic.Client
//初始化
func Init() {
var err error
//这个地方有个小坑 不加上elastic.SetSniff(false) 会连接不上
fmt.Println(conf.Config.EsHost)
client, err = elastic.NewClient(elastic.SetSniff(false), elastic.SetURL(conf.Config.EsHost))
if err != nil {
panic(err)
}
_, _, err = client.Ping(conf.Config.EsHost).Do(context.Background())
if err != nil {
panic(err)
}
_, err = client.ElasticsearchVersion(conf.Config.EsHost)
if err != nil {
panic(err)
}
}
2.封装多字段查询
func BoolQueryKeyword(index, Type, keyword, sort string, page, limit int, desc bool, field []string) (*elastic.SearchResult, error) {
var (
res *elastic.SearchResult
err error
)
boolQuery := elastic.NewBoolQuery()
for _, v := range field {
boolQuery.Should(elastic.NewMatchQuery(v, keyword))
}
res, err = client.Search(index).Type(Type).Query(boolQuery).Sort(sort, desc).Size(limit).From((page - 1) * limit).Do(context.Background())
if err != nil {
return res, err
}
return res, nil
}
3.将返回结果append到数组中
if err != nil {
fmt.Println("查询失败")
}
for _, item := range res.Each(reflect.TypeOf(Topic{})) {
t := item.(Topic)
topic = append(topic, t)
}