在ElasticSearch中,如何检查某个字段是否等于某个值,或者该字段不存在? [英] In ElasticSearch how to check if a field exists that it equals some value, or that the field doesn't exist?

查看:269
本文介绍了在ElasticSearch中,如何检查某个字段是否等于某个值,或者该字段不存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to find all documents in elasticsearch, where my "updated" field exists and is less that some value or where the field doesn't exist in the document at all. I can see that using a bool query, and must and must not can be utilized but how do I get the exact scenario I am trying to achieve with them?

谢谢!

推荐答案

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

Assuming updated is a date type of field the query would look as below:

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

以上说明:

让我们

  • 已更新字段应存在===> A
  • 已更新字段应小于 X ===> B
  • 已更新字段根本不存在===> C
  • Field updated should exists ===> A
  • Field updated should be less than X ===> B
  • Field updated should not exist at all ===> C

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

(A AND B) D

现在,就弹性而言,它变为:

Now in terms of elastic it becomes:

should 
{
   D,
   C
} 

OR

should
{
   must
   {
      A,
      B
   },
   C
}

仅在上述查询中 range查询就足够了,并且不需要使用

In the above query only range query is sufficient and there is no requirement to check for the existence of updated field using exists query along with the range.

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

So the query can be rewritten as (B OR C):

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

这篇关于在ElasticSearch中,如何检查某个字段是否等于某个值,或者该字段不存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆