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

时间:2019-06-14 00:33:17

标签: elasticsearch kibana

我想在elasticsearch中找到所有文档,其中“我的已更新”字段存在且小于某个值,或者该字段在文档中根本不存在。我可以看到使用布尔查询,并且必须也必须不能使用它,但是如何获得要使用它们实现的确切方案呢?

谢谢!

1 个答案:

答案 0 :(得分:1)

假设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
} 

OR

should
{
   must
   {
      A,
      B
   },
   C
}

在上述查询中,仅range query就足够了,并且不需要使用exists query和范围来检查是否存在更新的字段。

因此查询可以重写为(B或C):

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