简体   繁体   English

neo4j cypher:从查询结果“堆叠”节点

[英]neo4j cypher: “stacking” nodes from query result

Considering the existence of three types of nodes in a db, connected by the schema 考虑数据库中通过模式连接的三种类型的节点的存在

(a)-[ra {qty}]->(b)-[rb {qty}]->(c)

with the user being able to have some of each in their wishlist or whatever. 用户可以在自己的愿望清单中包含其中的一些内容。

What would be the best way to query the database to return a list of all the nodes the user has on their wishlist, considering that when he has an (a) then in the result the associated (b) and (c) should also be returned after having multiplied some of their fields (say b.price and c.price ) for the respective ra.qty and rb.qty ? 考虑到当用户拥有(a)时,结果中关联的(b)(c)也应为:查询数据库以返回其愿望清单上所有节点的列表的最佳方法是什么?在将各自的ra.qtyrb.qty某些字段(例如b.pricec.price )相乘后返回?

NOTE: you can find the same problem without the variable length over here 注意:你可以找到同样的问题,而不需要通过可变长度这里

Assuming you have users connected to the things they want like so: 假设您有用户连接到他们想要的东西,如下所示:

(user:User)-[:WANTS]->(part:Part)

And that parts, like you describe, have dependencies on other parts in specific quantities: 就像您描述的那样,这些部分在特定数量上依赖于其他部分:

CREATE 
  (a:Part) -[:CONTAINS {qty:2}]->(b:Part),
  (a:Part) -[:CONTAINS {qty:3}]->(c:Part),
  (b:Part) -[:CONTAINS {qty:2}]->(c:Part)

Then you can find all parts, and how many of each, you need like so: 然后,您可以找到所有零件,以及每个零件需要多少个零件,如下所示:

MATCH 
    (user:User {name:"Steven"})-[:WANTS]->(part),
    chain=(part)-[:CONTAINS*1..4]->(subcomponent:Part) 
RETURN subcomponent, sum( reduce( total=1, r IN relationships(chain) | total * r.rty) )

The 1..4 term says to look between 1-4 sub-components down the tree. 1..4项表示要在树上的1-4个子组件之间看。 You can obv. 你可以看。 set that to whatever you like, including "1..", infinite depth. 将其设置为任意值,包括“ 1 ..”,无限深度。

The second term there is a bit complex. 第二项有点复杂。 It helps to try the query without the sum to see what it does. 它有助于尝试不加总和的查询,以查看其作用。 Without that, the reduce will do the multiplying of parts that you want for each "chain" of dependencies. 否则,reduce将使依赖的每个“链”的所需部分相乘。 Adding the sum will then aggregate the result by subcomponent (inferred from your RETURN clause) and sum up the total count for that subcomponent. 然后,将总和相加将按子组件汇总结果(从RETURN子句推断得出),并对该子组件的总计数求和。

Figuring out the price is then an excercise of multiplying the aggregate quantities of each part. 然后弄清楚价格就是将每个零件的总数量相乘的练习。 I'll leave that as an exercise for the reader ;) 我将其留给读者练习;)

You can try this out by running the queries in the online console at http://console.neo4j.org/ 您可以通过在http://console.neo4j.org/在线控制台中运行查询来进行尝试。

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

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