Ran*_*dom 5 aggregation elasticsearch
我有Product实体和嵌套Variation实体的索引.Product实体包括Id,Title和嵌套的变化.Variation实体组成的Color,Size和Price领域.我需要通过聚合搜索结果Color,Size和Price字段,以获取产品数量为每种颜色,尺寸和价格组.如果我对这些字段使用嵌套聚合,则会获得正确的buckes,但桶中的文档数是Variation每个桶的实体数.但我需要获得Product每个桶的实体数量(根文档).
例如,第一个产品有变化(红色,小,10美元),(绿色,小,10美元),(红色,中等,11美元),第二个产品有变化(绿色,中等,15美元).嵌套聚合返回2 for red和2,small因为2个变体具有red颜色和small大小.但是我需要每个桶的产品数量(根实体),应该是1 red和1 small.
由于其他要求,我也不能使用子文档而不是嵌套文档.
如何撰写查询以获得此结果?
这是映射:
{
"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"
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个查询
{
"aggs": {
"Variations": {
"nested": {
"path": "variations"
},
"aggs": {
"Colous": {
"terms": {
"field": "variations.colour"
}
},
"Sizes": {
"terms": {
"field": "variations.size"
}
}
}
},
"Brands": {
"terms": {
"field": "brand"
}
}
},
"query": {
"match_all": {}
}
}
Run Code Online (Sandbox Code Playgroud)
该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": {}
}
}
Run Code Online (Sandbox Code Playgroud)
在回复中,您将看到:
colour: greencolour: redsize: mediumsize: small| 归档时间: |
|
| 查看次数: |
2318 次 |
| 最近记录: |