简体   繁体   English

带有子图聚合的递归查询

[英]Recursive query with sub-graph aggregation

I am trying to use Neo4j to write a query that aggregates quantities along a particular sub-graph. 我正在尝试使用Neo4j编写一个查询,该查询沿特定的子图汇总数量。

We have two stores Store1 and Store2 one with supplier S1 the other with supplier S2 . 我们有两家商店Store1Store2其中一家与供应商S1 ,另一家与供应商S2 We move 100 units from Store1 into Store3 and 200 units from Store2 to Store3 . 我们将Store1 100个单位移动到Store3 ,并将Store3 200个单位Store2Store3

We then move 100 units from Store3 to Store4 . 然后,我们将100个单位从Store3移至Store4 So now Store4 has 100 units and approximately 33 originated from supplier S1 and 66 from supplier S2 . 所以,现在Store4具有100个单位和大约33源自供应商S1和66从供应商S2

在此处输入图片说明

I need the query to effectively return this information, Eg 我需要查询以有效返回此信息,例如

S1, 33 S1,33
S2, 66 S2、66

I have a recursive query to aggregate all the movements along each path 我有一个递归查询,以汇总沿每个路径的所有运动

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

Returns: 返回值:

| | store1.Supplier | store1.Supplier | reduction| 减少|
|-------------------- |-------------| | -------------------- | ------------- |
| | S1 | S1 | 200 | 200 |
| | S2 | S2 | 300 | 300 |
| | null | 空| 100 | 100 |

Desired: 期望的:

| | store1.Supplier | store1.Supplier | reduction| 减少|
|---------------------|-------------| | --------------------- | ------------- |
| | S1 | S1 | 33.33 | 33.33 |
| | S2 | S2 | 66.67 | 66.67 |

What about this one : 这个如何 :

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

Which returns : 哪个返回:

supplier    pct
Store1  33
Store2  67
Returned 2 rows in 151 ms

So the following is pretty ugly, but it works for the example you've given. 因此,以下内容很难看,但适用于您给出的示例。

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

I'm sure it can be improved. 我相信它可以改善。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM