user6521061
user6521061

Reputation:

get a list of the shortest path from one node to another on neo4j?

I need to find the short way between two nodes, getting a list of all the relations (with the properties) of the path.

If I have something like this:

MERGE (p1:Person{name: 'jim'})
MERGE (p2:Person{name: 'rob'})
MERGE (p3:Person{name: 'tom'})
MERGE (p4:Person{name: 'bob'})  

MERGE (p1)-[:FRIEND{age: '20'}]->(p2)
MERGE (p2)-[:NO_FRIEND{age: '35'}]->(p3)
MERGE (p3)-[:FRIEND{age: '20'}]->(p4)
MERGE (p2)-[:FOO{age: '40'}]->(p4)

Assuming that I need to go from p1 to p4, the resulting list should be a list with: FRIEND{age: '20'} and FOO{age: '40'}

If I need to go from p1 to p3, the result should be FRIEND{age: '20'} and NO_FRIEND{age: '35'}

So I have this two requirements, the short way, and the list with relationships. How can I do it?

Upvotes: 0

Views: 423

Answers (1)

cybersam
cybersam

Reputation: 66957

It sounds like you just need to use the shortestPath function and return the resulting path (which will give you the nodes and relationships along the path, along with their properties). For example, to get the shortest path from your p1 to p4 nodes:

MATCH path=shortestPath((p1:Person {name: 'jim'})-[*]-(p4:Person {name: 'bob'}))
RETURN path;

You can use allShortestPaths function if you want to find all paths that have the same shortest path length.

Upvotes: 1

Related Questions