我正在尝试通过嵌套字段sections.name
对ElasticSearch返回的结果进行如下排序:
映射:
PUT /staff
{
"mappings": {
"list": {
"properties": {
"id": {"type": "text" },
"name": {
"type":"text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"sections" : {
"type":"nested",
"properties": {
"id": {"type":"text", "fielddata" : true},
"name": {
"fielddata" : true,
"type": "text",
"fields": {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
}
}
}
}
文档:
POST /staff/list
{
"id": 10,
"name": "abc def",
"sections":
[
{
"id":"1",
"name" : "zamphire"
},{
"id":"2",
"name" : "warden"
}
]
}
POST /staff/list
{
"id": 9,
"name": "abc def",
"sections":
[
{
"id":"1",
"name" : "shaggi"
},{
"id":"2",
"name" : "robert"
}
]
}
POST /staff/list
{
"id": 8,
"name": "abc def",
"sections":
[
{
"id":"3",
"name" : "zamphire"
},{
"id":"2",
"name" : "abi"
}
]
}
我正在执行以下查询:
GET /staff/_search
{
"from": 0,
"query": {
"nested": {
"path": "sections",
"query": {
"match": {
"sections.id": {
"query": "1"
}
}
}
}
},
"size": 25,
"sort": [
{
"sections.name": {
"nested": {
"filter": {
"nested": {
"path": "sections",
"query": {
"term" : { "sections.id" : "1" }
}
}
}
},
"order": "asc"
}
}
],
"_source": {
"includes": [
"id",
"name",
"sections"
]
}
}
我得到这些结果:
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 2,
"max_score" : null,
"hits" : [
{
"_index" : "staff",
"_type" : "list",
"_id" : "rJtyyGwBNB-cdBRb5XGR",
"_score" : null,
"_source" : {
"name" : "abc def",
"id" : 10,
"sections" : [
{
"name" : "zamphire",
"id" : "1"
},
{
"name" : "warden",
"id" : "2"
}
]
},
"sort" : [
null
]
},
{
"_index" : "staff",
"_type" : "list",
"_id" : "rZtyyGwBNB-cdBRb6nHU",
"_score" : null,
"_source" : {
"name" : "abc def",
"id" : 9,
"sections" : [
{
"name" : "shaggi",
"id" : "1"
},
{
"name" : "robert",
"id" : "2"
}
]
},
"sort" : [
null
]
}
]
}
}
我希望shaggi
节位于zamphire
之前,因此两个文档的顺序应该颠倒。
我在结果中注意到了这一点
"sort" : [
null
]
这有关系吗?我在这里想念什么?
答案 0 :(得分:1)
将sort
部分更改为docs
"sort": [
{
"sections.name": {
"order": "asc",
"nested": {
"path": "sections",
"filter": {
"term" : { "sections.id" : "1" }
}
}
}
}
]
返回
{
"took" : 7,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "staff",
"_type" : "_doc",
"_id" : "8hSJyWwBHfpsFyAs9f_8",
"_score" : null,
"_source" : {
"name" : "abc def",
"id" : 9,
"sections" : [
{
"name" : "shaggi",
"id" : "1"
},
{
"name" : "robert",
"id" : "2"
}
]
},
"sort" : [
"shaggi"
]
},
{
"_index" : "staff",
"_type" : "_doc",
"_id" : "8RSJyWwBHfpsFyAs5v98",
"_score" : null,
"_source" : {
"name" : "abc def",
"id" : 10,
"sections" : [
{
"name" : "zamphire",
"id" : "1"
},
{
"name" : "warden",
"id" : "2"
}
]
},
"sort" : [
"zamphire"
]
}
]
}
}
已通过Elasticsearch 7.2.0测试。
希望有帮助。