作者:ydw
地点:武汉
email:[email protected]
原始数据还是引用第一篇中的数据:ElasticSearch超强聚合查询(一)
GET /cars/transactions/_search
{
"size" : 0,
"aggs": {
"sales": {
"date_histogram": {
"field": "sold",
"interval": "quarter",
"format": "yyyy-MM-dd",
"min_doc_count" : 0,
"extended_bounds" : {
"min" : "2014-01-01",
"max" : "2014-12-31"
}
},
"aggs": {
"per_make_sum": {
"terms": {
"field": "make"
},
"aggs": {
"sum_price": {
"sum": { "field": "price" }
}
}
},
"total_sum": {
"sum": { "field": "price" }
}
}
}
}
}
@Test
public void bucketsInsideBuckets(){
SearchResponse response = transportClient.prepareSearch("cars")
.setTypes("transactions")
.addAggregation(
AggregationBuilders.dateHistogram("sales")
.field("sold")
.dateHistogramInterval(DateHistogramInterval.QUARTER)
.format("yyyy-MM-dd")
.minDocCount(0l)
.extendedBounds(
new ExtendedBounds("2014-01-01","2014-12-31")
).subAggregation(
//按照季度划分,每个季度所有品牌的的销售额
AggregationBuilders.sum("total_sum")
.field("price")
)
//添加一个集合的嵌套,在每个季度中,再根据品牌进行划分
.subAggregation(
AggregationBuilders.terms("per_make_sum")
.field("make")
.subAggregation(
//计算各个品牌在每个解读中的销售额
AggregationBuilders.sum("sum_price")
.field("price")
)
)
)
.setSize(0)
.get();
Aggregation sales = response.getAggregations().get("sales");
System.out.println(sales);
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 7,
"max_score": 0.0,
"hits": []
},
"aggregations": {
"sales": {
"buckets": [
{
"key_as_string": "2014-01-01",//第一个季度
"key": 1388534400000,
"doc_count": 1,
"per_make_sum": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "bmw",
"doc_count": 1,
"sum_price": {//各个品牌的销售总额
"value": 80000.0
}
}
]
},
"total_sum": {//所有品牌销售总额
"value": 80000.0
}
},
{
"key_as_string": "2014-04-01",
"key": 1396310400000,
"doc_count": 1,
"per_make_sum": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "ford",
"doc_count": 1,
"sum_price": {
"value": 30000.0
}
}
]
},
"total_sum": {
"value": 30000.0
}
},
{
"key_as_string": "2014-07-01",
"key": 1404172800000,
"doc_count": 2,
"per_make_sum": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "toyota",
"doc_count": 2,
"sum_price": {
"value": 27000.0
}
}
]
},
"total_sum": {
"value": 27000.0
}
},
{
"key_as_string": "2014-10-01",
"key": 1412121600000,
"doc_count": 3,
"per_make_sum": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "honda",
"doc_count": 3,
"sum_price": {
"value": 50000.0
}
}
]
},
"total_sum": {
"value": 50000.0
}
}
]
}
}
}