这两天项目中需要从es中查询数据,根据某个字段进行分组,求其最大、最小、平均值,并按最大值进行排序。
springboot的版本号:2.0.6.RELEASE
Elasticsearch的版本号:5.6.3
主要代码记录下:
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
.filter(QueryBuilders.termsQuery("a", aList))
.filter(QueryBuilders.termsQuery("b", bList))
.filter(QueryBuilders.rangeQuery("cTime")
.from(startTime)
.to(endTime));
AggregationBuilder termsBuilder = AggregationBuilders.terms("fieldTerms").field("myField").size(99999).order(Terms.Order.aggregation("max_f", false));
MaxAggregationBuilder maxAggf = AggregationBuilders.max("max_f").field("prod.f");
MinAggregationBuilder minAggf = AggregationBuilders.min("min_f").field("prod.f");
AvgAggregationBuilder avgAggf = AggregationBuilders.avg("avg_f").field("prod.f");
termsBuilder.subAggregation(maxAggf);
termsBuilder.subAggregation(minAggf);
termsBuilder.subAggregation(avgAggf);
termsBuilder.subAggregation(maxAggMem);
termsBuilder.subAggregation(minAggMem);
termsBuilder.subAggregation(avgAggMem);
TransportClient transportClient = ESConnectionManagement.getInstance();
SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch("indexName_*")
.setTypes("type1", "type2")
.setScroll(TimeValue.timeValueMinutes(1))
.setQuery(queryBuilder)
.addAggregation(aggregationBuilder)
.setSize(0); // 只获取聚合结果,不显示hits数据
SearchResponse scrollResponse = searchRequestBuilder.execute().actionGet();
Map<String, Aggregation> map = scrollResponse.getAggregations().asMap();
StringTerms stringTerms = (StringTerms)map.get("fieldTerms");
List<StringTerms.Bucket> buckets = stringTerms.getBuckets();
for (StringTerms.Bucket bucket : buckets) {
String myField = bucket.getKeyAsString();
Map<String, Aggregation> aggMap = bucket.getAggregations().asMap();
// 获取的最大、最小、平均值
InternalMax maxf = (InternalMax)aggMap.get("max_f");
String maxfValue = BigDecimal.valueOf(maxf.getValue())
.setScale(2, BigDecimal.ROUND_HALF_UP)
.toString();
InternalMin minf = (InternalMin)aggMap.get("min_f");
String minfValue = BigDecimal.valueOf(minf.getValue())
.setScale(2, BigDecimal.ROUND_HALF_UP)
.toString();
InternalAvg avgf = (InternalAvg)aggMap.get("avg_f");
String avgfValue = BigDecimal.valueOf(avgf.getValue())
.setScale(2, BigDecimal.ROUND_HALF_UP)
.toString();
...
}
其中
1、termsBuilder.subAggregation(maxAggf);
表示往分组聚合对象里追加聚合函数,可以追加多个聚合函数。
2、AggregationBuilders.terms("fieldTerms").field("myField").size(99999).order(Terms.Order.aggregation("max_f", false));
表示将字段myField进行分组,并按聚合字段max_f倒序排列,设置最多返回99999条结果,若不写则默认返回10条结果,需要注意。
3、InternalMax maxf = (InternalMax)aggMap.get("max_f");文章来源:https://www.toymoban.com/news/detail-596197.html
表示最大值的聚合对象获取到的值类型,会有对应的InternalMax对象来接收,最小值对象为InternalMin,平均值对象为InternalAvg。文章来源地址https://www.toymoban.com/news/detail-596197.html
到了这里,关于Springboot操作Elasticsearch——聚合分组与排序的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!