Course contentsShow
← System Design
Lesson 465 of 1,91913. NoSQL: Graph DatabasesFree lesson

Variable-Length Paths

Using variable-length relationship patterns like [*1..3] to explore paths of varying depth efficiently.

Variable-Length Paths

What you'll learn: How to efficiently explore graph relationships across multiple hops using variable-length patterns in graph queries.

In the last lesson, you learned to traverse relationships step by step, like finding friends-of-friends with two explicit relationship patterns. But what if you want to explore connections that might be 1, 2, 3, or even more hops away? Manually writing out each possibility becomes impractical quickly.

The Core Idea

Variable-length paths let you specify a range of relationship traversals in a single pattern using special syntax like [*1..3]. This tells the graph database: "follow this type of relationship between 1 and 3 times."

Think of it like exploring a social network to find connections within a certain degree. Instead of writing separate queries for "direct connections," "friends-of-friends," and "friends-of-friends-of-friends," you define a single pattern that covers all three levels.

Common Patterns

In Cypher, the syntax looks like:

MATCH (person:User {name: 'Alice'})-[:KNOWS*1..3]-(connection)
RETURN connection

The *1..3 means "traverse 1 to 3 KNOWS relationships." You can also use:

  • * for unlimited depth (use cautiously!)
  • *2.. for "at least 2 hops"
  • *..4 for "up to 4 hops"

This is particularly powerful for fraud detection (finding indirect connections between suspicious accounts), recommendation systems (discovering items through intermediate relationships), or organizational hierarchies (reporting chains of varying depth).

The database uses index-free adjacency to efficiently explore these paths without expensive joins, making variable-length traversals much faster than equivalent operations in relational databases.

Key Takeaway: Variable-length path patterns like [*1..3] let you explore relationships across multiple hops in a single, efficient query without writing redundant traversal logic.