Graph Data Models
Property graphs, RDF triples and graphs stored in SQL tables: how each works, how you query paths of unknown length, and when a graph database is worth it.
Overview
Some data is mostly about connections. Who follows whom, which account shared a card with which device, which package depends on which. When the links are what you query, and a question can follow them several steps deep, a graph is the natural model: vertices (also called nodes) are the things, and edges (relationships) are the links between them.
Tables can hold a graph too, so the real question is how easy the model makes path questions and what it costs to answer them. This chapter covers the three common ways to store a graph and how each one asks for a path.
When connections are the data
A tree is a graph where each item has one parent. Documents handle trees well. Once items share neighbors in many directions, and the depth of a question is not fixed ('anyone within three follows of Ana'), a graph model keeps both the data and the queries simple.
The same pattern shows up in four common domains. In each, once you name the vertices and the edges, the typical question turns out to be a path.
- Social network: the vertices are people, and the edges are follows and friendships. A typical question asks for friends of friends who are not yet connected.
- Fraud detection: the vertices are accounts, cards, devices and addresses, and the edges say which account used or shares which. A typical question asks for accounts linked through shared devices.
- Package manager: the vertices are packages and their versions, and the edges are 'depends on'. A typical question asks for everything a package pulls in, transitively.
- Access control: the vertices are users, groups and resources, and the edges are 'member of' and 'can read'. A typical question asks whether this user can reach this file through any group.
The next three sections show three ways to store such a graph, starting with the one built around it.
Key concepts
- Vertex and edge
- Property graph
- RDF triple
- Cypher
- SPARQL
- GQL
- Recursive CTE
- Index-free adjacency
Interview questions
- When would you choose a graph database over a relational one?
- How do a property graph and an RDF triple store differ?
- How would you find everyone within three hops of a user in SQL?
- What is the difference between a graph database and a graph processing framework?
Sign up free to read the full topic
More DDIA topics
- Encoding Formats: JSON, Protobuf, Avro, Thrift
- End-to-End Correctness and the Exactly-Once Myth
- Event Streams and Message Brokers
- Fan-Out and the Twitter Timeline Problem
- Fault Tolerance in Stream Processing
- Faults and Partial Failures
- Implementing Serializability
- Isolation Levels
- Joins in Batch Processing
- Joins in Stream Processing
- Lambda and Kappa Architectures
- Leaderless Replication (Dynamo-Style)
Start free on Cariara · Coding problems · System design studio