在 ElasticSearch 中如何检查一个字段是否存在它等于某个值,或者该字段不存在?

In ElasticSearch how to check if a field exists that it equals some value, or that the field doesn't exist?

我想在 elasticsearch 中找到所有文档,其中我的 "updated" 字段存在并且小于某个值或者文档中根本不存在该字段。我可以看到使用 bool 查询,并且 must 和 must not 可以使用但是我如何获得我试图用它们实现的确切场景?

谢谢!

假设 updateddate 类型的字段,查询将如下所示:

GET test/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "exists": {
                  "field": "updated"
                }
              },
              {
                "range": {
                  "updated": {
                    "lte": "2019-06-10"
                  }
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must_not": [
              {
                "exists": {
                  "field": "updated"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

以上解释:

让,

  • 字段 updated 应该存在 ===> A
  • 字段 updated 应小于 X ===> B
  • 字段 updated 根本不应该存在 ===> C

所需条件转换为(A AND B) OR C

(A AND B)D

现在在弹性方面变成:

should 
{
   D,
   C
} 

should
{
   must
   {
      A,
      B
   },
   C
}

在上面的查询中只有 range query is sufficient and there is no requirement to check for the existence of updated field using exists query 以及范围。

所以查询可以重写为 (B OR C):

GET test/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "range": {
            "updated": {
              "lte": "2019-06-10"
            }
          }
        },
        {
          "bool": {
            "must_not": [
              {
                "exists": {
                  "field": "updated"
                }
              }
            ]
          }
        }
      ]
    }
  }
}