对于ES 1.7.3,没有办法根据两个不同聚合的结果来计算数据,但这可以在ES 2.0中使用pipeline aggregations来完成。
但是,你所要求的并不是在1.7.3的客户端上做得太复杂。如果您使用下面的查询,你会得到所有你需要得到你所期望的数字:
POST components/_search
{
"size": 0,
"aggs": {
"total_duration": {
"sum": {
"field": "duration"
}
},
"components": {
"terms": {
"field": "component"
},
"aggs": {
"duration_sum": {
"sum": {
"field": "duration"
}
}
}
}
}
}
结果是这样的:
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 4,
"max_score": 0,
"hits": []
},
"aggregations": {
"total_duration": {
"value": 44
},
"components": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "a",
"doc_count": 2,
"duration_sum": {
"value": 15
}
},
{
"key": "b",
"doc_count": 1,
"duration_sum": {
"value": 27
}
},
{
"key": "c",
"doc_count": 1,
"duration_sum": {
"value": 2
}
}
]
}
}
}
现在,所有你需要做的是下列。我正在使用JavaScript,但您可以使用任何可以读取JSON的其他语言来执行此操作。
var response = ...the JSON response above...
var total_duration = response.aggregations.total_duration.value;
var total_docs = response.hits.total;
response.aggregations.components.buckets.forEach(function(comp_stats) {
// total duration for the component
var total_duration_comp = comp_stats.duration_sum.value;
// percentage duration of the component
var perc_duration_comp = total_duration_comp/total_duration * 100;
// percentage documents for the component
var perc_doc_comp = comp_stats.doc_count/total_docs * 100;
});
来源
2015-11-05 05:26:09
Val
我的意思是,我应该怎么做,在一个单一的查询。 –
相关:https://stackoverflow.com/questions/43508321/elasticsearch-calculate-percentage-for-each-bucket-from-total – ChrisWue