![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/54071100d9031963987d5f75cf75c7a2.png)
***java Api***
public static List groupBy(String index,String type, String field1,String field2,String sortField){
ESClient esClient = ESClientFactory.me().getDefaultDelegateClient();
SearchRequestBuilder search=esClient.prepareSearch(index).setTypes(type);
//指定分组的字段
AggregationBuilder<TermsBuilder> termsBuilder1 = AggregationBuilders.terms("field1").field(field1).size(Integer.MAX_VALUE);
AggregationBuilder<TermsBuilder> termsBuilder2 = AggregationBuilders.terms("field2").field(field2).subAggregation(AggregationBuilders.max("maxTime").field(sortField)).size(Integer.MAX_VALUE);
search.addAggregation(termsBuilder1.subAggregation(termsBuilder2));
SearchResponse response=search.get();
List list=new ArrayList();
//将查询结果放入map中
Map<String, Aggregation> aggMap = response.getAggregations().getAsMap();
//根据属性名到map中查找
StringTerms teams = (StringTerms) aggMap.get("field1");
for (Terms.Bucket teamBucket : teams.getBuckets()) {
//先按球队进行分组
String team = (String) teamBucket.getKey();
Map<String, Aggregation> subAggMap = teamBucket.getAggregations().getAsMap();
StringTerms positions = (StringTerms) subAggMap.get("field2");
//因为一个球队有很多位置,那么还要依次拿出位置信息
for (Terms.Bucket posBucket : positions.getBuckets()) {
//拿到位置的名字
String pos = (String) posBucket.getKey();
//拿出该位置的数量
long docCount = posBucket.getDocCount();
//打印球队,位置,人数
Max time = posBucket.getAggregations().get("maxTime"); //
double value = time.getValue();
Map map=new TreeMap();
map.put("ip", team);
map.put("hostname", pos);
map.put("count", docCount);
map.put("tem", team);
String stringTime = DateUtil.getStringTime((long) value);
map.put("time", stringTime);
list.add(map);
}
}
return list;
}