es分组求最大值保留2位小数 java代码
时间: 2023-10-13 22:28:39 浏览: 99
以下是使用Java实现的求ES分组最大值并保留2位小数的代码:
```java
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.max.Max;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class ESMaxAggregation {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(); // 创建ES客户端
SearchRequest searchRequest = new SearchRequest("your_index_name"); // 创建搜索请求
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 设置分组聚合
sourceBuilder.aggregation(AggregationBuilders.terms("group_by_field_name")
.field("field_name")
.subAggregation(AggregationBuilders.max("max_value").field("value_field_name")));
// 设置排序方式
sourceBuilder.sort("sort_field_name", SortOrder.DESC);
// 设置查询条件
sourceBuilder.query(QueryBuilders.matchAllQuery());
// 设置超时时间
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
// 设置返回数据条数,默认是10条
sourceBuilder.size(100);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
Terms terms = searchResponse.getAggregations().get("group_by_field_name");
for (Terms.Bucket bucket : terms.getBuckets()) {
Max max = bucket.getAggregations().get("max_value");
double maxValue = max.getValue();
System.out.println(bucket.getKeyAsString() + " 的最大值为:" + String.format("%.2f", maxValue));
}
client.close(); // 关闭ES客户端
}
}
```
其中,需要替换的参数有:
- `your_index_name`:替换为你要查询的ES索引名称。
- `group_by_field_name`:替换为你要分组的字段名称。
- `field_name`:替换为你要聚合的字段名称。
- `value_field_name`:替换为你要求最大值的字段名称。
- `sort_field_name`:替换为你要排序的字段名称。
注意:需要引入 Elasticsearch 的 Java API 依赖。
阅读全文