Bobi Qnkov
Bobi Qnkov

Reputation: 29

Shortest path through a node

How to get the shtortest path between two nodes, where the path is going through a specific node. This is what I've got so far:

MATCH (a:User { username:"User1" }),(b:User { username:"User2" }),(c:User { username:"User3" }),
  p = allShortestPaths((a)-[*]-(b))
RETURN p 

I want a result in which the path goes through User3 (c).

Upvotes: 0

Views: 94

Answers (1)

cybersam
cybersam

Reputation: 66947

You can find each leg separately:

MATCH (a:User {username:"User1"}),(b:User {username:"User2"}),(c:User {username:"User3"}),
  p = allShortestPaths((a)-[*]-(c)), q = allShortestPaths((c)-[*]-(b))
RETURN p, q

Be aware, though, that if you have very long paths, or cycles, this query can take a long time or never finish. You should consider putting an upper bound on the path lengths, e.g.:

MATCH (a:User {username:"User1"}),(b:User {username:"User2"}),(c:User {username:"User3"}),
  p = allShortestPaths((a)-[*..10]-(c)), q = allShortestPaths((c)-[*..10]-(b))
RETURN p, q

Upvotes: 1

Related Questions