在elasticsearch中过滤嵌套排序

Filter nested sorting in elasticsearch

我有一个嵌套结构的文档,嵌套对象有一个 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
            }
          }
        }
      }
    }
  }
}

我想:

  1. 过滤所有具有特定 assignment_name 的文档(例如 user_a
  2. 按下一个 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。然后你必须使用 nested sorting 根据嵌套文档字段对文档进行排序。

查询将是:

{
  "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"
            }
          }
        }
      }
    }
  ]
}

上面的问题是在排序中使用与主查询中使用的过滤器相同的过滤器来过滤文档。这确保了正确的嵌套文档的字段值被认为是对文档进行排序。