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

Elasticsearch嵌套聚合查询:如何返回所有字段而非仅嵌套字段?

Elasticsearch嵌套聚合返回所有字段解决方法

当前你的聚合查询只返回嵌套字段categories,是因为top_hits是在嵌套文档上下文里执行的,只能获取到categories嵌套对象的内容。要拿到根文档的所有字段,需要先通过reverse_nested聚合切换回根文档层级,再获取数据。

修改后的聚合代码如下:

aggs: {
    categories: {
        nested: {
            path: "categories"
        },
        aggs: {
            category_name: {
                terms: {
                    field: "categories.categoryId.keyword",
                    min_doc_count: 1,
                    size: 500,
                    order: {
                        _count: "desc"
                    }
                },
                aggs: {
                    // 从嵌套上下文切回根文档
                    back_to_root: {
                        reverse_nested: {}
                    },
                    product: {
                        top_hits: {
                            size: 1,
                            _source: {
                                // 这里可以指定要返回的所有字段,或者直接去掉include返回全部
                                include: ["id", "assets", "categories", "title", "price"] // 替换成你需要的字段
                            }
                        }
                    }
                }
            }
        }
    }
}

关键说明:

  • reverse_nested:这个聚合的作用是从嵌套字段的上下文回到根文档的上下文,让后续的top_hits能访问到根文档的所有字段。
  • 如果需要返回根文档的全部字段,可以直接删除_source.include配置,或者设置_source: true。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:40:27