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

Elasticsearch带OR/AND组合逻辑的nested query编写方法咨询

Elasticsearch 查询语句编写说明

首先明确字段类型场景,两种场景对应不同写法:

  • 若name和country为文档顶级非嵌套字段,无需使用nested query,直接用bool查询组合条件即可
  • 若name和country隶属于某个nested类型的对象字段,才需要使用nested query语法

场景1:顶级字段查询(无嵌套)

通过bool.should包裹两组bool.must条件,每组对应一组需要同时满足的配对规则:

GET /你的索引名/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              { "term": { "name": "John" } },
              { "term": { "country": "US" } }
            ]
          }
        },
        {
          "bool": {
            "must": [
              { "term": { "name": "Andy" } },
              { "term": { "country": "UK" } }
            ]
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}

注:如果你的name和country字段是text类型,需要把term查询替换为match查询。

场景2:字段属于nested类型对象(假设嵌套字段名为user)

如果你的文档实际结构如下(即name和country存放在nested类型的user字段下):

{
  "user": [
    {
      "name": "...",
      "country": "..."
    }
  ]
}

对应的nested query写法如下:

GET /你的索引名/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "nested": {
            "path": "user",
            "query": {
              "bool": {
                "must": [
                  { "term": { "user.name": "John" } },
                  { "term": { "user.country": "US" } }
                ]
              }
            }
          }
        },
        {
          "nested": {
            "path": "user",
            "query": {
              "bool": {
                "must": [
                  { "term": { "user.name": "Andy" } },
                  { "term": { "user.country": "UK" } }
                ]
              }
            }
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}

注:需要把语句中的user替换为你实际的嵌套字段路径,字段名和索引名也需要和实际业务配置保持一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:36:03