Search code examples
neo4jcyphershortest-path

Shortest Path using Neo4j, with relationships of Start and End Node


I'm fairly new to Neo4j. I'm trying to get the shortest path for default movie database. However, along with it I also need the start and end node(of type Person) to display there first level relation to any other node and if any person node on the path have a relation to the start and end node via some other node. Its better to explain with below pictures.

Normal shortestpath will look, something like this. enter image description here

MATCH (p1:Person { name: 'Kevin Bacon' }),(p2:Person { name: 'Meg Ryan' }),
p = shortestPath((p1)-[*..15]-(p2))
return p

However my desired output is this one. enter image description here

I tried below cypher. However i cannot understand, how to do it. I'm getting below result, which is incorrect.

MATCH (p1:Person { name: 'Kevin Bacon' }),(p2:Person { name: 'Meg Ryan' }),
p = shortestPath((p1)-[*..15]-(p2))
MATCH (p1:Person)-[r]-(b)  // here i need foreach node on path for type person, get there relationships? However can't do that
return p,p1,r,b

enter image description here

Appreciate any help. Thanks.


Solution

  • You can get all the movies in the start and end nodes of shortest path. Then add the movies with the path.

    MATCH p = shortestPath((p1:Person { name: 'Kevin Bacon' })-[*..15]-(p2:Person { name: 'Meg Ryan' })) 
    WITH p1, p2, p
    MATCH (p1)-[:ACTED_IN]->(m1) 
    MATCH (p2)-[:ACTED_IN]->(m2) 
    RETURN p, m1, m2