Pattern Matching and Traversal
You'll learn how to write queries that explore connected data by matching relationship patterns and walking through graph structures.
The Core Idea
In graph databases, pattern matching lets you describe shapes of relationships you're looking for, and traversal operations walk along edges to discover connected nodes. Think of it like giving directions: "Find me all people who know someone who works at Company X" describes a pattern (person→knows→person→works_at→company), and the database traverses those relationships to find matches.
How Pattern Matching Works
Using Cypher (from our previous lesson), you specify patterns with ASCII-art-like syntax. The database engine then searches for subgraphs that match your pattern:
MATCH (alice:Person)-[:KNOWS]->(friend:Person)
WHERE alice.name = 'Alice'
RETURN friend.name
This pattern says: "Find a Person node named Alice, follow KNOWS relationships outward, and return the connected Person nodes." The traversal engine walks the graph structure, following edges that match your criteria.
Multi-Hop Traversal
You can traverse multiple relationships in sequence:
MATCH (person:Person)-[:KNOWS]->(friend)-[:WORKS_AT]->(company:Company)
RETURN person.name, company.name
This finds paths two hops long: person→friend→company. The database efficiently navigates these connections using the relationship edges stored with each node.
Variable-Length Paths
For "friends of friends" scenarios, specify path length:
MATCH (start:Person)-[:KNOWS*1..3]->(connected:Person)
WHERE start.name = 'Bob'
RETURN connected.name
The *1..3 means "follow 1 to 3 KNOWS relationships," letting you find connections within a certain distance.
Key Takeaway: Pattern matching in graph databases lets you declaratively describe relationship shapes, while traversal operations efficiently walk those connections to find matching paths through your data structure.