Search code examples
neo4jcypher

Neo4J finding two nodes such that the shortest path between them is of length n


I would like to know if there is a way to find two nodes such that the shortest path between them is of a specific length, say, 10.

All my nodes have the same label; "n1", and the shortest path can be through any edge type.

So far i have been doing this manually, by finding the shortest path between node n and node m, and constantly changing n and m and stop when i find a path of length 10.

Here is the Cypher query:

match sp = shortestpath((startNode)-[*]->(endNode)) where id(startNode) = 1 and id(endNode) = 2 return sp

Note, i do not specify the node label since i only have one label in the graph.

So i just continuously change the start and end nodes and run it until i find a path of the desired length.

I'm sure there is an easier way to do this, but since i am a Neo beginner i am struggling to figure it out.

I have also tried this:

MATCH (n1), (n2)
WHERE n1 <> n2 and shortestPath((n1)-[*]-(n2)) = 5
RETURN n1, n2
LIMIT 2

However, i don't believe this is correct because shortest paths of length 5 is very common in my graph, and it is taking a long time to execute...


Solution

  • This has worked for me!

    MATCH (n1), (n2)
    WHERE n1 <> n2 and length(shortestPath((n1)-[*]->(n2))) = 10
    RETURN n1, n2
    LIMIT 1