Elasticsearch8.x Java 聚合多个字段
时间: 2024-02-29 19:08:26 浏览: 150
要聚合多个字段,可以使用Elasticsearch的聚合功能。在Java中,可以使用Elasticsearch的Java API来实现。下面是一个示例代码,演示如何聚合多个字段:
```java
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("group_by_field")
.field("field1")
.subAggregation(AggregationBuilders.terms("subgroup_by_field").field("field2"));
searchSourceBuilder.aggregation(aggregationBuilder);
SearchRequest searchRequest = new SearchRequest("index_name");
searchRequest.source(searchSourceBuilder);
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
```
这个代码片段中,我们首先创建一个SearchSourceBuilder对象,然后创建一个TermsAggregationBuilder对象,用于分组聚合。我们通过field()方法指定要聚合的字段,然后使用subAggregation()方法指定在每个分组中再次聚合的字段。最后,我们将聚合器添加到SearchSourceBuilder中,并使用SearchRequest对象执行搜索。
阅读全文