Victor Axelsson
Victor Axelsson

Reputation: 1466

Matching subtree recursively in Neo4j

I'm using Neo4j, and I consider myself quite a newbie, and I don't really understand how I can select a subtree of my graph. I've found solutions using the shortestPath and allShortestPaths but that's not really the same thing as selecting a whole subtree by variable and all its children.

What I want to do is e.g. match MATCH (n {name: "Sovrum"})-[r:CHILDOF]->(child) return n, child but that only gives me the directly related nodes. enter image description here

Instead I want to select the whole subtree. enter image description here

Is there any good way of doing this or am I missing some vital point in how stuff works?

Upvotes: 3

Views: 1114

Answers (1)

Michael Hunger
Michael Hunger

Reputation: 41676

It's quite easy with variable length paths, you start at the root and tell Cypher to match CHILD_OF all the way down until it doesn't go further.

Please make sure to use labels in your query to allow Neo4j (with an index) to find your starting point quickly.

You can also assign the pattern matched to a path and return that path

MATCH path = (n:Node {name: "Sovrum"})-[:CHILDOF*]->(child)
RETURN path

Upvotes: 3

Related Questions