Traversal Queries: Friends of Friends
What you'll learn: How to traverse multiple hops in a graph database to discover indirect connections, like finding friends-of-friends in a social network.
The Core Concept
In graph databases, a traversal query follows relationships across multiple steps (hops) to find nodes at specific depths. The classic example is finding "friends of friends" — people who aren't your direct friends, but are connected to you through someone you know.
Think of it like this: imagine you're at a party. Your direct friends are the people you know (1 hop away). Their friends, whom you haven't met, are 2 hops away. A traversal query lets you discover these second-degree connections efficiently.
Why Graph Databases Excel Here
Unlike relational databases that require expensive self-joins to find indirect relationships, graph databases use index-free adjacency. Each node physically points to its connected neighbors, making multi-hop traversals extremely fast — you simply follow the pointers.
Pattern Matching for Multi-Hop Queries
Using Cypher (as you've learned in Neo4j), you express depth by chaining relationship patterns:
// Find friends of friends (2 hops)
MATCH (you:Person {name: 'Alice'})-[:FRIEND]->(friend)-[:FRIEND]->(fof)
RETURN fof.name
This pattern (you)-[:FRIEND]->(friend)-[:FRIEND]->(fof) describes a path: start at Alice, traverse one FRIEND relationship to reach a friend, then traverse another to reach a friend-of-friend.
You can specify variable-length paths for flexible depth:
// Friends within 1 to 3 hops
MATCH (you:Person {name: 'Alice'})-[:FRIEND*1..3]->(connection)
RETURN connection.name
Real-World Applications
- Social recommendations: "People you may know"
- Fraud detection: Finding suspicious transaction chains
- Influence analysis: Measuring reach in social networks
Key Takeaway: Graph traversal queries follow relationships across multiple hops efficiently using pattern matching, enabling powerful social-graph queries like finding friends-of-friends without complex joins.