springboot整合ES的聚合查询
时间: 2023-10-09 10:04:19 浏览: 62
SpringBoot整合ES的聚合查询可以通过使用ElasticsearchTemplate来实现。聚合查询可以用于统计和分析数据,可以按照某个字段进行分组、计数、求和等操作。下面是一个示例代码:
```java
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;
@Service
public class AggregationService {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
public void aggregateQuery() {
Terms aggregation = elasticsearchTemplate.query(
new NativeSearchQueryBuilder()
.withIndices("your_index")
.withTypes("your_type")
.withQuery(QueryBuilders.matchAllQuery())
.addAggregation(AggregationBuilders.terms("by_field").field("your_field"))
.addAggregation(AggregationBuilders.sum("sum_field").field("your_field"))
.build(),
response -> response.getAggregations().get("by_field")
);
for (Terms.Bucket entry : aggregation.getBuckets()) {
String key = entry.getKeyAsString();
long docCount = entry.getDocCount();
Sum sum = entry.getAggregations().get("sum_field");
double sumValue = sum.getValue();
// 进行其他操作
}
}
}
```