ElasticSearch java API - 聚合查询
在ElasticSearch中,我们可以使用Java API进行复杂的聚合查询。以下是一些常见的聚合查询类型及其Java API实现方式的示例。
- 聚合查询 - 统计数量
SearchRequest searchRequest = new SearchRequest("index_name");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.aggregation(AggregationBuilders.count("count_agg").field("field_name"));
searchRequest.source(searchSourceBuilder);
RestHighLevelClient client = new RestHighLevelClient(...);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
Aggregations aggregations = searchResponse.getAggregations();
ParsedLongTerms countAgg = (ParsedLongTerms) aggregations.get("count_agg");
for (Terms.Bucket bucket : countAgg.getBuckets()) {
System.out.println(bucket.getKeyAsString() + " - " + bucket.getDocCount());
}
client.close();
- 聚合查询 - 统计平均值
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.aggregation(AggregationBuilders.avg("avg_agg").field("field_name"));
searchRequest.source(searchSourceBuilder);
...
Aggregations aggregations = searchResponse.getAggregations();
ParsedAvg avgAgg = aggregations.get("avg_agg");
System.out.println("平均值:" + avgAgg.getValue());
...
- 聚合查询 - 按照字段分组统计数量
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.aggregation(AggregationBuilders.terms("terms_agg").field("field_name").size(10));
searchRequest.source(searchSourceBuilder);
...
Aggregations aggregations = searchResponse.getAggregations();
ParsedStringTerms termsAgg = (ParsedStringTerms) aggregations.get("terms_agg");
for (Terms.Bucket bucket : termsAgg.getBuckets()) {
System.out.println(bucket.getKeyAsString() + " - " + bucket.getDocCount());
}
...
- 嵌套聚合查询
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("by_gender").field("gender").size(10);
termsAggregationBuilder.subAggregation(AggregationBuilders.avg("average_height").field("height"));
searchSourceBuilder.aggregation(termsAggregationBuilder);
searchRequest.source(searchSourceBuilder);
...
Aggregations aggregations = searchRes
评论已关闭