Multi Hop Traversal
Introduction
Welcome back to Advanced Queries! We're now at the halfway point in our course, having learned how to aggregate data and match complex patterns in graphs. In this third unit, we're expanding our pattern-matching capabilities by learning how to traverse paths of varying lengths through the graph.
So far, we've worked with fixed-length patterns. When we wanted to find friends of friends, we explicitly wrote two relationship hops in our pattern. But what if we want to find all connections within three degrees of separation, regardless of whether they're one, two, or three hops away? Or what if we need to find all possible paths between two people, no matter how long those paths might be?
This is where variable-length traversals become essential. In this lesson, we'll discover how to write patterns that can match paths of flexible lengths, extract detailed information about the paths we find, and understand the performance implications of traversing deeper into our graph. These techniques are fundamental for analyzing network connectivity, measuring social distance, and exploring the full reach of relationships in our data.
From Fixed to Variable Paths
In our previous lesson, we used patterns like (alice)-[:FRIENDS_WITH]->()-[:FRIENDS_WITH]->(rec) to find friends of friends. This pattern is explicit about the path length: exactly two hops. If we wanted to find people three hops away, we'd need to write another relationship traversal and, for four hops, yet another.
This approach becomes impractical when we want to answer questions like, "Who is within my extended network?" or "How far is this person from me?" We need a way to express patterns that can match paths of different lengths without writing separate queries for each possible distance.
Variable-length relationships solve this problem. Instead of specifying each hop individually, we can tell Neo4j to follow a relationship type for a range of hops, allowing a single pattern to match paths of varying lengths. This makes our queries more flexible and our analysis more comprehensive.
Visualizing Variable-Length Paths
Before we dive into the syntax, let's visualize what variable-length paths look like:

This diagram shows a simple network with node A as the starting point. Notice how nodes B and C are directly connected to A (1 hop away), node D is reachable through either B or C (2 hops away), and node E sits at the edge of the network (3 hops away). The relationships form a web that demonstrates how a single variable-length pattern can capture connections at multiple distances simultaneously.

