SpringBoot ElasticSearch 聚合统计
在Spring Boot中使用Elasticsearch进行聚合统计,你可以使用Spring Data Elasticsearch提供的ElasticsearchRestTemplate
或者ElasticsearchRepository
。以下是一个使用ElasticsearchRestTemplate
进行聚合统计的例子:
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
@Service
public class ElasticsearchStatsService {
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
public Object performStatsAggregation(String indexName, String field) {
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchAllQuery()) // 使用所有文档匹配查询
.withPageable(PageRequest.of(0, 10)) // 设置分页
.addAggregation(
AggregationBuilders.terms(field).field(field) // 创建聚合
);
AggregatedPage<Object> page = elasticsearchRestTemplate.queryForPage(queryBuilder.build(), Object.class, indexName);
Aggregations aggregations = page.getAggregations();
Terms termsAggregation = aggregations.get(field);
// 处理聚合结果
// ...
return termsAggregation;
}
}
在这个例子中,performStatsAggregation
方法接受索引名和需要聚合的字段名。使用NativeSearchQueryBuilder
构建查询并添加聚合。然后使用ElasticsearchRestTemplate
执行查询并获取聚合结果。
请根据你的具体需求调整索引名、字段名和对聚合结果的处理。
评论已关闭