按照字段值排序
创建索引:
PUT student
{
"mappings" : {
"properties" : {
"name" : {
"type" : "keyword"
},
"age" : {
"type" : "integer"
}
}
}
}
使用 _bulk
创建文档
POST _bulk
{ "index" : { "_index" : "student", "_id" : "1" } }
{ "name" : "张三", "age": 12}
{ "index" : { "_index" : "student", "_id" : "2" } }
{ "name" : "李四", "age": 10 }
{ "index" : { "_index" : "student", "_id" : "3" } }
{ "name" : "王五", "age": 11 }
{ "index" : { "_index" : "student", "_id" : "4" } }
{ "name" : "陈六", "age": 11 }
age 降序:
GET student/_search
{
"query": {
"match_all": {}
}
,
"sort": [
{
"age": { "order": "desc"}
}
]
}
age降序,_id
升序:
GET student/_search
{
"query": {
"match_all": {}
}
,
"sort": [
{
"age": { "order": "desc"}
},
{
"_id": {"order" : "asc"}
}
]
}
_id
升序、age降序:
GET student/_search
{
"query": {
"match_all": {}
}
,
"sort": [
{
"_id": {"order" : "asc"}
},
{
"age": { "order": "desc"}
}
]
}
多字段值排序
如果某个字段是数组,也是可以排序的,不过需要指定 mode 。mode 支持 min
、max
、avg
、sum
。
# 删除之前建的 student
DELETE student
# 重建 student
PUT student
{
"mappings" : {
"properties" : {
"name" : {
"type" : "keyword"
},
"score" : {
"type" : "integer"
}
}
}
}
# 添加文档
POST _bulk
{ "index" : { "_index" : "student", "_id" : "1" } }
{ "name" : "张三", "score": [80, 90]}
{ "index" : { "_index" : "student", "_id" : "2" } }
{ "name" : "李四", "score": [78, 95] }
按照 score 的最小值排序:
# 请求
GET student/_search
{
"query": {
"match_all": {}
},
"sort": [
{
"score": {"order" : "asc", "mode": "min"}
}
]
}
# 响应
{
"took" : 16,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "student",
"_type" : "_doc",
"_id" : "2",
"_score" : null,
"_source" : {
"name" : "李四",
"score" : [
78,
95
]
},
"sort" : [
78
]
},
{
"_index" : "student",
"_type" : "_doc",
"_id" : "1",
"_score" : null,
"_source" : {
"name" : "张三",
"score" : [
80,
90
]
},
"sort" : [
80
]
}
]
}
}