Elasticsearch:如何设置过滤器聚合的“doc_count”与总“doc_count”的关系

分享于2022年07月17日 elasticsearch elasticsearch-aggregation 问答
【问题标题】:Elasticsearch:如何设置过滤器聚合的“doc_count”与总“doc_count”的关系(Elasticsearch: How set 'doc_count' of a FILTER-Aggregation in relation to total 'doc_count')
【发布时间】:2022-01-17 04:15:57
【问题描述】:

一个看似很琐碎的问题,促使我今天又勤奋地阅读了 Elasticsearch 文档。但是,到目前为止,我还没有遇到解决方案....

问题:
有没有一种简单的方法来设置过滤器聚合的 doc_count 与总 doc_count 的关系?

这是我的 search-request-json 中的一个 sn-p。
feature_occurrences 聚合中,我过滤了文档。
现在我想计算每个时间段中过滤/所有文档的比率。

GET my_index/_search
{
  "aggs": {
    "time_buckets": {
      "date_histogram": {
        "field": "date",
        "calendar_interval": "1d",
        "min_doc_count": 0
      },
      "aggs": {
        "feature_occurrences": {
          "filter": {
            "term": {
              "x": "y"
            }
          }
        },
        "feature_occurrences_per_doc" : {
             
            // feature_occurences.doc_count / doc_count 
         
       }

       

有什么想法吗?


【解决方案1】:

您可以使用 bucket_script 来计算比率:

{
  "aggs": {
    "date": {
      "date_histogram": {
        "field": "@timestamp",
        "interval": "hour"
      },
      "aggs": {
        "feature_occurrences": {
          "filter": {
            "term": {
              "cloud.region": "westeurope"
            }
          }
        },
        "ratio": {
          "bucket_script": {
            "buckets_path": {
              "doc_count": "_count",
              "features_count": "feature_occurrences._count"
            },
            "script": "params.features_count / params.doc_count"
          }
        }
      }
    }
  }
}

弹性桶脚本文档:

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-bucket-script-aggregation.html