我有一个带有嵌套结构的文档,嵌套对象具有 assignment_name
和 due_date
:
映射
{
"goal": {
"mappings": {
"doc": {
"properties": {
"title": {
"type": "keyword"
},
// lot's of other fields here ...
"steps": {
"type": "nested",
"properties": {
"assignment_name": {
"type": "keyword"
},
"due_date": {
"type": "date"
}
// lots of other fields here
}
}
}
}
}
}
}
我想:
- 过滤所有具有特定sigsments_name(例如
user_a
(的文档 - 按下下一个Due_date对结果进行排序,不考虑其他分配。
此查询给我随机结果(没有排序(:
{
"query":{
"bool":{
"filter":[
{
"nested":{
"path":"steps",
"query":{
"term":{
"steps.assignment_name":"user_a"
}
}
}
}
]
}
},
"sort":[
{
"steps.due_date":{
"order":"asc",
"nested":{
"path":"steps",
"filter":{
"term":{
"steps.assignment_name":"user_a"
}
}
}
}
}
],
"from":0,
"size":25
}
首先,您需要确保steps
字段的数据类型为nested
。然后,您必须使用嵌套排序来基于嵌套的文档字段对文档进行排序。
查询将是:
{
"query": {
"bool": {
"filter": [
{
"nested": {
"path": "steps",
"query": {
"term": {
"steps.assignment_name": "user_a"
}
}
}
}
]
}
},
"sort": [
{
"steps.due_date": {
"order": "asc",
"nested": {
"path": "steps",
"filter": {
"term": {
"steps.assignment_name": "user_a"
}
}
}
}
}
]
}
上面的捕获是使用与主查询中使用的相同过滤器来过滤文档。这样可以确保将正确的嵌套文档的字段值视为对文档进行排序。