對於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