查找字段不存在或字段小于值的文档

Find documents with field that doesn't exist or field is less than value

我有一些员工,我试图找到那些没有输入生日或生日早于 1963-03-01 的人。我有:

GET employees/_search
{
  "query": {
    "bool": {
      "must_not": {
        "exists": {
          "field": "birthday"
        }
      },
      "filter": {
        "range": {"birthday": {"lte": 19630301}}
      }
    }
  }
}

现在我有 250 名员工,其中 none 个有生日字段,但此查询 returns 0 个结果。

您可以为此尝试使用出现 should 的 bool 查询。

第一个子句可以检查没有生日字段的文档,而第二个子句可以根据给定的范围过滤文档。

should 查询的使用将充当逻辑 OR 运算符并检索两者之一。

{
  "query": {
    "bool": {
      "should": [
        {
           "bool": { 
              "must_not": [{ "exists": { "field": "birthday" } }]
           }
        },
        {
           "bool": {
              "filter": [{ "range": {"birthday": { "lte": 19630301 }} }]
           }
        }
      ]
    }
  }
}

由于不计算过滤器的分数,您可能希望所有分数彼此保持一致。你可以选择使用 Constant Score Query 或者你可以在生日过滤子句上添加一个额外的查询来反转第一个子句中的 must_not 像这样:

{
  "query": {
    "bool": {
      "should": [
        {
           "bool": { 
              "must_not": [{ "exists": { "field": "birthday" } }]
           }
        },
        {
           "bool": {
              "must": [{ "exists": { "field": "birthday" } }],
              "filter": [{ "range": {"birthday": { "lte": 19630301 }} }]
           }
        }
      ]
    }
  }
}