聚合子查詢:
TermsAggregationBuilder aggregation = AggregationBuilders.terms("dt_id").field("dt_ids").size(30000);
String agg_area_field = "city_code";
TermsAggregationBuilder area_field_builder = AggregationBuilders.terms("area_field").field(agg_area_field).size(30000);
area_field_builder.subAggregation(aggregation);
SearchResponse response = client.prepareSearch(index_name).setTypes("lw_devices")
.setQuery(boolQuery)
.addAggregation(area_field_builder)
.execute()
.actionGet();
以上demo的大致的意思就是,先對city_code字段進行聚合,然后對聚合結果,再用dt_ids字段進行嵌套聚合(子聚合) , 相當於sql的兩個group by , 一個聚合嵌套於另一個聚合之內,可以用subAggregation方法進行關聯。
然后就是對聚合結果的遍歷:
Terms terms = response.getAggregations().get("area_field");
List<Terms.Bucket> buckets = terms.getBuckets();for (Terms.Bucket bucket : buckets) {
//地區
String code = (String) bucket.getKey();
System.out.println(code);
Aggregations aggregations = bucket.getAggregations();
Terms dt_id = aggregations.get("dt_id");
List<Terms.Bucket> buckets1 = dt_id.getBuckets();
for (Terms.Bucket bucket1 : buckets1) {
System.out.println(bucket1.getKey() + ":" + bucket1.getDocCount());
}
}
思路就是,先根據response拿到aggregation,然后根據標識符拿到對應的,聚合類型,然后得到bucket的集合。然后再通過bucket拿到aggregation, 然后以此循環往下提取聚合結果。
