java查询elasticsearch聚合

时间:2024-01-27 16:09:09

java查es多分组聚合:

SearchRequestBuilder requestBuilderOfLastMonth = transportClient.prepareSearch(TYPE_NAME + "_" + date + "*").setTypes(TYPE_NAME);
TermsAggregationBuilder groupByLastMonthWeek = AggregationBuilders.terms("groupByWeek").field("week")
.subAggregation(AggregationBuilders.terms("groupByHour").field("hour")
.subAggregation(AggregationBuilders.sum("sumDown").field("downOutput")))
.size(100);

requestBuilderOfLastMonth.setQuery(boolQueryBuilder).addAggregation(groupByLastMonthWeek);
SearchResponse responseOfLastMonth = requestBuilderOfLastMonth.get();

Terms termsfOfLastMonth = responseOfLastMonth.getAggregations().get("groupByWeek");
for (Terms.Bucket entry : termsfOfLastMonth.getBuckets()) {
String oneWeek = entry.getKey().toString();
Terms groupByHour = entry.getAggregations().get("groupByHour");
for (Terms.Bucket entry2 : groupByHour.getBuckets()) {
Map<String, Object> kvMap = new HashMap<>();
String hour = entry2.getKey().toString();
Sum downSum = entry2.getAggregations().get("sumDown");
double sumValue = downSum.getValue();
kvMap.put(hour, sumValue);
lastMonthWeekMap.put(oneWeek, kvMap);
}
}
查询的核心代码,client是TransportClient