弹性搜索中的多个过滤器和聚合

gee*_*ekQ 25 elasticsearch

如何在elasticsearch中使用与聚合相关的过滤器?

官方文档仅提供过滤器聚合的简单示例,并且没有对dsl的查询的正式描述 - 例如与postgres文档进行比较.

通过尝试我发现以下查询,这是由elasticsearch接受(没有解析错误),但忽略给定的过滤器:

{
  "filter": {
    "and": [
      {
        "term": {
          "_type": "logs"
        }
      },
      {
        "term": {
          "dc": "eu-west-12"
        }
      },
      {
        "term": {
          "status": "204"
        }
      },
      {
        "range": {
          "@timestamp": {
            "from": 1398169707,
            "to": 1400761707
          }
        }
      }
    ]
  },
  "size": 0,
  "aggs": {
    "time_histo": {
      "date_histogram": {
        "field": "@timestamp",
        "interval": "1h"
      },
      "aggs": {
        "name": {
          "percentiles": {
            "field": "upstream_response_time",
            "percents": [
              98.0
            ]
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

有人建议使用query而不是filter.但官方文档通常建议相反过滤精确值.另一个问题query:虽然过滤器提供and,query但没有.

有人可以指向文档,博客或书籍,它描述了编写非平凡的查询:至少是聚合加上多个过滤器.

gee*_*ekQ 27

我最终使用了过滤器聚合 - 未过滤查询.所以现在我有3个嵌套的aggs元素.

由于http://www.elasticsearch.org/blog/all-about-elasticsearch-filter-bitsets/,我也使用bool过滤器而不是and@ alex-brasetvik推荐的过滤器

我最后的实施:

{
  "aggs": {
    "filtered": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "_type": "logs"
              }
            },
            {
              "term": {
                "dc": "eu-west-12"
              }
            },
            {
              "term": {
                "status": "204"
              }
            },
            {
              "range": {
                "@timestamp": {
                  "from": 1398176502000,
                  "to": 1400768502000
                }
              }
            }
          ]
        }
      },
      "aggs": {
        "time_histo": {
          "date_histogram": {
            "field": "@timestamp",
            "interval": "1h"
          },
          "aggs": {
            "name": {
              "percentiles": {
                "field": "upstream_response_time",
                "percents": [
                  98.0
                ]
              }
            }
          }
        }
      }
    }
  },
  "size": 0
}
Run Code Online (Sandbox Code Playgroud)

  • 你现在可能是我最喜欢的人了.几个小时以来一直在争夺这个. (7认同)
  • 在此解决方案中,top aggr字段被命名为"filtered",并且不应与http://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-filtered-query.html混合使用,因此请使用其他名称(例如"aggresults") - 在该名称下,您将获得响应结果.请查看参考资料:http://www.elastic.co/guide/en/elasticsearch/reference/master/search-aggregations-bucket-filter-aggregation.html并回答http://stackoverflow.com/a/24823895/565525 . (4认同)

Ale*_*vik 7

将过滤器放在filtered-query中.

顶级filter用于仅过滤搜索命中,而不是过滤/聚合.post_filter由于这种相当普遍的混淆,它在1.0中被重命名为.

此外,您可能想看看这个职位上,你为什么经常要使用的bool,而不是and/ or:http://www.elasticsearch.org/blog/all-about-elasticsearch-filter-bitsets/