go-elasticsearch

go 操作 elasticsearch官方包:https://github.com/elastic/go-elasticsearch/

1、安装go-elasticsearch

go get github.com/elastic/go-elasticsearch/v6

2、es工具类,返回一个es连接

package util

import (
	"github.com/elastic/go-elasticsearch/v6"
	"log"
)

func Esutil() *elasticsearch.Client {
	addresses := []string{"http://127.0.0.1:9200"}
	config := elasticsearch.Config{
		Addresses: addresses,
		Username:  "",
		Password:  "",
		CloudID:   "",
		APIKey:    "",
	}
	es, err := elasticsearch.NewClient(config)

	log.SetFlags(0)

	if err != nil {
		log.Fatalf("Error creating the client: %s", err)
	}
	return es
}

3、导入util并使用go-elasticsearch

以go-kit为例,如果在service层访问es。
1、导入项目名/util模块,然后定义一个全局变量作为es连接客户端

package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"log"
	"search/util"
	"strconv"
)

var es = util.Esutil()

2、构造query
在mysearch函数里实现一个查询:需要status=1,并且商品价格在指定区间;同时物品标题或者内容可以匹配到给定的keyword。得到满足查询条件的商品id切片。

func mysearch(page int,rows int,keyword string, min_price int,max_price int)(result []int){
	all_result :=make([]int,0)
	log.SetFlags(0)
	var (
		r map[string]interface{}
	)
	var buf bytes.Buffer

	query := map[string]interface{}{
		"_source": "item_id", // 返回物品id
		"size":    rows, // 每页返回数量
		"from":    page, // 从第几页开始
		"query": map[string]interface{}{
			"bool": map[string]interface{}{
				"must": []map[string]interface{}{  // 如果must中包含多个独立条件,则使用[]map[string]interface{}
					{
						"term": map[string]interface{}{ // term类型的条件放到一个map里面。
							"status": 1,
						},
					},
					{
						"range":map[string]interface{}{
							"item_price":map[string]interface{}{ //同理,range类型的条件放到一个map里面
								"gte": min_price,
								"lte": max_price,
							},
						},
					},
				},
				"should": []map[string]interface{}{ //同理,如果should有多个独立条件,使用[]map[string]interface{}
					{
						"match": map[string]interface{}{
							"item_title": map[string]interface{}{
								"query":                keyword,
								"minimum_should_match": "90%",
							},
						},
					},
					{
						"match": map[string]interface{}{
							"item_content": map[string]interface{}{
								"query":                keyword,
								"minimum_should_match": "90%",
							},
						},
					},
				},
				"minimum_should_match": 1, //代表当must匹配完成之后,还需要至少匹配一个should里面的条件。
			},
		},
	}



	if err := json.NewEncoder(&buf).Encode(query); err != nil{
		log.Fatalf("Error encoding query: %s", err)
	}

	res, err := es.Search(
		es.Search.WithContext(context.Background()),
		es.Search.WithIndex("es表名"),
		es.Search.WithBody(&buf),
		es.Search.WithTrackTotalHits(true),
		es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close() // 最后关闭Body
	if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
		log.Fatalf("Error parsing the response body: %s", err)
	}

	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		//log.Printf(" * ID=%s, %s", hit.(map[string]interface{})["_id"], hit.(map[string]interface{})["_source"])
		b,error := strconv.Atoi(hit.(map[string]interface{})["_id"].(string))
		if error != nil{
			fmt.Println("字符串转换成整数失败")
		}
		all_result = append(all_result,b)
	}

	return all_result
}
原文地址:https://www.cnblogs.com/leimu/p/14699697.html