Querying a graph database with Cypher, I'm trying to walk an indefinite distance up a tree from a starting node, and return each node with information about that node's relationships.
For example, take a family tree:
I'd like to start at "James" (node id 4), and get a response with rows for each node along with the edge data defining that node's relationships.
If I do something like:
MATCH (p:Person)<-[r:Related]-(p2:Person)
WHERE id(p)=4
RETURN p, r, p2
I get
To get rid of the duplicated data, I can collect some of the results like:
MATCH (p:Person)<-[r:Related]-(p2:Person)
WHERE id(p)=4
RETURN id(p), p, collect(r.relationship), collect(id(p2))
gives me
But I still only have the initial node. How do I expand this to include rows in this format (or something similar) for each node all the way up the tree, including the leaf nodes?
Ended up doing it by getting all connected to my target, then gathering relationship information with an optional match
:
match (p:Person)<-[*0..]-(p2)
where id(p)=0
optional match (p2)<-[r]-(p3)
return id(p2), p2.name, collect(r.relationship), collect(id(p3))
This query will (I think... still figuring this out):
This gives me a nice result with only one row per node, with all the info I need about that node and that nodes relationships to other nodes.