Implementing Graph Databases

1. Modeling Nodes and Relationships

ConceptDetail
Node (vertex)Entity with labels + properties
Relationship (edge)Typed, directed; can have properties
LabelGroup nodes (e.g., :Person, :Company)
Property graphMost 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

StepDetail
Identify entitiesNouns → nodes
Identify connectionsVerbs → relationships
Direction mattersFOLLOWS vs FOLLOWED_BY
ConstraintsUnique node properties (CREATE CONSTRAINT)
IndexesOn 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

PatternCypher
Variable-length(a)-[:KNOWS*1..3]->(b)
Shortest pathshortestPath((a)-[*]-(b))
All pathsallShortestPaths(...)
APOCProcedures for BFS/DFS, expansion

5. Modeling Properties on Edges

UseExample
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

AlgorithmUse
BFS / DFSConnectivity, levels
DijkstraShortest weighted path
A*Heuristic shortest path
Bellman-FordNegative weights
Floyd-WarshallAll-pairs shortest

7. Modeling Social Networks

QueryPattern
Friends-of-friendsMATCH (u)-[:FRIEND*2]-(fof) WHERE fof <> u
Mutual friendsMATCH (a)-[:FRIEND]-(m)-[:FRIEND]-(b)
InfluencersPageRank algorithm
CommunitiesLouvain, Label Propagation

8. Implementing Recommendation Systems

ApproachDetail
CollaborativePeople who bought X also bought Y (2-hop)
Content-basedItem similarity via shared tags
HybridCombine signals
GDS libraryNeo4j Graph Data Science algorithms
Node embeddingsnode2vec, 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

TipDetail
Anchor on indexed propertyStart MATCH with selective node
Bound traversal depthAvoid exponential explosion
PROFILE / EXPLAINInspect plan, db hits
Right directionMatch the lower-cardinality side first
Avoid Cartesian productsDisconnected MATCH patterns