【ElasticSearch-聚合查询】ES聚合统计及springboot对比实现
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.avg.Avg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class AggregationService {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
public AggregatedPage<Object> aggregationSearch(String indexName,
String field,
int page,
int size) {
// 创建聚合查询
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
queryBuilder.withIndices(indexName);
queryBuilder.withQuery(QueryBuilders.matchAllQuery());
queryBuilder.addAggregation(AggregationBuilders.terms(field).field(field));
// 执行查询
NativeSearchQuery query = queryBuilder.build();
SearchQuery searchQuery = elasticsearchTemplate.getClient().prepareSearch(query.getIndices())
.setQuery(query.getQuery())
.addAggregation(query.getAggregations()[0])
.setSize(0) // 不需要返回文档,只需要聚合结果
.request();
SearchResponse response = searchQuery.get();
Aggregations aggregations = response.getAggregations();
Terms terms = aggregations.get(field);
// 转换为Spring Data的AggregatedPage
List<Object> content = new ArrayList<>();
for (Terms.Bucket bucket : terms.getBuckets()) {
content.add(bucket.getKey());
}
int totalHits = (
评论已关闭