我有一个产品结构,这些产品可以在不同的商店以不同的价格购买:
[{
"name": "SomeProduct",
"store_prices": [
{
"store": "FooStore1",
"price": 123.45
},
{
"store": "FooStore2",
"price": 345.67
}
]
},{
"name": "OtherProduct",
"store_prices": [
{
"store": "FooStore1",
"price": 456.78
},
{
"store": "FooStore2",
"price": 234.56
}
]
}]
我想显示以最低价格升序排列的产品列表,以这种方式限制在10个结果中:
这该怎么做?我尝试了https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-nested-aggregation.html中描述的嵌套聚合方法,但它仅返回所有产品的最低价格,而不返回每种产品的最低价格:
{
"_source": [
"name",
"store_prices.price"
],
"query": {
"match_all": {}
},
"sort": {
"store_prices.price": "asc"
},
"aggs": {
"stores": {
"nested": {
"path": "store_prices"
},
"aggs": {
"min_price": {"min": {"field": "store_prices.price"}}
}
}
},
"from": 0,
"size": 10
}
在SQL中,可以使用以下查询描述我要执行的操作。恐怕我在“sql中”考虑的太多了:
SELECT
p.name,
MIN(s.price) AS price
FROM
products p
INNER JOIN
store_prices s ON s.product_id = p.id
GROUP BY
p.id
ORDER BY
price ASC
LIMIT 10
最佳答案
您需要一个nested sorting:
{
"query": // HERE YOUR QUERY,
"sort": {
"store_prices.price": {
"order" : "asc",
"nested_path" : "store_prices",
"nested_filter": {
// HERE THE FILTERS WHICH ARE EVENTUALLY
// FILTERING OUT SOME OF YOUR STORES
}
}
}
}
请注意,您必须在嵌套过滤器字段内重复最终的嵌套查询。然后,您可以在响应的
score
字段中找到价格。
关于sorting - Elasticsearch分组和按嵌套字段最小值的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46040088/