go-elasticsearch 官方包操作合集

导包

require (
	github.com/elastic/go-elasticsearch/v7 v7.12.0
	)

连接客户端


var (
	client *es.Client
)

func init() {
	var err error
	client, err = es.NewClient(es.Config{
		Addresses: []string{"http://192.168.6.39:9201"},
		// 配置HTTP传输对象
		Transport: &http.Transport{
			//MaxIdleConnsPerHost 如果非零,控制每个主机保持的最大空闲(keep-alive)连接。如果为零,则使用默认配置2。
			MaxIdleConnsPerHost: 10,
			//ResponseHeaderTimeout 如果非零,则指定在写完请求(包括请求体,如果有)后等待服务器响应头的时间。
			ResponseHeaderTimeout: time.Second,
			//DialContext 指定拨号功能,用于创建不加密的TCP连接。如果DialContext为nil(下面已弃用的Dial也为nil),那么传输拨号使用包网络。
			DialContext: (&net.Dialer{Timeout: time.Second}).DialContext,
			// TLSClientConfig指定TLS.client使用的TLS配置。
			//如果为空,则使用默认配置。
			//如果非nil,默认情况下可能不启用HTTP/2支持。
			TLSClientConfig: &tls.Config{
				MaxVersion: tls.VersionTLS11,
				//InsecureSkipVerify 控制客户端是否验证服务器的证书链和主机名。
				InsecureSkipVerify: true,
			},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
}

索引操作 CRUD

添加索引


// es-官方包 添加索引操作
func TestAddIndex(t *testing.T) {
	// type IndicesCreate func(index string, o ...func(*IndicesCreateRequest)) (*Response, error)  官方函数
	response, _ := client.API.Indices.Create("es_test")
	fmt.Printf("response: %v\n", response)
}

查询索引


// 查询索引
func TestGetIndex(t *testing.T) {
	// type IndicesGet func(index []string, o ...func(*IndicesGetRequest)) (*Response, error)
	response, _ := client.API.Indices.Get([]string{"es_test"})
	fmt.Printf("response: %v\n", response)
}

删除索引

// 删除索引
func TestDelIndex(t *testing.T) {
	//	type IndicesDelete func(index []string, o ...func(*IndicesDeleteRequest)) (*Response, error)
	response, _ := client.API.Indices.Delete([]string{"es_test_book"})
	fmt.Printf("response: %v\n", response)
}

文档操作

创建索引

// 创建文档
type Book struct {
	ID      string     `json:"id"`
	Author  string     `json:"author"`
	Name    string     `json:"name"`
	Pages   int        `json:"pages"`
	Price   float64    `json:"price"`
	PubDate *time.Time `json:"pubDate"`
	Summary string     `json:"summary"`
}

func TestAddDoc(t *testing.T) {
	assertions := assert.New(t)
	body := &bytes.Buffer{}
	pubDate := time.Now()
	err := json.NewEncoder(body).Encode(&Book{
		Author:  "金庸",
		Price:   96.0,
		Name:    "天龙八部",
		Pages:   1978,
		PubDate: &pubDate,
		Summary: "...",
	})
	assertions.Nil(err)
	// 创建
	response, err := client.Create("es_test_book", "1", body)
	assertions.Nil(err)
	t.Log(response)
}

覆盖性更新文档

func TestIndexDocument(t *testing.T) {
	a := assert.New(t)
	body := &bytes.Buffer{}
	pubDate := time.Now()
	err := json.NewEncoder(body).Encode(&Book{
		Author:  "金庸",
		Price:   96.0,
		Name:    "天龙八部",
		Pages:   1978,
		PubDate: &pubDate,
		Summary: "...",
	})
	a.Nil(err)
	response, err := client.Index("es_book", body, client.Index.WithDocumentID("1"))
	a.Nil(err)
	t.Log(response)
}

局部性更新文档,

// 下面的代码借助go json的omitempty,在将更新数据对象序列化成json,
// 可以只序列化非零值字段,实现局部更新。 实际项目采用这种方式时,需要注意某个字段的零值具有业务意义时,可以采用对应的指针类型实现。
type doc struct {
	Doc interface{} `json:"doc"`
}
type Book1 struct {
	Author  string     `json:"author,omitempty"`
	Name    string     `json:"name,omitempty"`
	Pages   int        `json:"pages,omitempty"`
	Price   float64    `json:"price,omitempty"`
	PubDate *time.Time `json:"pubDate,omitempty"`
	Summary string     `json:"summary,omitempty"`
}

func TestPartialUpdateDocument(t *testing.T) {
	a := assert.New(t)
	body := &bytes.Buffer{}
	err := json.NewEncoder(body).Encode(&doc{
		Doc: &Book1{
			Name: "《天龙八部》",
		},
	})
	a.Nil(err)
	response, err := client.Update("es_book", "1", body)

	a.Nil(err)
	t.Log(response)
}

删除文档

func TestDeleteDocument(t *testing.T) {
	a := assert.New(t)
	response, err := client.Delete("es_book", "1")
	a.Nil(err)
	t.Log(response)
}

获取文档

func TestGetDocument(t *testing.T) {
	assertions := assert.New(t)
	response, err := client.Get("es_book", "1")
	assertions.Nil(err)
	t.Log(response)
}

文档的批量操作添加跟删除

/ 批量操作对应ES的REST API是:
// POST /<target>/_bulk
// { "index" : { "_id" : "1" } }
// { "field1" : "value1" }
// { "delete" : { "_id" : "2" } }
// { "create" : { "_id" : "3" } }
// { "field1" : "value3" }
// { "update" : {"_id" : "1" } }
// { "doc" : {"field2" : "value2"} }
// 对应index, create, update操作,
// 提交的数据都是由两行组成,第一行是meta数据,描述操作信息
// ,第二行是具体提交的数据,对于delete操作只有一行meta数据。 对照REST API
func TestBulk(t *testing.T) {
	createBooks := []*Book{
		{
			ID:     "10002",
			Name:   "神雕侠侣",
			Author: "金庸",
		},
		{
			ID:     "10003",
			Name:   "射雕英雄传",
			Author: "金庸",
		},
	}
	deleteBookIds := []string{"1"}

	a := assert.New(t)
	body := &bytes.Buffer{}
	for _, book := range createBooks {
		meta := []byte(fmt.Sprintf(`{ "index" : { "_id" : "%s" } }%s`, book.ID, "\n"))
		data, err := json.Marshal(book)
		a.Nil(err)
		data = append(data, "\n"...)
		body.Grow(len(meta) + len(data))
		body.Write(meta)
		body.Write(data)
	}
	for _, id := range deleteBookIds {
		meta := []byte(fmt.Sprintf(`{ "delete" : { "_id" : "%s" } }%s`, id, "\n"))
		body.Grow(len(meta))
		body.Write(meta)
	}
	t.Log(body.String())

	response, err := client.Bulk(body, client.Bulk.WithIndex("book"))
	a.Nil(err)
	t.Log(response)
}

文档搜索 单个字段


// 文档搜索 单个字段
func TestSearchByOneDoc(t *testing.T) {
	a := assert.New(t)

	query := map[string]interface{}{
		"query": map[string]interface{}{
			"match": map[string]interface{}{
				"name": "神雕侠侣",
			},
		},
		"highlight": map[string]interface{}{
			"pre_tags":  []string{"<font color='red'>"},
			"post_tags": []string{"</font>"},
			"fields": map[string]interface{}{
				"title": map[string]interface{}{},
			},
		},
	}
	marshal, _ := json.Marshal(query)
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

查询操作

提高某个字段权重,可以使用 ^ 字符语法为单个字段提升权重,在字段名称的末尾添加 ^boost ,其中 boost 是一个浮点数:

func TestSearchBy(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"query": map[string]interface{}{
			"multi_match": map[string]interface{}{
				"query":  "《天龙八部》",
				"fields": []string{"name", "author^2"},
			},
		},
		"highlight": map[string]interface{}{
			"pre_tags":  []string{"<font color='red'>"},
			"post_tags": []string{"</font>"},
			"fields": map[string]interface{}{
				"title": map[string]interface{}{},
			},
		},
	}
	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

// 显示所有的

func TestSearchByAll(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"query": map[string]interface{}{
			"match_all": map[string]interface{}{},
		},
	}
	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

// 范围查询通过range实现范围查询,类似SQL语句中的>, >=, <, <=表达式。 gte范围参数 - 等价于>= lte范围参数 - 等价于 <= 范围参数可以只写一个,例如:仅保留 “gte”: 10, 则代表 FIELD字段 >= 10

func TestSearchByRang(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"query": map[string]interface{}{
			"range": map[string]interface{}{
				"price": map[string]interface{}{
					"gte": "0",
					"lte": "20",
				},
			},
		},
	}
	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

文档搜索 多个字段

func TestSearchByInesDoc(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"query": map[string]interface{}{
			"multi_match": map[string]interface{}{
				"query":  "金",
				"fields": []string{"name", "author"},
			},
		},
		"highlight": map[string]interface{}{
			"pre_tags":  []string{"<font color='red'>"},
			"post_tags": []string{"</font>"},
			"fields": map[string]interface{}{
				"title": map[string]interface{}{},
			},
		},
	}
	marshal, _ := json.Marshal(query)
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

布尔 must and

func TestSearchByAnd(t *testing.T) {
	a := assert.New(t)

	name := "金庸"
	price := "0"
	query := map[string]interface{}{
		"query": map[string]interface{}{
			"bool": map[string]interface{}{
				"must": []map[string]interface{}{
					{
						"match": map[string]interface{}{
							"author": name,
						},
					},
					{
						"match": map[string]interface{}{
							"price": price,
						},
					},
				},
			},
		},
		"from": 0,
		"size": 1,
		"sort": []map[string]interface{}{
			{"pubDate": []map[string]interface{}{
				{"order": "desc"},
			},
			},
		},
	}
	marshal, _ := json.Marshal(query)

	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

布尔查询 or

func TestSearchByOr(t *testing.T) {
	a := assert.New(t)

	name := "金庸"
	price := "0"
	query := map[string]interface{}{
		"query": map[string]interface{}{
			"bool": map[string]interface{}{
				"should": []map[string]interface{}{
					{
						"match": map[string]interface{}{
							"author": name,
						},
					},
					{
						"match": map[string]interface{}{
							"price": price,
						},
					},
				},
			},
		},
		"from": 0,
		"size": 1,
		"sort": []map[string]interface{}{
			{"pubDate": []map[string]interface{}{
				{"order": "desc"},
			},
			},
		},
	}
	marshal, _ := json.Marshal(query)

	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

精确度查询

func TestSearchByTerm(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"query": map[string]interface{}{
			"term": map[string]interface{}{
				"name.keyword": "射雕英雄传",
			},
		},
	}

	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

使用Mysql 的方式查询

func TestSearchBySql(t *testing.T) {
	a := assert.New(t)
	index := "book"
	query := map[string]interface{}{
		"query": "select count(1) from " + index,
	}
	jsonBody, _ := json.Marshal(query)
	t.Log(string(jsonBody))
	response, err := client.SQL.Query(bytes.NewReader(jsonBody), client.SQL.Query.WithContext(context.Background()))
	a.Nil(err)
	t.Log(response)
}

Cat 的操作

func TestCatDemo(t *testing.T) {
	// 查看集群健康状态
	health, _ := client.Cat.Health()
	t.Log(health.String())
	//allocation 查看节点磁盘资源分配信息
	allocation, _ := client.Cat.Allocation(client.Cat.Allocation.WithNodeID(""))
	t.Log(allocation)
	//shards 节点分片信息
	shards, _ := client.Cat.Shards()
	t.Log(shards)
	//master?v 查看主节点
	master, _ := client.Cat.Master()
	t.Log(master)
	// nodes 查看集群信息
	nodes, _ := client.Cat.Nodes()
	t.Log(nodes)
	// tasks 返回集群中一个或多个节点上当前执行的任务信息。
	tasks, _ := client.Cat.Tasks()
	t.Log(tasks)
	// indices 查看索引信息
	response, _ := client.Cat.Indices(client.Cat.Indices.WithIndex(""))
	t.Log(response)
	// segments 分片中的分段信息
	segments, _ := client.Cat.Segments()
	t.Log(segments)
	// count 查看当前集群的doc数量
	count, _ := client.Cat.Count()
	t.Log(count)
	// recovery 显示正在进行和先前完成的索引碎片恢复的视图
	recovery, _ := client.Cat.Recovery()
	t.Log(recovery)
	// /pending_tasks 显示正在等待的任务
	pendingTasks, _ := client.Cat.PendingTasks()
	t.Log(pendingTasks)
	// aliases 显示别名、过滤器、路由信息
	aliases, _ := client.Cat.Aliases()
	t.Log(aliases)
	// thread_pool 查看线程池信息
	threadPool, _ := client.Cat.ThreadPool()
	t.Log(threadPool)
	// plugins 显示每个运行插件节点的视图
	plugins, _ := client.Cat.Plugins()
	t.Log(plugins)
	// fielddata #查看每个数据节点上fielddata当前占用的堆内存。
	fielddata, _ := client.Cat.Fielddata()
	t.Log(fielddata)
	// nodeattrs 查看每个节点的自定义属性
	nodeattrs, _ := client.Cat.Nodeattrs()
	t.Log(nodeattrs)
	// /templates 模板
	templates, _ := client.Cat.Templates()
	t.Log(templates)
}

聚合查询

聚合 group by

func TestAggGroupBy(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"aggs": map[string]interface{}{ // 合查询语句的简写
			"count_name": map[string]interface{}{ // 给聚合查询取个名字,
				"terms": map[string]interface{}{ // 聚合类型为,terms,terms是桶聚合的一种,类似SQL的group by的作用,根据字段分组,相同字段值的文档分为一组。
					"field": "name.keyword", // terms聚合类型的参数,这里需要设置分组的字段为name,根据name分组
				},
			},
		},
		"from": 0,
		"size": 1,
		"sort": []map[string]interface{}{
			{"pubDate": []map[string]interface{}{
				{"order": "desc"},
			},
			},
		},
	}
	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

count

func TestAggCount(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"aggs": map[string]interface{}{ // 合查询语句的简写
			"count_name": map[string]interface{}{ // 给聚合查询取个名字,
				"value_count": map[string]interface{}{
					"field": "name.keyword", //
				},
			},
		},
		"from": 0,
		"size": 1,
		"sort": []map[string]interface{}{
			{"pubDate": []map[string]interface{}{
				{"order": "desc"},
			},
			},
		},
	}
	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

Cardinality 基数聚合,也是用于统计文档的总数,跟Value Count的区别是,基数聚合会去重,不会统计重复的值,类似SQL的count(DISTINCT 字段)用法。

func TestAggCardinality(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"aggs": map[string]interface{}{ // 合查询语句的简写
			"count_name": map[string]interface{}{ // 给聚合查询取个名字,
				"cardinality": map[string]interface{}{
					"field": "name.keyword", //
				},
			},
		},
		"from": 0,
		"size": 1,
		"sort": []map[string]interface{}{
			{"pubDate": []map[string]interface{}{
				{"order": "desc"},
			},
			},
		},
	}
	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

Avg

func TestAggAvg(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"aggs": map[string]interface{}{ // 合查询语句的简写
			"count_name": map[string]interface{}{ // 给聚合查询取个名字,
				"avg": map[string]interface{}{
					"field": "price", //
				},
			},
		},
		"from": 0,
		"size": 1,
		"sort": []map[string]interface{}{
			{"pubDate": []map[string]interface{}{
				{"order": "desc"},
			},
			},
		},
	}
	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

sum

func TestAggSum(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"aggs": map[string]interface{}{ // 合查询语句的简写
			"count_name": map[string]interface{}{ // 给聚合查询取个名字,
				"sum": map[string]interface{}{
					"field": "price", //
				},
			},
		},
		"from": 0,
		"size": 1,
		"sort": []map[string]interface{}{
			{"pubDate": []map[string]interface{}{
				{"order": "desc"},
			},
			},
		},
	}
	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

Max

func TestAggMax(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"aggs": map[string]interface{}{ // 合查询语句的简写
			"count_name": map[string]interface{}{ // 给聚合查询取个名字,
				"max": map[string]interface{}{
					"field": "price", //
				},
			},
		},
		"from": 0,
		"size": 1,
		"sort": []map[string]interface{}{
			{"pubDate": []map[string]interface{}{
				{"order": "desc"},
			},
			},
		},
	}
	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

Min

func TestAggMin(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"aggs": map[string]interface{}{ // 合查询语句的简写
			"count_name": map[string]interface{}{ // 给聚合查询取个名字,
				"min": map[string]interface{}{
					"field": "price", //
				},
			},
		},
		"from": 0,
		"size": 1,
		"sort": []map[string]interface{}{
			{"pubDate": []map[string]interface{}{
				{"order": "desc"},
			},
			},
		},
	}
	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

综合

func TestAgg(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"aggs": map[string]interface{}{ // 合查询语句的简写
			"count_name": map[string]interface{}{ // 给聚合查询取个名字,
				"min": map[string]interface{}{
					"field": "price",
				},
			},
			"count_name1": map[string]interface{}{
				"value_count": map[string]interface{}{
					"field": "name.keyword", //
				},
			},
		},
		"from": 0,
		"size": 1,
		"sort": []map[string]interface{}{
			{"pubDate": []map[string]interface{}{
				{"order": "desc"},
			},
			},
		},
	}
	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

// Terms聚合 terms聚合的作用跟SQL中group by作用一样,都是根据字段唯一值对数据进行分组(分桶),字段值相等的文档都分到同一个桶内。select price, count(*) from book group by price

func TestAggTerms(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"aggs": map[string]interface{}{ // 合查询语句的简写
			"count_name": map[string]interface{}{ // 给聚合查询取个名字,
				"terms": map[string]interface{}{
					"field": "price",
				},
			},
		},
		"from": 0,
		"size": 1,
		"sort": []map[string]interface{}{
			{"pubDate": []map[string]interface{}{
				{"order": "desc"},
			},
			},
		},
	}
	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

Histogram聚合

func TestAggHistogram(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"aggs": map[string]interface{}{ // 合查询语句的简写
			"count_name": map[string]interface{}{ // 给聚合查询取个名字,
				"histogram": map[string]interface{}{
					"field":    "price",
					"interval": 50, // 分桶的间隔为50,意思就是price字段值按50间隔分组
				},
			},
		},
		"from": 0,
		"size": 1,
		"sort": []map[string]interface{}{
			{"pubDate": []map[string]interface{}{
				{"order": "desc"},
			},
			},
		},
	}
	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

Date histogram

func TestAggDateHistogram(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"aggs": map[string]interface{}{ // 合查询语句的简写
			"count_name": map[string]interface{}{ // 给聚合查询取个名字,
				"date_histogram": map[string]interface{}{
					"field":             "pubDate",    // 根据date字段分组
					"calendar_interval": "month",      // 分组间隔:month代表每月、支持minute(每分钟)、hour(每小时)、day(每天)、week(每周)、year(每年)
					"format":            "yyyy-MM-dd", // 设置返回结果中桶key的时间格式
				},
			},
		},
		"from": 0,
		"size": 1,
		"sort": []map[string]interface{}{
			{"pubDate": []map[string]interface{}{
				{"order": "desc"},
			},
			},
		},
	}
	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

Range

func TestAggRange(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"aggs": map[string]interface{}{ // 合查询语句的简写
			"count_name": map[string]interface{}{ // 给聚合查询取个名字,
				"range": map[string]interface{}{
					"field": "price",
					"ranges": []interface{}{ // 范围配置
						map[string]float64{"to": 100.0},                // 意思就是 price <= 100的文档归类到一个桶
						map[string]float64{"from": 100.0, "to": 200.0}, // price>100 and price<200的文档归类到一个桶
						map[string]float64{"from": 200.0},              // price>200的文档归类到一个桶},
					},
				},
			}},
		"from": 0,
		"size": 1,
		"sort": []map[string]interface{}{
			{"pubDate": []map[string]interface{}{
				{"order": "desc"},
			},
			},
		},
	}
	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}

综合案例

func TestAggs(t *testing.T) {
	a := assert.New(t)
	query := map[string]interface{}{
		"aggs": map[string]interface{}{ // 合查询语句的简写
			"count_name1": map[string]interface{}{ // 给聚合查询取个名字,
				"range": map[string]interface{}{
					"field": "price",
					"ranges": []interface{}{ // 范围配置
						map[string]float64{"to": 100.0},                // 意思就是 price <= 100的文档归类到一个桶
						map[string]float64{"from": 100.0, "to": 200.0}, // price>100 and price<200的文档归类到一个桶
						map[string]float64{"from": 200.0},              // price>200的文档归类到一个桶},
					},
				},
			},
			"aggs": map[string]interface{}{ // 合查询语句的简写
				"count_name": map[string]interface{}{ // 给聚合查询取个名字,
					"min": map[string]interface{}{
						"field": "price",
					},
				},
			}},
	}
	marshal, _ := json.Marshal(query)
	t.Log(string(marshal))
	response, err := client.Search(client.Search.WithIndex("book"), client.Search.WithBody(bytes.NewReader(marshal)))
	a.Nil(err)
	t.Log(response)
}
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值