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

Elasticsearch:基于嵌套数组属性的文档唯一计数聚合查询问题

问题:统计Nested类型中数组元素对应的根文档唯一数量

现有Elasticsearch索引,其mapping里details为nested类型,包含elts整数数组。需要通过聚合查询统计elts数组各元素对应的根文档唯一数量,但当前嵌套聚合返回的是嵌套文档计数,不符合预期。


索引Mapping

"mappings": {
      "properties": {
        "code": {
          "type": "keyword"
        },
        "details": {
          "type": "nested",
          "properties": {
            "name": {
              "type": "text",
              "analyzer": "html_stripper"
            },            
            "elts": {
              "type": "integer"
            }
          }
        }
      }
    },

示例文档

[
    {
        "code": "test",
        "details": [
            {"name": "test", "elts": [1,4]},
            {"name": "test", "elts": [1,4]}
        ]
    },
    {
        "code": "test2",
        "details": [
            {"name": "test2", "elts": [1,2,4]},
            {"name": "test2", "elts": [2,3]}
        ]
    }
]

尝试的查询语句

POST /my-index/_search

{
  "_source": false,  
  "aggs": {
    "inside_details": {
      "nested": {
        "path": "details"
      },
      "aggs": {
        "unique_count": {
          "terms": {
            "field": "details.elts",
            "order": {
              "_key": "asc"
            }
          }
        }
      }
    }
  }
}

错误结果

[
  {
    "key": "1",
    "doc_count": 3
  },
  {
    "key": "2",
    "doc_count": 2
  },
  {
    "key": "3",
    "doc_count": 1
  },
  {
    "key": "4",
    "doc_count": 3
  }
]

预期结果

[
  {
    "key": "1",
    "doc_count": 2
  },
  {
    "key": "2",
    "doc_count": 2
  },
  {
    "key": "3",
    "doc_count": 1
  },
  {
    "key": "4",
    "doc_count": 2
  }
]

修正后的查询方案

要统计根文档的唯一数量,需在嵌套聚合内部通过reverse_nested回到根文档层面,再对根文档的唯一标识做去重计数,最后按elts元素分组。

修正后的查询语句

POST /my-index/_search
{
  "_source": false,
  "aggs": {
    "inside_details": {
      "nested": {
        "path": "details"
      },
      "aggs": {
        "elts_terms": {
          "terms": {
            "field": "details.elts",
            "order": {
              "_key": "asc"
            }
          },
          "aggs": {
            "back_to_root": {
              "reverse_nested": {},
              "aggs": {
                "unique_root_docs": {
                  "cardinality": {
                    "field": "code"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

逻辑说明

  1. 进入details嵌套文档层,按elts元素做分组
  2. 对每个elts分组,通过reverse_nested回到根文档层面
  3. 用cardinality聚合统计该elts元素对应的唯一根文档数量(依赖code字段的唯一性)

返回结果中,每个elts分组下的unique_root_docs.value即为预期的根文档唯一计数。若根文档有更合适的唯一标识(如_id),可将cardinality的字段替换为_id,效果一致。


内容的提问来源于stack exchange,提问作者Aymard Moyo Kemgne

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 04:30:56