使用es聚合時,有時還需要獲取query(或filter) 的結果。
比如統計各個地區編碼的營業額,得到了聚合的統計結果,還想知道query結果中對應的地區名稱,並根據營業額進行排序,
這時可以使用 top_hits。
top_hits屬性
top_hits有以下的屬性:
from - 從第幾個結果開始獲取。
size - 每個桶返回的query結果的數量。默認情況下,返回前三個匹配的結果。
sort - 根據字段進行排序。默認情況下,按主查詢的分數排序。
top_hits的DSL
格式如下:
{
"size" : 0,
"query" : { },
"aggregations" : {
"自己命名的聚合名稱" : {
"terms" : {
"field" : "聚合字段",
"size" : 10000,
"order" : {
"_term" : "asc"
}
},
"aggregations" : {
"hits" : {
"top_hits" : {
"sort": [
{
"排序字段": {
"order": "desc"
}
}
],
"from" : 0,
"size" : 5
}
},
"自己命名的聚合統計的名稱" : {
"sum" : {
"field" : "聚合統計字段"
}
}
}
}
}
}
示例如下:
{
"size" : 0,
"query" : { },
"aggregations" : {
"agg_area" : {
"terms" : {
"field" : "area",
"size" : 10000,
"order" : {
"_term" : "asc"
}
},
"aggregations" : {
"hits" : {
"top_hits" : {
"sort": [
{
"amount": {
"order": "desc"
}
}
],
"from" : 0,
"size" : 5
}
},
"area_sum" : {
"sum" : {
"field" : "amount"
}
}
}
}
}
}
top_hits的java代碼
如下所示:
public static String getTopHitsDSL() {
SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource();
AggregationBuilder areaCodeAgg = AggregationBuilders.terms("agg_area").field("area")
.order(Terms.Order.aggregation(TERM, true)).size(10000)
.subAggregation(AggregationBuilders.topHits(HITS).sort("amount").size(5))
.subAggregation(AggregationBuilders.sum("area_sum").field("amount"));
return searchSourceBuilder.query().aggregation(areaCodeAgg).size(0).toString();
}