我正在尝试使用Neo4j编写一个沿特定子图聚合数量的查询。
我们有两家商店Store1
和Store2
一家与供应商S1
,另一家与供应商S2
。我们将Store1
的100个单位移至Store3
,将Store2
的200个单位移至Store3
。
然后,我们将Store3
的100个单位移至Store4
。现在Store4
有100个单位,大约33个来自供应商S1
,66来自供应商S2
。
我需要查询才能有效地返回此信息,例如
S1,33
S2,66
我有一个递归查询来聚合每条路径上的所有移动
MATCH p=(store1:Store)-[m:MOVE_TO*]->(store2:Store { Name: 'Store4'})
RETURN store1.Supplier, reduce(amount = 0, n IN relationships(p) | amount + n.Quantity) AS reduction
返回:
| store1.Supplier |减少|
| -------------------- | ------------- |
| S1 | 200 |
| S2 | 300 |
| null | 100 |
所需
| store1.Supplier |减少|
| --------------------- | ------------- |
| S1 | 33.33 |
| S2 | 66.67 |
答案 0 :(得分:4)
这个怎么样:
MATCH (s:Store) WHERE s.name = 'Store4'
MATCH (s)<-[t:MOVE_TO]-()<-[r:MOVE_TO]-(supp)
WITH t.qty as total, collect(r) as movements
WITH total, movements, reduce(totalSupplier = 0, r IN movements | totalSupplier + r.qty) as supCount
UNWIND movements as movement
RETURN startNode(movement).name as supplier, round(100.0*movement.qty/supCount) as pct
返回:
supplier pct
Store1 33
Store2 67
Returned 2 rows in 151 ms
答案 1 :(得分:3)
所以以下内容非常难看,但它适用于您已经给出的示例。
MATCH (s4:Store { Name:'Store4' })<-[r1:MOVE_TO]-(s3:Store)<-[r2:MOVE_TO*]-(s:Store)
WITH s3, r1.Quantity as Factor, SUM(REDUCE(amount = 0, r IN r2 | amount + r.Quantity)) AS Total
MATCH (s3)<-[r1:MOVE_TO*]-(s:Store)
WITH s.Supplier as Supplier, REDUCE(amount = 0, r IN r1 | amount + r.Quantity) AS Quantity, Factor, Total
RETURN Supplier, Quantity, Total, toFloat(Quantity) / toFloat(Total) * Factor as Proportion
我确信它可以改进。