Use allShortestPaths on directed graphs

Hey, I'm using neo4j-desktop version 4.2.6 from Java.

I've been using the allShortestPaths (not the algo one) in my graph. The graph has 1 node type and 1 relationship type where all relationships have the same weight.
This is my query:

MATCH (article:Article) where article.title IN [\"%1$s\",\"%2$s\"]\n" +
            "WITH collect(article) as nodes\n" +
            "UNWIND nodes as n\n" +
            "UNWIND nodes as m\n" +
            "WITH * WHERE id(n) < id(m)\n" +
            "MATCH path = allShortestPaths((n)-[*..6]-(m))\n" +
            "RETURN path";

My problem is that I want the search to be directional. I only need to search between 2 nodes and want to set a start and end node, such that all relationships are in the same direction (from start to end)
For example:

  • N-> b <- c -> M shouldn't count
  • N <- b <- c <- M shouldn't count
  • N -> b -> c -> M should count

I was wondering how could I do this.
Thanks in advance!


You can add direction to the pattern you're matching for allShortestPaths. Try this:

MATCH path = allShortestPaths((n)-[*..6]->(m))

That will only evaluate directed paths moving outbound from (n) to (m). I tested it with an example graph on my Neo4j Desktop instance using Neo4j 4.2.6 and it worked as expected. Let me know how you get on!

All the best,


1 Like

Hey, this didn't work for me.

I have a relationship that looks like N -> M.
I tried the command once and it showed the path, and then switched N and M in the command and it showed the same result, when it shouldn't have.

I think this is happening because the command doesn't have a "start" and "end" node, but rather it just takes a list.

Odd. Could you show me the queries and the data they return please?

I don't think that will be much help because they're not in english. I will say that doing the same query and replacing between the 2 inputs changes nothing. I think you misunderstood my issue, so I'll try and explain again.

Looking back at my original examples:

  • N-> b <- c -> M shouldn't count
  • N <- b <- c <- M shouldn't count
  • N -> b -> c -> M should count

Your solution did help with eliminating the 1st example, because now all relationships have to be in the same direction, however, the 2nd example is still a problem, because the command can't differentiate between start and end.

I think I may need to change a lot of the command in order for this to work, but I don't know how to because I'm not proficient with Cypher. Do you have any idea how to make the command only show results in 1 direction?

Thanks in advance!