2017-09-04 140 views
1

我已經得到了它們在不同的商店可提供不同價格的產品結構:Elasticsearch組和order by嵌套字段的最小值

[{ 
    "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個結果,以這樣的方式

  • SomeProduct:123.45美元
  • OtherProduct:234.56美元

如何做到這一點?我試着在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 
+0

您可以顯示迄今爲止嘗試過的查詢嗎? – Val

+0

@Val:在問題中更新;基本上,文檔中的示例查詢。 –

回答

1

你需要一個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字段中找到響應的價格。