Elasticsearch如何动态统计不同properties.type对应的产品数量
Elasticsearch 动态统计嵌套字段取值对应数量方案
你可以使用Elasticsearch内置的terms聚合实现动态按字段值分组统计,不需要手动枚举每个type的取值。根据你统计的维度不同,有两种常见写法:
前提说明
请先确认你的索引中properties字段的映射类型:
- 如果是对象数组存储,建议设置为
nested类型避免数组扁平化导致统计结果错误 properties.type字段需要为keyword类型才可用于terms聚合,如果是text类型请使用对应的keyword子字段(例如properties.type.keyword)
场景1:统计每个type对应的嵌套条目总数(和你之前示例中dog:4、cat:2的结果一致)
如果properties为nested类型,聚合写法如下:
{ "size": 0, "aggs": { "all_properties": { "nested": { "path": "properties" }, "aggs": { "type_count": { "terms": { "field": "properties.type", "size": 1000 // 调整该参数可返回更多type取值,默认仅返回前10个 } } } } } }
如果properties为普通object类型,可简化为:
{ "size": 0, "aggs": { "type_count": { "terms": { "field": "properties.type", "size": 1000 } } } }
场景2:统计每个type对应的独立产品总数量
即同个产品下多个同type的嵌套条目只计数1次,需要额外加reverse_nested聚合回到顶层文档计数:
{ "size": 0, "aggs": { "all_properties": { "nested": { "path": "properties" }, "aggs": { "group_by_type": { "terms": { "field": "properties.type", "size": 1000 }, "aggs": { "product_total": { "reverse_nested": {} } } } } } } }
返回结果中每个type分组下的product_total.value就是该type对应的产品总数。
内容的提问来源于stack exchange,提问作者Rafael Franklin
相关产品推荐
相关产品推荐

