Go查询Elasticsearch

在 Go 中需要在 Elasticsearch 中执行带有过滤条件的查询时,你可以使用 github.com/olivere/elastic 库的过滤器(Filter)功能。以下是一个示例代码,展示了如何在 Go 中使用 Elasticsearch 进行带有过滤条件的分页查询:

go 复制代码
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/olivere/elastic/v7"
)

func main() {
	// 创建 Elasticsearch 客户端
	client, err := elastic.NewClient(elastic.SetURL("http://your-elasticsearch-host:9200"))
	if err != nil {
		// 处理错误
		log.Fatalf("Error creating the client: %s", err)
	}

	// 准备查询和过滤条件
	query := elastic.NewMatchAllQuery()
	filter := elastic.NewRangeQuery("age").Gte(18)

	// 设置分页参数
	pageSize := 10
	pageNumber := 1
	from := (pageNumber - 1) * pageSize

	// 执行查询
	searchResult, err := client.Search().
		Index("your-index").
		Query(query).
		PostFilter(filter). // 将过滤条件添加为 PostFilter
		From(from).
		Size(pageSize).
		Do(context.Background())
	if err != nil {
		// 处理错误
		log.Fatalf("Error executing the search: %s", err)
	}

	// 处理搜索结果
	fmt.Printf("Total hits: %d\n", searchResult.TotalHits())
	for _, hit := range searchResult.Hits.Hits {
		var data map[string]interface{}
		err := json.Unmarshal(hit.Source, &data)
		if err != nil {
			log.Printf("Error unmarshalling JSON: %s", err)
		}
		fmt.Printf("Document ID: %s, Data: %v\n", hit.Id, data)
	}
}

在这个示例中,我们添加了一个名为 filter 的过滤条件,并使用 PostFilter 方法将其添加到查询中。这样,我们就可以在查询中同时使用查询条件和过滤条件。这个示例中的过滤条件是一个范围查询,用来过滤出年龄大于等于 18 岁的文档。

更多查询可以用更多的方法:

例如,要匹配 "file" 字段为 "/var/audit.log" 的的数据
termQuery := elastic.NewTermQuery("file", "/var/paas/sys/log/kubernetes/audit/audit.log")

同样,请替换代码中的 http://your-elasticsearch-host:9200your-index 分别为你的 Elasticsearch 主机地址和索引名称。

希望这个示例能够帮助你使用 Go 语言向 Elasticsearch 发送带有过滤条件的分页请求。如果你有其他问题或需要进一步的帮助,请随时告诉我。

相关推荐
星空椰8 小时前
Python 面向对象高级:继承与类定义详解
开发语言·python
白露与泡影8 小时前
2026大厂Java面试题大全!牛客网最新版
java·开发语言
凯瑟琳.奥古斯特9 小时前
高阶子查询题目精炼
开发语言·数据库·python·职场和发展·数据库开发
雪度娃娃9 小时前
转向现代C++——在意为改写的函数添加 override
开发语言·c++
喵星人工作室10 小时前
C++火影忍者1.1.2
开发语言·c++
basketball61610 小时前
C++ 中的 ptrdiff_t 详解
开发语言·c++
月亮邮递员61611 小时前
Markdown语法总结
开发语言·前端·javascript
printfLILEI11 小时前
php中的类与对象以及反序列化
linux·开发语言·php
曹牧11 小时前
C#:主线程能够捕获到子线程中的异常
开发语言·数据库·c#
代码中介商11 小时前
深入解析STL中的stack、queue与priority_queue
开发语言·c++