Elasticsearch 聚合查询(aggs),java后端面试常见问题
在Elasticsearch中,聚合查询(aggs)允许你对数据执行复杂的分析,比如值的计数、平均值、最大值、最小值等。以下是一个使用Java High Level REST Client执行聚合查询的例子:
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
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.elasticsearch.search.aggregations.metrics.max.Max;
import org.elasticsearch.search.aggregations.metrics.min.Min;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.builder.SearchSourceBuilder;
// 假设你已经有了一个RestHighLevelClient实例client
SearchRequest searchRequest = new SearchRequest("index_name"); // 替换为你的索引名
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery()); // 使用所有文档
// 添加聚合查询
searchSourceBuilder.aggregation(AggregationBuilders.terms("group_by_field").field("field_name")); // 分组字段
searchSourceBuilder.aggregation(AggregationBuilders.avg("avg_agg").field("field_name")); // 平均值
searchSourceBuilder.aggregation(AggregationBuilders.max("max_agg").field("field_name")); // 最大值
searchSourceBuilder.aggregation(AggregationBuilders.min("min_agg").field("field_name")); // 最小值
searchSourceBuilder.aggregation(AggregationBuilders.sum("sum_agg").field("field_name")); // 求和
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
Aggregations aggregations = searchResponse.getAggregations();
// 获取聚合结果
Terms groupByAgg = aggregations.get("group_by_field");
Avg avgAgg = aggregations.get("avg_agg");
Max maxAgg = aggregations.get("max_agg");
Min minAgg = aggregations.get("min_agg");
Sum sumAgg = aggregations.get("sum_agg");
// 处理聚合结果
// ...
这段代码演示了如何在Java中使用Elasticsearch High Level REST Client执行聚合查询。你需要替换index_name
为你的索引名,并且调整\`field_
评论已关闭