之前寫過《es~通過ElasticsearchTemplate進行聚合操作》的文章,這一次主要寫一個嵌套的聚合,例如先對sex集合,再對desc聚合,最后再對age求和,共三層嵌套,
Aggregations的部分特性類似于SQL語言中的group by,avg,sum等函式,Aggregations需要理解兩個概念:
- 桶(Buckets):符合條件的檔案的集合,相當于SQL中的group by,按“性別”聚合,一個人將被分到男桶或女桶
- 指標(Metrics):基于Buckets的基礎上進行統計分析,并進行計算,大多數metric是數學計算,僅輸出一個值,min/max/avg/sum/cardinality,部分metric支持輸出多個數值,stats(統計)/percentiles(百分比)/percentile_ranks
嵌套聚合寫法
// 創建一個查詢條件物件
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
// 拼接查詢條件
queryBuilder.should(QueryBuilders.termQuery("creator", "1"));
// 創建聚合查詢條件
TermsAggregationBuilder sexAgg = AggregationBuilders
.terms("sex")
.field("sex.keyword");//keyword表示不使用分詞進行聚合,全字匹配
TermsAggregationBuilder descAgg = AggregationBuilders
.terms("desc")
.field("desc.keyword");//keyword表示不使用分詞進行聚合,全字匹配
SumAggregationBuilder ageSumAgg = AggregationBuilders
.sum("ageSum")
.field("age");
//嵌套
descAgg.subAggregation(ageSumAgg);
sexAgg.subAggregation(descAgg);
// 創建查詢物件
SearchQuery build = new NativeSearchQueryBuilder()
.withQuery(queryBuilder) //添加查詢條件
.addAggregation(sexAgg) // 添加聚合條件
.withPageable(PageRequest.of(0, 1)) //符合查詢條件的檔案分頁,如果檔案比較大,可以把這個分頁改小(不是聚合的分頁)
.build();
// 執行查詢
AggregatedPage<TestEsDto> testEntities = elasticsearchTemplate.queryForPage(build, TestEsDto.class);
// 取出聚合結果
Aggregations entitiesAggregations = testEntities.getAggregations();
Terms terms = (Terms) entitiesAggregations.asMap().get("sex");
// 遍歷取出聚合欄位列的值,與對應的數量
for (Terms.Bucket bucket : terms.getBuckets()) {
Terms descTerms = (Terms) bucket.getAggregations().asMap().get("desc");
for (Terms.Bucket descTermsBucket : descTerms.getBuckets()) {
ParsedSum parsedSum = descTermsBucket.getAggregations().get("ageSum");//注意從bucket而不是searchResponse
System.out.println(bucket.getKeyAsString() + "\t" +
bucket.getDocCount() + "\t" +
descTermsBucket.getKeyAsString() + "\t" +
parsedSum.getValueAsString());
}
}
結果
參考:https://www.elastic.co
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/1088.html
標籤:大數據