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

Elasticsearch如何按aname:Color条件聚合查询对应avalue颜色值

实现步骤

1. 确认索引Mapping配置

你存储的是属性对象数组,要精准关联筛选aname和对应的avalue,必须将attributes_list.src1字段设置为nested嵌套类型,否则Elasticsearch会自动扁平化数组,导致属性名和属性值无法对应,筛选结果出错。
正确的Mapping示例参考:

{
  "mappings": {
    "properties": {
      "attributes_list": {
        "properties": {
          "src1": {
            "type": "nested",
            "properties": {
              "aname": {"type": "keyword"},
              "avalue": {"type": "keyword"}
            }
          }
        }
      }
    }
  }
}

注:如果aname、avalue需要支持模糊搜索,可以额外加text类型子字段,聚合必须用keyword类型保证准确性。如果现有索引不是该配置,需要重建索引重新导入数据才能生效。

2. 聚合查询DSL

直接使用嵌套聚合+过滤+分组的三层结构即可实现需求:

GET /你的索引名/_search
{
  "size": 0, // 不需要返回原始文档,只返回聚合结果
  "aggs": {
    "nested_src1": {
      "nested": {
        "path": "attributes_list.src1" // 定位到嵌套数组层级
      },
      "aggs": {
        "filter_color_attr": {
          "filter": {
            "term": {
              "attributes_list.src1.aname": "Color" // 仅筛选属性名为Color的条目
            }
          },
          "aggs": {
            "colors": {
              "terms": {
                "field": "attributes_list.src1.avalue", // 对筛选后的颜色值分组统计
                "size": 100 // 自定义返回的颜色数量上限,默认仅返回前10个
              }
            }
          }
        }
      }
    }
  }
}

3. 返回结果说明

返回的聚合结果结构和你预期的效果完全匹配,示例如下:

{
  "aggregations": {
    "nested_src1": {
      "filter_color_attr": {
        "colors": {
          "buckets": [
            {
              "key": "red",
              "doc_count": 10
            },
            {
              "key": "green",
              "doc_count": 5
            }
          ]
        }
      }
    }
  }
}

直接取aggregations.nested_src1.filter_color_attr.colors.buckets即可拿到各颜色对应的文档统计数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:36:10