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:9200 和 your-index 分别为你的 Elasticsearch 主机地址和索引名称。

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

相关推荐
Elasticsearch2 小时前
Elasticsearch:为自行管理的 Elastic Stack 自定义 TLS 证书
elasticsearch
WJ.Polar7 小时前
Java封装、继承、多态
java·开发语言
Elasticsearch7 小时前
斯坦福《2026 年 AI 指数报告》与金融服务业的安全现实
elasticsearch
9624567 小时前
Go EVM 链上数据平台实践:从 RPC Demo 到可演进架构
rpc·架构·golang
摇滚侠7 小时前
Java 中如何表示负数,有符号和无符号的区别,补码的计算规则,char byte short int long 的范围
java·开发语言
weixin_307779137 小时前
C++代码实现MATLAB中的fitrtree函数功能
开发语言·c++·算法·matlab
爱读书的小胖8 小时前
Codewars:Rot13(C)解题分析
c语言·开发语言
鸽鸽程序猿8 小时前
【项目】【在线判题系统】b端题目增删改
开发语言·python
Lhappy嘻嘻8 小时前
读懂 JVM:内存模型、类加载机制、分代回收
java·开发语言·jvm
weixin_307779139 小时前
C++代码实现MATLAB中的spectralcluster函数功能
开发语言·c++·算法·matlab