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

如何在ElasticSearch中统计列表字段元素数量的文档分布?

ElasticSearch DSL统计数组类型字段的元素数量分布

现有文档中,fieldtype是嵌套在Volume数组内的列表类型字段,需要统计该字段包含1个元素、2个元素的文档数量。

示例文档

// Document1
"Volume": [
  {
    "partition": "s1",
    "fieldtype": ["A","B"]
  }
]
// Document2
"Volume": [
  {
    "partition": "s1",
    "fieldtype": ["A"]
  }
]
// Document3
"Volume": [
  {
    "partition": "s1",
    "fieldtype": ["B"]
  }
]

需求

统计结果需显示:1个文档的fieldtype含2个元素,2个文档的fieldtype含1个元素。

尝试的查询及问题

使用以下聚合查询:

{
  "size": 0,
  "aggs": {
    "name": {
      "terms": {
        "field": "fieldtype.keyword"
      }
    }
  }
}

执行后得到的是单个元素(如A、B)的计数,且不使用keyword会直接报错。

解决方案

要统计数组元素的数量,需通过脚本计算每个文档中fieldtype数组的长度,再按长度分组聚合。具体DSL如下:

{
  "size": 0,
  "aggs": {
    "fieldtype_length_count": {
      "terms": {
        "script": {
          "source": "doc['fieldtype.keyword'].length"
        }
      }
    }
  }
}

说明

  • 脚本doc['fieldtype.keyword'].length会计算每个文档中fieldtype数组的元素个数
  • 聚合结果会按数组长度分组,直接得到不同长度对应的文档数量,其中key:1对应2个文档,key:2对应1个文档,完全匹配需求
  • 必须使用fieldtype.keyword是因为fieldtype默认是text类型,不支持直接获取数组长度,而keyword类型支持聚合操作,能正确读取数组的长度信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:45:34