Roy
Roy

Reputation: 277

Recursive call in neo4j

I am trying to trace messages in a graph of messages. For example, node A sends message to node B which sends message to node C (and so on), how can I devise a query in Cypher that will keeping calling the next node until a terminal node is reached.

A -> B -> C -> D -> E -> F

start search is A, returns a list containing B,C,D,E,F (in the classic neo4j graph visualisation where these nodes are connected because B sent message to C and so on til F.

The code I have is

MATCH p=(a { address: "A" })-[r]->(b)
RETURN *

This only returns me A and the nodes A sent a message to. How can I modify it to accomplish the recursive call I am seeking.

Note: I have referred to this post and browsed the neo4j manual. However, I still don't get it (either could not find the answer or perhaps I am not 'getting it'). Any help is truly appreciated!

Upvotes: 0

Views: 841

Answers (1)

FrobberOfBits
FrobberOfBits

Reputation: 18002

This call:

MATCH p=(a { address: "A" })-[r*]->(b)
RETURN b;

will match as many hops away from A as you want, because of the asterisk on the relationship. The b variable will end up being everything that's downstream of a.

I'm not sure what you mean by "call the next node". This will just return the data behind that node. You don't actually need recursion to do this at all with cypher and neo4j. Rather, you should just ask cypher for what data you want, and it will get it for you. If you were implementing this stuff on a non-graph database, you might use recursion as part of a depth-first or breadth-first search, but it simply isn't necessary with a graph DB. The query language handles all of that for you.

Upvotes: 1

Related Questions