0
votes

I'm trying to get the all the intermediate nodes between two nodes in a graph using Neo4j CYPHER.

Sample

A sample result would be.

  1. Path between 1 and 4 should return 1, 2, 3 and 4.
  2. Path between 1 and 3 should return 1, 2 and 3.
  3. Path between 4 and 6 should return 4, 5 and 6.
  4. Path between 1 and 6 should return 1, 2, 3, 4, 5 and 6.

The path between 1,2,3 and 4 has the combined distance as to 1 and 4 directly. 4 to 6 would have the same distance as 4,5,6.

Alternatively, a cypher query to remove the shortcuts if a longer route is available.

I've tried a standard path finding command but that returns 1 and 4 each time.:

MATCH path = shortestpath((s:Node{ Id: 1})-[Link*]->(e:Node {Id: 4}))
RETURN path LIMIT 1

public class Node {

    public long Id {get;set;}    

}

public class Link {

}

Thank you.

2
Since the path from 4 to 5 (if we follow the directionality of the relationships) does not include 6, why do you say that the path "between 4 and 5 should return 4, 5 and 6"? Also, can you explain what exactly "mandatory" means in your model? - cybersam
Sorry that was meant to be a 6. Mandatory means that it needs to be specified at the full path. For example one person may plot a path 1,2,3,4,6 or 1,4,6 or 1,4,5,6 as some people are lazy. I am running a loop with i and i + 1 to find any intermediate nodes they've missed out. - Liam
One way to look it is that a train may stop at 1, 4 and 6 but I want to know what stations it passes between 1 and 4 and 4 and 6. Another train may stop at 1,3,4 and 5 so I want to know if there's any stops in between 1 and 3, 3 and 4 and 4 and 6 - Liam
I've updated the question to make it easier. - Liam

2 Answers

0
votes

Well, you are specifically asking in your query to find the shortest path. If your graph image is correct, the shortest path between 1 and 4 is a direct link.

So you should get rid of it and try:

MATCH path = (s:Node{ Id: 1})-[Link*]->(e:Node {Id: 4})
RETURN path LIMIT 1
0
votes

This query will return the longest path between the 2 endpoints:

MATCH path = (:Node{Id: 1})-[:Link*]->(:Node {Id: 4})
RETURN path
ORDER BY LENGTH(path) DESC LIMIT 1;