Neo4j:匹配

时间:2017-09-05 10:26:48

标签: neo4j cypher

我有Cypher查询:

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 个答案:

答案 0 :(得分: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