[go 开源推荐] esquery —— 语法简单的 elasticsearch 请求库 | go优质外文翻译 | go 技术论坛-江南app体育官方入口
介绍
esquery
减少了使用嵌套极为紧密的映射(map[string]interface{}
)和手动将查询序列化为 json 的需要。由于所有内容都是静态类型,因此它还有助于消除常见错误,例如查询类型拼写错误。
使用 esquery
可以使您的代码更易于编写、读取和维护,并显著减少您编写的代码量。想知道你能节省多少代码吗?检查一下这个项目的测试。
安装
esquery
是一个 go 模块。要安装它,只需要在项目的根目录中运行此命令:
go get github.com/aquasecurity/esquery
使用说明
esquery 提供了一种样式的 api,用于构建、执行查询和聚合。它不封装正式的 go 客户端,也不要求您更改现有代码来集成这个库。可以使用 esquery
直接构建查询,并通过传递 * elasticsearch.client
实例(带有可选搜索参数)来执行查询。结果从官方客户端按原样返回(例如 * esapi.response
对象)。
入门非常简单:
package main
import (
"context"
"log"
"github.com/aquasecurity/esquery"
"github.com/elastic/go-elasticsearch/v7"
)
func main() {
// 连接到 elasticsearch 实例
es, err := elasticsearch.newdefaultclient()
if err != nil {
log.fatalf("failed creating client: %s", err)
}
// 运行布尔搜索查询
qres, err := esquery.query(
esquery.
bool().
must(esquery.term("title", "go and stuff")).
filter(esquery.term("tag", "tech")),
).run(
es,
es.search.withcontext(context.todo()),
es.search.withindex("test"),
)
if err != nil {
log.fatalf("failed searching for stuff: %s", err)
}
defer qres.body.close()
// 运行聚合
ares, err := esquery.aggregate(
esquery.avg("average_score", "score"),
esquery.max("max_score", "score"),
).run(
es,
es.search.withcontext(context.todo()),
es.search.withindex("test"),
)
if err != nil {
log.fatalf("failed searching for stuff: %s", err)
}
defer ares.body.close()
// ...
}
特征
支持的查询
当前支持以下查询:
elasticsearch dsl | esquery function |
---|---|
"match" |
match() |
"match_bool_prefix" |
matchboolprefix() |
"match_phrase" |
matchphrase() |
"match_phrase_prefix" |
matchphraseprefix() |
"match_all" |
matchall() |
"match_none" |
matchnone() |
"exists" |
exists() |
"fuzzy" |
fuzzy() |
"ids" |
ids() |
"prefix" |
prefix() |
"range" |
range() |
"regexp" |
regexp() |
"term" |
term() |
"terms" |
terms() |
"terms_set" |
termsset() |
"wildcard" |
wildcard() |
"bool" |
bool() |
"boosting" |
boosting() |
"constant_score" |
constantscore() |
"dis_max" |
dismax() |
支持的聚合
当前支持以下聚合:
elasticsearch dsl | esquery function |
---|---|
"avg" |
avg() |
"weighted_avg" |
weightedavg() |
"cardinality" |
cardinality() |
"max" |
max() |
"min" |
min() |
"sum" |
sum() |
"value_count" |
valuecount() |
"percentiles" |
percentiles() |
"stats" |
stats() |
"string_stats" |
stringstats() |
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 cc 协议,如果我们的工作有侵犯到您的权益,请及时联系江南app体育官方入口。
原文地址: