You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elasticsearch实现city_name或country_name为空的OR条件查询

匹配city_name或country_name为空记录的Elasticsearch查询语句

你当前的查询用must_not数组同时排除了存在city_name和country_name的记录,因此只会匹配两个字段都为空的条目。要实现任意一个字段为空的OR逻辑,有两种简洁的写法:

写法一:使用should+minimum_should_match

这种写法直接明确指定“满足任意一个字段为空的条件”:

POST index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "timestamp": {
              "gte": "2023-02-27 06:40:00"
            }
          }
        }
      ],
      "should": [
        {
          "must_not": {
            "exists": {
              "field": "city_name"
            }
          }
        },
        {
          "must_not": {
            "exists": {
              "field": "country_name"
            }
          }
        }
      ],
      "minimum_should_match": 1
    }
  },
  "size": 3,
  "sort": [{
            "timestamp": {
                "order": "asc"
            }
        }
    ]
}
  • should数组中的两个条件分别对应“city_name为空”和“country_name为空”
  • minimum_should_match: 1确保只要满足其中一个条件就会被匹配

写法二:使用逻辑等价的must_not嵌套

利用逻辑上¬A ∨ ¬B = ¬(A ∧ B)的等价关系,查询“不同时存在city_name和country_name”的记录:

POST index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "timestamp": {
              "gte": "2023-02-27 06:40:00"
            }
          }
        }
      ],
      "must_not": [
        {
          "bool": {
            "must": [
              {
                "exists": {
                  "field": "city_name"
                }
              },
              {
                "exists": {
                  "field": "country_name"
                }
              }
            ]
          }
        }
      ]
    }
  },
  "size": 3,
  "sort": [{
            "timestamp": {
                "order": "asc"
            }
        }
    ]
}

这种写法通过排除“两个字段都存在”的记录,间接得到“至少一个字段为空”的结果,逻辑和写法一完全一致。

内容的提问来源于stack exchange,提问作者Dui Samarasinghe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 12:51:35