Search code examples
cypherredisgraph

Cypher query to recursively traverse family tree?


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:

enter image description here

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

enter image description here

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

enter image description here

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?


Solution

  • 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):

    1. Get all nodes connected at any distance
    2. to my target node.
    3. Optionally look for relationships on each of those
    4. and return the node's id, name, and a collection of relationships and a collection of those relationship targets

    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.

    enter image description here