聚合的两种排序方式

   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")
)

posted on 2022-06-10 16:58  肖建锋  阅读(642)  评论(0编辑  收藏  举报