Elasticsearch 按嵌套字段的最小值分组和排序
Elasticsearch group and order by nested field's min value
我有一个在不同商店以不同价格提供的产品结构:
[{
"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 个结果,这样:
- 一些产品:123.45 美元
- 其他产品:234.56 美元
如何做到这一点?我尝试了 https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-nested-aggregation.html 中描述的嵌套聚合方法,但它只是 returns 所有产品的最低价格,而不是每个产品各自的最低价格:
{
"_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 中,我想做的事情可以使用以下查询来描述。怕是我想多了"in 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
字段中找到价格。
我有一个在不同商店以不同价格提供的产品结构:
[{
"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 个结果,这样:
- 一些产品:123.45 美元
- 其他产品:234.56 美元
如何做到这一点?我尝试了 https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-nested-aggregation.html 中描述的嵌套聚合方法,但它只是 returns 所有产品的最低价格,而不是每个产品各自的最低价格:
{
"_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 中,我想做的事情可以使用以下查询来描述。怕是我想多了"in 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
字段中找到价格。