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

Pattern Matching in Cypher

Writing complex graph patterns with multiple nodes, relationship types, and variable-length paths.

Pattern Matching in Cypher

You'll learn how to write complex graph queries that traverse multiple nodes, follow different relationship types, and use variable-length paths to find hidden connections.

What Is Pattern Matching?

Pattern matching is Cypher's superpower for finding patterns in your graph. While basic queries might find single nodes or simple relationships, real-world graphs require searching for complex shapes: "friends of friends," "products bought by people who liked similar items," or "paths connecting two distant nodes."

Think of it like describing a treasure map: instead of just marking one spot, you're drawing a path that winds through multiple landmarks, crosses different types of terrain, and might even loop back on itself.

Multiple Nodes and Relationship Types

You can chain patterns together to traverse longer paths:

MATCH (a:Person)-[:FRIENDS_WITH]->(b:Person)-[:LIKES]->(c:Movie)
RETURN a.name, b.name, c.title

This finds people connected through friendship to someone who likes a movie—a two-hop pattern with different relationship types.

Variable-Length Paths

When you don't know how many hops separate nodes, use variable-length patterns:

MATCH (a:Person)-[:FRIENDS_WITH*1..3]->(b:Person)
RETURN a.name, b.name

The *1..3 syntax means "follow FRIENDS_WITH relationships between 1 and 3 times." This finds friends, friends-of-friends, and friends-of-friends-of-friends. Omitting bounds (*) finds paths of any length (use carefully—can be expensive!).

Why This Matters

Pattern matching transforms graph databases from simple lookups into powerful relationship explorers. Instead of writing complex JOIN logic, you describe the shape of connections you're looking for, and Cypher efficiently traverses the graph to find matches.

Key Takeaway: Pattern matching in Cypher lets you write expressive queries across multiple nodes, diverse relationship types, and variable-length paths, making complex graph traversals remarkably simple.