Muhamed Shafi
Muhamed Shafi

Reputation: 43

Neo4j Cypher Recursively traverse until a specific node

I am trying to create a recursive query that will start from a specific node but wants to stop the recursion when it reaches to the specific node.

For example

  (node{Id:1})-[Parent]->(node{Id:2})
    (node{Id:2})-[Parent]->(node{Id:3})
    (node{Id:3})-[Parent]->(node{Id:4})
....
....
(node{Id:99})-[Parent]->(node{Id:100})

Now I want to traverse from node 3 to node 8.

I tried below query but it traverses from node 3 to the root node (ie node 100).

match  (c:node{Id:3})-[Parent*0..]->(p:node) retun p;

How can I put a condition here to stop the traversal when I reach to the node 8?

Upvotes: 0

Views: 1141

Answers (1)

Rajendra Kadam
Rajendra Kadam

Reputation: 4052

You can add Id parameter in Match clause to the second node(here p) as well.

MATCH path=(c:node{Id:3})-[Parent*0..]->(p:node{Id:8}) RETURN path;

You can also add depth in Relationship match like [Parent*0..N] If you know the exact or max value of N.

EDIT: Above query returns path from node 3 to 8. If you are looking for only nodes in the path from node 3 to 8, You can match the path and return nodes present on that path.

MATCH path=(c:node{Id:3})-[Parent*0..]->(p:node{Id:8}) RETURN nodes(path);

Upvotes: 2

Related Questions