Variable-Length Paths

*1..3 / shortestPath / allShortestPaths — traversals that don't know their depth in advance.

0/4 done

Overview

Variable-Length Paths

*1..3 / shortestPath / allShortestPaths — traversals that don't know their depth in advance.

Why it matters

Always bound your stars. MATCH (a)-[*]->(b) will happily walk the whole graph; MATCH (a)-[*1..3]->(b) won't.

Going deeper

Patterns you'll actually use, in increasing specificity:

PatternReturnsCost shape
(a)-[:R*1..3]->(b)Every path up to depth 3Bounded fan-out per hop
shortestPath((a)-[*..6]-(b))One shortest path, any directionBidirectional BFS, very fast
allShortestPaths((a)-[*..6]-(b))Every path of the same shortest lengthOne BFS + enumeration of ties
(a)-[*]->(b) (no bound)Anything reachableAvoid — unbounded traversal

Three habits that keep variable-length queries fast:

  1. Always upper-bound the star — even if the bound is generous (e.g. *..15). It changes 'unbounded' into 'bounded but loose', and that flips the planner.
  2. Type-constrain the relationship[:KNOWS*1..4] instead of [*1..4]. Skips every edge of a different type at planning time.
  3. Direction matters(a)-[*1..4]->(b) only follows outgoing edges; omitting the arrow doubles the fan-out at every hop.

Analogy

Variable-length paths are giving a search dog a leash with an adjustable length.

(a)-[*1..3]->(b) is 'sniff at most three blocks away'. The dog comes back in seconds with all matching trails. (a)-[*]->(b) is letting the dog off the leash in a city the size of São Paulo — it will find the target eventually, after checking every alley on the way. The depth bound is the leash: it does nothing in small graphs, and it's the only thing keeping you in business in big ones.

Make it stick

Use the prompts below to anchor variable-length paths to a real graph you own.

  • Search your codebase for `[*]` (no bound) in Cypher — each occurrence is a latent runaway query.
  • For your most expensive traversal, what's the *true* maximum business-meaningful depth? Bound the star to that number.
  • Which of your variable-length queries could be replaced by `shortestPath` because you only need one example, not every path?

Reading in progress · 0 of 4 activities done