eLasticsearch中的过滤器嵌套排序



我有一个带有嵌套结构的文档,嵌套对象具有 assignment_namedue_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. 过滤所有具有特定sigsments_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。然后,您必须使用嵌套排序来基于嵌套的文档字段对文档进行排序。

查询将是:

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

上面的捕获是使用与主查询中使用的相同过滤器来过滤文档。这样可以确保将正确的嵌套文档的字段值视为对文档进行排序。

最新更新