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 发送带有过滤条件的分页请求。如果你有其他问题或需要进一步的帮助,请随时告诉我。

相关推荐
牛奔13 小时前
Go 如何打印调试深层或嵌套的结构体
开发语言·后端·golang
geovindu14 小时前
go: Iterative Algorithms
开发语言·后端·算法·golang·迭代算法
学逆向的14 小时前
汇编——JCC指令
开发语言·汇编·网络安全
mayaairi15 小时前
JS循环语句深度解析:嵌套for、while与do...while
开发语言·前端·javascript
kite012115 小时前
Go语言Map深度解析与最佳实践
开发语言·后端·golang
l1564694817 小时前
突围!图文混合知识库难以解析,Kimi-K3 原生视觉架构深耕知识工作,DMXAPI 统一接口,缩短项目开发周期
java·大数据·开发语言
charlie11451419117 小时前
现代C++工程实践 WeakPtr 实战(三):WeakPtrFactory 与「最后成员」惯用法
开发语言·c++·开源项目·现代c++
IT小盘19 小时前
04-大模型流式输出原理-SSE与Python实现
开发语言·网络·人工智能·python
不如语冰19 小时前
AI大模型入门-Python进阶-上下文管理与with语句
开发语言·数据结构·数据库·人工智能·pytorch·redis·python
阿童木写作20 小时前
Python批量翻译亚马逊商品图实战教程
开发语言·python·xcode