我正在尝试为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
答案 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
管道聚合将计算平均值的平均值。