Path Queries¶
Cypher supports variable-length paths for traversing the graph.
Variable-Length Patterns¶
// Any number of hops
MATCH (a:Person)-[:KNOWS*]->(b:Person)
RETURN a.name, b.name
// Exactly 2 hops
MATCH (a:Person)-[:KNOWS*2]->(b:Person)
RETURN a.name, b.name
// 1 to 3 hops
MATCH (a:Person)-[:KNOWS*1..3]->(b:Person)
RETURN a.name, b.name
// Up to 5 hops
MATCH (a:Person)-[:KNOWS*..5]->(b:Person)
RETURN a.name, b.name
// At least 2 hops
MATCH (a:Person)-[:KNOWS*2..]->(b:Person)
RETURN a.name, b.name
A range whose upper bound is below its lower bound (*3..1, or *..0, whose lower bound is 1) is empty and matches no path, as openCypher defines it: MATCH gives no rows and OPTIONAL MATCH a row of nulls.
Path Variables¶
// Capture the path
MATCH path = (a:Person)-[:KNOWS*]->(b:Person)
WHERE a.name = 'Alix' AND b.name = 'Dave'
RETURN path
// Path length
MATCH path = (a:Person)-[:KNOWS*]->(b:Person)
WHERE a.name = 'Alix'
RETURN b.name, length(path) AS distance
ORDER BY distance
Shortest Path¶
// Find shortest path
MATCH path = shortestPath((a:Person)-[:KNOWS*]-(b:Person))
WHERE a.name = 'Alix' AND b.name = 'Dave'
RETURN path, length(path)
// All shortest paths
MATCH path = allShortestPaths((a:Person)-[:KNOWS*]-(b:Person))
WHERE a.name = 'Alix' AND b.name = 'Dave'
RETURN path
The path must fit the relationship's length: [*] is one or more hops, [*..3] at most three, [*0..] also pairs a node with itself (length 0), and a relationship without * is a single hop. A pair of nodes without such a path has no row; use OPTIONAL MATCH to keep it with a null path.
A shortest path from a node to itself (shortestPath((a)-[:KNOWS*]-(a))) has no row, or a null path under OPTIONAL MATCH: a shortest path joins two different nodes, so the search does not look for a way back to the start, neither out and back over one relationship nor around a cycle such as Alix, Gus, Mia, Alix. With *0.. it is the path of length 0.
Path Filtering¶
// Filter paths by node properties
MATCH path = (a:Person)-[:KNOWS*]->(b:Person)
WHERE a.name = 'Alix'
AND all(n IN nodes(path) WHERE n.active = true)
RETURN path
// Filter by relationship properties
MATCH path = (a:Person)-[:KNOWS*]->(b:Person)
WHERE a.name = 'Alix'
AND all(r IN relationships(path) WHERE r.strength > 0.5)
RETURN path
Path Functions¶
| Function | Description |
|---|---|
nodes(path) | List of nodes in path |
relationships(path) | List of relationships in path |
length(path) | Number of relationships in path |