Implementing Graph Databases
1. Modeling Nodes and Relationships
| Concept | Detail |
|---|---|
| Node (vertex) | Entity with labels + properties |
| Relationship (edge) | Typed, directed; can have properties |
| Label | Group nodes (e.g., :Person, :Company) |
| Property graph | Most common model (Neo4j, Neptune) |
| RDF triple store | (subject, predicate, object) — SPARQL |
(:Person {name:"Ada"}) -[:WORKS_AT {since:2020}]-> (:Company {name:"X"})2. Designing Graph Schemas
| Step | Detail |
|---|---|
| Identify entities | Nouns → nodes |
| Identify connections | Verbs → relationships |
| Direction matters | FOLLOWS vs FOLLOWED_BY |
| Constraints | Unique node properties (CREATE CONSTRAINT) |
| Indexes | On node label + property |
3. Using Cypher Query Language
Example: Cypher
// Create
CREATE (p:Person {id:1, name:"Ada"})-[:KNOWS {since:2020}]->(q:Person {id:2, name:"Bob"});
// Read
MATCH (p:Person {name:"Ada"})-[:KNOWS]->(f) RETURN f.name;
// Update
MATCH (p:Person {id:1}) SET p.age = 36;
// Delete relationship
MATCH (:Person {id:1})-[r:KNOWS]->(:Person {id:2}) DELETE r;
4. Implementing Graph Traversal
| Pattern | Cypher |
|---|---|
| Variable-length | (a)-[:KNOWS*1..3]->(b) |
| Shortest path | shortestPath((a)-[*]-(b)) |
| All paths | allShortestPaths(...) |
| APOC | Procedures for BFS/DFS, expansion |
5. Modeling Properties on Edges
| Use | Example |
|---|---|
| Weight | :ROAD {distance: 12.4} |
| Time | :PURCHASED {at: ts} |
| Type qualifier | :WORKS_AT {role:"engineer"} |
| Confidence | :SIMILAR_TO {score: 0.87} |
6. Implementing Path Finding Algorithms
| Algorithm | Use |
|---|---|
| BFS / DFS | Connectivity, levels |
| Dijkstra | Shortest weighted path |
| A* | Heuristic shortest path |
| Bellman-Ford | Negative weights |
| Floyd-Warshall | All-pairs shortest |
7. Modeling Social Networks
| Query | Pattern |
|---|---|
| Friends-of-friends | MATCH (u)-[:FRIEND*2]-(fof) WHERE fof <> u |
| Mutual friends | MATCH (a)-[:FRIEND]-(m)-[:FRIEND]-(b) |
| Influencers | PageRank algorithm |
| Communities | Louvain, Label Propagation |
8. Implementing Recommendation Systems
| Approach | Detail |
|---|---|
| Collaborative | People who bought X also bought Y (2-hop) |
| Content-based | Item similarity via shared tags |
| Hybrid | Combine signals |
| GDS library | Neo4j Graph Data Science algorithms |
| Node embeddings | node2vec, FastRP |
9. Querying Complex Patterns
Example: Fraud Ring Detection
MATCH (a:Account)-[:USES]->(d:Device)<-[:USES]-(b:Account)
WHERE a <> b AND a.created > date() - duration({days:7})
WITH d, collect(DISTINCT a) AS accounts
WHERE size(accounts) >= 5
RETURN d, accounts;
10. Optimizing Graph Queries
| Tip | Detail |
|---|---|
| Anchor on indexed property | Start MATCH with selective node |
| Bound traversal depth | Avoid exponential explosion |
| PROFILE / EXPLAIN | Inspect plan, db hits |
| Right direction | Match the lower-cardinality side first |
| Avoid Cartesian products | Disconnected MATCH patterns |