java ElasticSearch es 聚合排序等

序言:

近来一直在javaAPI对ES数据进行统计分析, 中间也遇到不少问题, 本篇文章只针对聚合过程中的排序方法进行总结

例如:selectavg(age) as avg_age from table group by gender;

聚合的两种排序方式

1. 按组内字段排序: 分组后按组内数据某个字段进行排序

2. 按聚合后指标排序: 分组聚合后按照聚合后的某个新指标字段进行排序

案例:

1. 按组内字段排序

AggregationBuilder aggregation =
AggregationBuilders
.terms(“agg”).field(“gender”)
.subAggregation(
AggregationBuilders.topHits(“top”)
.explain(true)
.size(1)
.from(10)
.sort(“sortFiled”, SortOrder.ASC)
);
输出

import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.tophits.TopHits;

// sr is here your SearchResponse object
Terms agg = sr.getAggregations().get(“agg”);

// For each entry
for (Terms.Bucket entry : agg.getBuckets()) {
String key = entry.getKey(); // bucket key
long docCount = entry.getDocCount(); // Doc count
logger.info(“key [{}], doc_count [{}]”, key, docCount);

// We ask for top_hits for each bucket
TopHits topHits = entry.getAggregations().get(“top”);
for (SearchHit hit : topHits.getHits().getHits()) {
logger.info(" -> id [{}], _source [{}]", hit.getId(), hit.getSourceAsString());
}
}
2.按聚合后指标排序

import org.elasticsearch.search.aggregations.BucketOrder;
doc_count以递增的方式

AggregationBuilders
.terms(“genders”)
.field(“gender”)
.order(BucketOrder.count(true))
按升序方式按字母顺序按顺序排序

AggregationBuilders
.terms(“genders”)
.field(“gender”)
.order(BucketOrder.key(true))
按聚合名称标识对桶进行排序

AggregationBuilders
.terms(“genders”)
.field(“gender”)
.order(BucketOrder.aggregation(“avg_height”, false))
.subAggregation(
AggregationBuilders.avg(“avg_height”).field(“height”)
)
按多个聚合指标对桶进行排序

AggregationBuilders
.terms(“genders”)
.field(“gender”)
.order(BucketOrder.compound( // in order of priority:
BucketOrder.aggregation(“avg_height”, false), // sort by sub-aggregation first
BucketOrder.count(true))) // then bucket count as a tie-breaker
.subAggregation(
AggregationBuilders.avg(“avg_height”).field(“height”)
)
参考:https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/_bucket_aggregations.html
---------------------
作者:tiansheng1225
来源:CSDN
原文:https://blog.csdn.net/tiansheng1225/article/details/82661577
版权声明:本文为博主原创文章,转载请附上博文链接!

你可能感兴趣的:(java,elasticsearch,java,搜索引擎,大数据,运维)