【问题标题】:In ElasticSearch how to check if a field exists that it equals some value, or that the field doesn't exist?在 ElasticSearch 中,如何检查字段是否存在等于某个值,或者该字段不存在?
【发布时间】:2019-10-28 14:41:39
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: elasticsearch kibana


    【解决方案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
    } 
    

    should
    {
       must
       {
          A,
          B
       },
       C
    }
    

    在上面的查询中,只有range query 就足够了,不需要使用exists query 和范围来检查更新字段的存在。

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

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

    【讨论】:

    • 太棒了,你是美女。作为 ES 的初学者,它对我帮助很大。谢谢。
    猜你喜欢
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    相关资源
    最近更新 更多