2017-09-05 68 views
1

我有Cypher支架查詢:的Neo4j:複製在比賽

match(p:Product)--(stock:Stock) 
where p.StyleNumber = "Z94882A" and p.Color = "Black" and stock.Retailer = "11" 
with stock as stock, p as p 
optional match(p)-->(s:Sale) 
where s.Date = 20170801 and s.Retailer = "11" 
return p,stock, s 

在比賽中我得到重複的股票返回結果:

Duplicate in Size XL

結果包含兩個項的尺寸:XL (見圖),因爲它有兩個銷售。但在第一個查詢中,match(p:Product)--(stock:Stock)僅返回一個產品節點,且僅附加一個庫存節點: - /。 看到這個圖來加以說明:

Graph for Size XL

如果我總結的銷售和股票,我仍然得到重複的結果:

match(p:Product)--(stock:Stock) 
where p.StyleNumber = "Z94882A" and p.Color = "Black" and stock.Retailer = "11" 
with stock as stock, p as p 
optional match(p)-->(s:Sale) 
where s.Date = 20170801 and s.Retailer = "11" 
return p, sum(stock.Stockcount) as onstock, sum(s.Quantity) as sold 

爲XL其中給出:

{"Size":"XL", "Color":"Black", "Supplier":"1", "Id":"6322", "StyleNumber":"Z94882A"} 
| Stock =10 (should have been 5)  │ Sold =2 (is correct) 

問題是如何避免在這種情況下重複?

回答

1

您需要分階段進行彙總,因爲:Stock節點獨立於Sale節點。儘早聚集,避免在它們之間創建笛卡爾產品。

match(p:Product)--(stock:Stock) 
where p.StyleNumber = "Z94882A" and p.Color = "Black" and stock.Retailer = "11" 
with sum(stock.Stockcount) as onstock, p 
optional match(p)-->(s:Sale) 
where s.Date = 20170801 and s.Retailer = "11" 
return p, onstock, sum(s.Quantity) as sold