Spring-Data方式对ES进行分组聚合操作
上文【ElasticSearch】spring-data方式操作elasticsearch(一)进阶
1.10 搜索-分组
@Test
public void searchAggr() {
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
.addAggregation(AggregationBuilders.terms("ageCount")
.field("age")
.size(100)
.subAggregation(AggregationBuilders.terms("professionalCount").field("professional.keyword")
.subAggregation(AggregationBuilders.topHits("fieldNms")
.fetchSource(new String[] {"uid","age","professional","name"}, null))));
// 分组聚合分页结果
AggregatedPage<PeopleBean> peopleAggrPage = (AggregatedPage<PeopleBean>)peopleEsDao.search(queryBuilder.build());
System.out.println("结果:");
ParsedLongTerms ageAggr = (ParsedLongTerms)peopleAggrPage.getAggregation("ageCount");
List<? extends Bucket> buckets = ageAggr.getBuckets();
for (Bucket bucket : buckets) {
Number age = bucket.getKeyAsNumber();
long docCount = bucket.getDocCount();
System.out.println("年龄:"+age + " 总数:" + docCount);
Aggregations aggregations = bucket.getAggregations();
for (Aggregation aggregation : aggregations) {
ParsedStringTerms profAggr = (ParsedStringTerms) aggregation;
List<? extends Bucket> profBuckets = profAggr.getBuckets();
for (Bucket bucket2 : profBuckets) {
long profCount = bucket2.getDocCount();
String prof = bucket2.getKeyAsString();
System.out.println("\t职业:"+prof+" 总数:"+profCount);
Aggregations filedNmAggrs = bucket2.getAggregations();
for (Aggregation filedNmAggr : filedNmAggrs) {
ParsedTopHits topHits = (ParsedTopHits) filedNmAggr ;
SearchHits hits = topHits.getHits();
for (SearchHit hit : hits) {
String source = hit.getSourceAsString();
System.out.println("\t\t" + JSON.parseObject(source, PeopleBean.class));
}
}
}
}
}
}
类似SQL:
select
uid, age, professional, name
from people
group by age, professional
结果:
结果:
年龄:45 总数:4
职业:演员 总数:2
PeopleBean(uid=8, name=张家辉, age=45, addr=null, birthDay=null, professional=演员, interest=null)
PeopleBean(uid=1, name=吴彦祖, age=45, addr=null, birthDay=null, professional=演员, interest=null)
职业:歌手 总数:1
PeopleBean(uid=9, name=毛不易, age=45, addr=null, birthDay=null, professional=歌手, interest=null)
职业:武打演员 总数:1
PeopleBean(uid=3, name=吴京, age=45, addr=null, birthDay=null, professional=武打演员, interest=null)
年龄:30 总数:2
职业:歌手 总数:1
PeopleBean(uid=6, name=刘亦菲, age=30, addr=null, birthDay=null, professional=歌手, interest=null)
职业:运动员 总数:1
PeopleBean(uid=7, name=刘翔, age=30, addr=null, birthDay=null, professional=运动员, interest=null)
年龄:55 总数:2
职业:歌手 总数:1
PeopleBean(uid=2, name=吴奇隆, age=55, addr=null, birthDay=null, professional=歌手, interest=null)
职业:演员 总数:1
PeopleBean(uid=4, name=古天乐, age=55, addr=null, birthDay=null, professional=演员, interest=null)
年龄:35 总数:1
职业:运动员 总数:1
PeopleBean(uid=5, name=苏炳添, age=35, addr=null, birthDay=null, professional=运动员, interest=null)