[英]ElasticSearch aggregate nested fields as part of parent document
我有Product
实体和嵌套Variation
实体的索引。 Product
实体由Id
, Title
和嵌套变体组成。 Variation
实体由Color
, Size
和Price
字段组成。 我需要按Color
, Size
和Price
字段汇总搜索结果,以获得每种颜色,尺寸和价格组的产品数量。 如果我对这些字段使用嵌套聚合,我会得到正确的buckes,但桶中的文档数是每个桶的Variation
实体数。 但我需要获得每个桶的Product
实体(根文档)的数量。
例如,第一个产品有变化(红色,小,10美元),(绿色,小,10美元),(红色,中等,11美元),第二个产品有变化(绿色,中等,15美元)。 嵌套聚合返回2表示red
,2表示small
因为2个变体具有red
和small
尺寸。 但是我需要每个桶的产品数量(根实体), red
应为1, small
应为1。
由于其他要求,我也不能使用子文档而不是嵌套文档。
如何撰写查询以获得此结果?
这是映射:
{
"product": {
"properties": {
"id": {
"type": "long"
},
"title": {
"type": "string"
},
"brand": {
"type": "string"
},
"variations": {
"type": "nested",
"properties": {
"id": {
"type": "long"
},
"colour": {
"type": "string"
},
"size": {
"type": "string"
},
"price": {
"type": "double"
}
}
},
"location": {
"type": "geo_point"
}
}
}
}
这是一个查询
{
"aggs": {
"Variations": {
"nested": {
"path": "variations"
},
"aggs": {
"Colous": {
"terms": {
"field": "variations.colour"
}
},
"Sizes": {
"terms": {
"field": "variations.size"
}
}
}
},
"Brands": {
"terms": {
"field": "brand"
}
}
},
"query": {
"match_all": {}
}
}
Brand
聚合效果很好,因为它获得每组的根文档数,但嵌套聚合返回嵌套文档的数量而不是根文档的数量。
你以正确的方式解决了这个问题。 现在,您只需使用reverse_nested
聚合即可“加入”根产品,并为每个产品获取匹配产品的数量。
{
"aggs": {
"Variations": {
"nested": {
"path": "variations"
},
"aggs": {
"Colous": {
"terms": {
"field": "variations.colour"
},
"aggs": {
"product_count": { <--- add this reverse nested agg
"reverse_nested": {}
}
}
},
"Sizes": {
"terms": {
"field": "variations.size"
},
"aggs": {
"product_count": { <--- add this reverse nested agg
"reverse_nested": {}
}
}
}
}
},
"Brands": {
"terms": {
"field": "brand"
}
}
},
"query": {
"match_all": {}
}
}
在回复中,您将看到:
colour: green
colour: red
size: medium
size: small
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.