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

如何在Elasticsearch中按指定条件查询对应字段的最小值与最大值

Elasticsearch查询指定嵌套数组字段最值的实现方案

前提说明

  • 请先确认索引中priceBlock字段的mapping设置为nested类型,否则数组内的对象关联关系会被Elasticsearch自动扁平化,无法准确筛选同个对象下的两个字段匹配条件。如果当前是普通object类型,需要重建索引修改mapping为nested类型后重新导入数据,才能实现该需求。
  • 如果你的FilterTypeSelection字段为text类型,无keyword子字段,后续查询时需要将字段名改为priceBlock.CustomFilterDisplay.FilterTypeSelection,并将term查询替换为match查询。

查询DSL

{
  "size": 0,
  "query": {
    "nested": {
      "path": "priceBlock",
      "query": {
        "term": {
          "priceBlock.CustomFilterDisplay.FilterTypeSelection.keyword": "Size"
        }
      }
    }
  },
  "aggs": {
    "nested_price_block": {
      "nested": {
        "path": "priceBlock"
      },
      "aggs": {
        "filter_size_type": {
          "filter": {
            "term": {
              "priceBlock.CustomFilterDisplay.FilterTypeSelection.keyword": "Size"
            }
          },
          "aggs": {
            "min_size_value": {
              "min": {
                "field": "priceBlock.CustomFilterDisplay.FilterTypeValueText"
              }
            },
            "max_size_value": {
              "max": {
                "field": "priceBlock.CustomFilterDisplay.FilterTypeValueText"
              }
            }
          }
        }
      }
    }
  }
}

逻辑说明

  • size: 0:不需要返回匹配的原始文档,仅返回聚合结果,提升查询效率
  • 第一层nested query:先过滤出所有包含FilterTypeSelection=Size的文档,缩小聚合的计算范围
  • 嵌套聚合层的filter逻辑:在nested数组层级下再次筛选符合条件的对象,确保仅对FilterTypeSelection=Size的对象计算最值
  • 按照你提供的示例数据,返回的聚合结果中min_size_value取值为5,max_size_value取值为100

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 09:00:00