我也发现 Elastic 的 DSL 结构令人困惑,但在运行了数百个查询之后你就习惯了。
以下是不同类型查询的几个(完整)示例,希望这将有助于解决您可能遇到的一些问题,请随时在评论中添加场景,我会添加更多示例。
这是标准查询的样子:
{
"query": {
"bool": {
"must": {
"match": {
"message": "abcd"
}
}
}
}
}
但是,这是过滤后查询的样子,您会在过滤 elasticsearch 时注意到结构发生了变化:
{
"query": {
"filtered": {
"filter": {
"term": {
"message": "abcd"
}
}
}
}
}
(Read more about the difference between Filters and Queries)
同时具有过滤器和查询的查询如下所示:
{
"query": {
"filtered": {
"filter": {
"term": {
"message": "abcd"
}
},
"query": {
"bool": {
"must": {
"match": {
"message2": "bbbb"
}
}
}
}
}
}
}
以下是运行具有多个条件的过滤器的方法:
{
"query": {
"filtered": {
"filter": {
"and": [
{
"term": {
"message": "abcd"
}
},
{
"term": {
"message2": "abcdd"
}
}
]
}
}
}
}
还有一个更复杂的过滤器:
{
"query": {
"filtered": {
"filter": {
"and": [
{
"term": {
"message": "abcd"
}
},
{
"term": {
"message2": "abcdd"
}
},
{
"or": [
{
"term": {
"message3": "abcddx"
}
},
{
"term": {
"message4": "abcdd2"
}
}
]
}
]
}
}
}
}
使用聚合的简单查询:
{
"query": {
"filtered": {
"filter": {
"term": {
"message": "abcd"
}
}
}
},
"aggs": {
"any_name_will_work_here": {
"max": {
"field": "metric1"
}
}
}
}
query_string 查询:
{
"query": {
"query_string": {
"default_field": "message",
"query": "this AND that"
}
}
}
使用 DSL 时需要考虑的其他一些事项:
- 您可以在顶层(查询上方)添加
size 参数,该参数将确定要返回的结果数量。如果您只需要文档计数,您可以使用 "size": 0,它不会得到任何结果,只会得到元数据。
- 然而,当使用
aggs 时,size 参数有一个扭曲,在aggs 字段内设置"size": 0 将告诉ES 获取ALL 聚合桶
- DSL 结构有例外,在我的示例中,我通常使用
terms,但range 的结构有点不同。