主要知识点:
- 自定义排序
es默认是按照每个bucket的doc_count降序来排的,如果不指定就是这样排序。
但是假如说,我们现在统计出来每个颜色的电视的销售额,需要按照销售额降序排序,这样就需要自定义排序规则了。
语法:
GET /tvs/sales/_search
{
"size": 0,
"aggs": {"group_by_color": {
"terms": {"field": "color"},
"aggs": {"color_avg_price": {"avg": {"field": "price"}}}
}
}
}
这样就是以color_avg_price进行降序排列(默认进行降序排列),如果是用默认的排序方式,可以不写Order
执行结果如下:
"aggregations": {
"group_by_color": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "红色",
"doc_count": 4,
"color_avg_price": {
"value": 3250
}
},
{
"key": "绿色",
"doc_count": 2,
"color_avg_price": {
"value": 2100
}
},
以升序排列
GET /tvs/sales/_search
{
"size": 0,
"aggs": {"group_by_color": {
"terms": {"field": "color","order": {"color_avg_price": "desc"}},
"aggs": {"color_avg_price": {"avg": {"field": "price"}}}
}
}
}