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

相关推荐
Ivanqhz4 分钟前
NFM(神经因子分解机)
开发语言·javascript·人工智能·算法·蓝桥杯
Elasticsearch8 分钟前
Semantic_text 字段默认嵌入模型变为 .jina-embeddings-v5-text-small
elasticsearch
yxlalm43 分钟前
2.java秒杀项目第二课-后端登录功能
java·开发语言
光学补偿1 小时前
文件IO的前世今生
开发语言·学习·面试·java-ee
解局易否结局1 小时前
鸿蒙原生开发实战:用 Native C++ 与 OpenGL ES 构建高性能图形渲染管线
c++·elasticsearch·华为·harmonyos
ttwuai1 小时前
后台管理系统 RBAC 排障:隐藏菜单后接口为什么还能调用
golang
玖玥拾2 小时前
C# 语言进阶(十三)网络 DLL 库分层设计
服务器·开发语言·网络·网络协议·c#
2601_949816352 小时前
C++内存对齐与结构体填充深度精讲:底层规则、内存裁剪、适配优化与工程避坑
开发语言·arm开发·c++
浩瀚地学2 小时前
【面试算法笔记】0105-数组-螺旋矩阵
java·开发语言·笔记·算法·面试
Geek-Chow2 小时前
Mobile App Certificate Pinning: Underlying Principle and a Swift Example
开发语言·ios·swift·安全架构