'neo4j -- Find all shortest paths between more than 2 nodes
For example,I want to query allShortestPaths between 3 nodes(A,B,C),it means i want to query: 1. the allShortestPaths between A and B 2. the allShortestPaths between C and B 3. the allShortestPaths between A and C
but I only find the allShortestPaths query to get allShortestPaths between two nodes.
As follow:
MATCH (node1:E { eid:"a9c2f114-796f-4934-a2d0-04bb3345e1d2" }),
(node2:E { eid:"01968dd2-1ed6-472d-82e9-be7701036b3b" }),
p = allShortestPaths((node1)-[*]-(node2))
RETURN p LIMIT 25
I am wondering if there exists a allShortestPaths query supporting more than 2 nodes input?
Now,to search 3 nodes,I have to invoke the "allShortestPaths" three times,as follow:
MATCH (node1:E { eid:"b73ade90-dfa1-4b94-bd0f-c16fd93bd680" }),
(node2:E { eid:"ddb5c52d-7002-4ac7-87d5-0f727f2ab3e7" }),
(node3:E { eid:"0398b081-6676-4a91-856b-abbabaee5e70" }) ,
p = allShortestPaths((node1)-[*]-(node2)),
q = allShortestPaths((node3)-[*]-(node2)),
m = allShortestPaths((node3)-[*]-(node1))
RETURN p,q,m LIMIT 10
What i want to do is to search allShortestPaths between arbitrary number of nodes.
So far,I intend to write user-defined procedures,but it will costs more time.I wondering who can provide better advice.
i want to search search allShortestPaths between serveral nodes.
such as: allShortestPaths((a)-[*]-(b)-[*]-(c)-[*]-(a))
I want get the all shortest path between a and b,b and c,c and a in a query
Solution 1:[1]
Neo4j doesn't provide a version of allShortestPaths taking multiple patterns, which is what you want:
allShortestPaths((node1)-[*]-(node2), (node1)-[*]-(node3), (node2)-[*]-(node3))
You wish to optimize the traversals by piggy-backing on the first one to do the second one at the same time, but there's no such thing out of the box, and it wouldn't do the third one either. It's a really specific use case.
You either have to call allShortestPaths n*(n-1) times (for n nodes) in Cypher, or try implementing it yourself server-side in a procedure using the Traversal framework.
Solution 2:[2]
here a sample cypher
MATCH (n:Entity) where n.name IN {names}
WITH collect(n) as nodes
UNWIND nodes as n
UNWIND nodes as m
WITH * WHERE id(n) < id(m)
MATCH path = allShortestPaths( (n)-[*..4]-(m) )
RETURN path
see https://neo4j.com/developer/kb/all-shortest-paths-between-set-of-nodes/ for more
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Frank Pavageau |
| Solution 2 | Jimmy Obonyo Abor |
