Graph Databases with Neo4j
Model highly connected data as nodes and relationships and query deep traversals with Cypher.
Advanced · about 4 hours · difficulty 3/5
Learn first: NoSQL Families and When to Use Them
Some data is mostly about connections: social networks, recommendation engines, fraud rings, access-control hierarchies, knowledge graphs. In SQL, "friends of friends of friends" becomes a pile of self-joins that slow down with each hop. A graph database stores relationships directly, so traversals stay fast.
The property graph model
- Nodes represent entities and carry labels (
:Person,:Product) and properties. - Relationships connect nodes, have a type (
:FOLLOWS,:BOUGHT) and a direction, and can carry properties too.
Cypher queries
Neo4j's query language uses ASCII-art patterns: MATCH (me:Person {id: 1})-[:FOLLOWS]->()-[:FOLLOWS]->(suggestion) WHERE NOT (me)-[:FOLLOWS]->(suggestion) RETURN suggestion LIMIT 10 That reads as "people followed by the people I follow, whom I do not follow yet". Cypher ideas are now standardized as GQL.
When to reach for it
- Queries with variable or deep path lengths (shortest path, recommendations).
- Relationship-heavy domains where the relationships themselves are the product.
For simple hierarchies, PostgreSQL recursive CTEs are often enough, so try those first.
Pitfalls
- Using a graph database as a general-purpose store for tabular data.
- "Supernodes" with millions of relationships (a celebrity account) that make traversals slow unless modeled carefully.
You are ready to move on when you can model a small social graph and write a Cypher query for mutual connections and one for shortest path.
Key concepts
- Nodes, relationships and properties
- Cypher pattern matching
- Traversals and shortest path
- Recursive CTEs as an SQL alternative
- Supernodes
Mini project
Load a small follow graph into Neo4j and build an endpoint that returns 'people you may know' ranked by mutual connections.
Check yourself
Why does a friends-of-friends-of-friends query get slower in SQL but stay manageable in a graph database?
Free resources
- Neo4j documentation (Neo4j)
- Neo4j GraphAcademy (Neo4j)