聚合内的ElasticSearch聚合

时间:2019-02-26 20:31:43

标签: elasticsearch elasticsearch-aggregation

我正在尝试为ElasticSearch编写聚合脚本。

文档类型:

{
  Score: [1 , null, 3]
},
{
  Score: [2, 4, null + 3]
}

我想获得所有分数的平均值。我写了简单的汇总,返回

(1 + 3 + 2 + 4 + 3) / 5 = 2.6

但是我想为每个文档执行平均得分,然后将其平均。 例如

[1 + 3] / 2 (# of scores in first document)
+
[2 + 4 + 3] / 3 (# of scores in second document)
= (2 + 3) / 2 (# of documents)
= 2.5

1 个答案:

答案 0 :(得分:0)

我认为此查询正是您要寻找的:

{
  "size": 0,
  "aggs": {
    "group_by_id": {
      "terms": {
        "field": "_id"
      },
      "aggs": {
        "avg_by_group": {
          "avg": {
            "field": "score"
          }
        }
      }
    },
    "overall_avg": {
      "avg_bucket": {
        "buckets_path": "group_by_id>avg_by_group"
      }
    }
  }
}

说明

group_by_id聚合将为每个文档创建一个存储桶,而avg_by_group子聚合将为每个存储桶/文档计算平均score。最后,overall_avg管道聚合将计算平均值的平均值。