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

如何编写Elasticsearch查询判断嵌套对象中expires字段存在情况

Elasticsearch 嵌套对象字段存在性查询

假设我们有存储冰箱信息的索引,示例文档结构如下:

{
  "_id": "whatever",
  "location": "North Building 1",
  "floor": 2,
  "tag": "refrigerator-1",
  "contents": [
    {
      "item": "milk-carton",
      "expires": "2023-01-01"
    },
    {
      "item": "pyrex-container"
    }
  ]
}

以下是对应需求的查询语句:

1. 查找至少有一件物品包含expires字段的冰箱

直接使用exists查询匹配存在目标字段的文档:

{
  "query": {
    "exists": {
      "field": "contents.expires"
    }
  }
}

2. 查找没有任何物品包含expires字段的冰箱

通过bool查询的must_not排除所有存在目标字段的文档:

{
  "query": {
    "bool": {
      "must_not": [
        {
          "exists": {
            "field": "contents.expires"
          }
        }
      ]
    }
  }
}

3. 查找所有物品都包含expires字段的冰箱

注意:此查询要求contents字段必须是nested类型(若未设置需先修改索引映射)。通过组合nested查询和bool逻辑实现:

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "contents",
            "query": {
              "exists": {
                "field": "contents.expires"
              }
            }
          }
        }
      ],
      "must_not": [
        {
          "nested": {
            "path": "contents",
            "query": {
              "bool": {
                "must_not": [
                  {
                    "exists": {
                      "field": "contents.expires"
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}

逻辑说明:

  • must部分确保文档至少有一个物品包含expires字段(过滤空数组或无符合条件的情况)
  • must_not部分排除任何存在物品不包含expires字段的文档
    两者结合即可得到所有物品都带有expires字段的冰箱文档。

内容的提问来源于stack exchange,提问作者Erik Philips

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:00:52