在 Go 中需要在 Elasticsearch 中执行带有过滤条件的查询时,你可以使用 github.com/olivere/elastic
库的过滤器(Filter)功能。以下是一个示例代码,展示了如何在 Go 中使用 Elasticsearch 进行带有过滤条件的分页查询:
package mainimport ("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 := 10pageNumber := 1from := (pageNumber - 1) * pageSize// 执行查询searchResult, err := client.Search().Index("your-index").Query(query).PostFilter(filter). // 将过滤条件添加为 PostFilterFrom(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 发送带有过滤条件的分页请求。如果你有其他问题或需要进一步的帮助,请随时告诉我。