0
votes

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?

NOTE: you can find the same problem without the variable length over here

1
Hi! Could you please revise your question to include more specific examples of your Neo4j data model? What are you trying to do and what is your problem? For instance, I do not know what a wishlist is in this context. - Kenny Bastani

1 Answers

4
votes

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. You can obv. set that to whatever you like, including "1..", infinite depth.

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. Adding the sum will then aggregate the result by subcomponent (inferred from your RETURN clause) and sum up the total count for that subcomponent.

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/