Designing Data-Intensive ApplicationsParts I-III (complete book) · condensed, chapter by chapter
Chapter 2

Data Models and Query Languages

How general-purpose data models (relational, document, graph) and their query languages shape what software can do, and how to pick the one that fits your application.

Key takeaways

  • The document model fits self-contained trees of one-to-many data: better locality, schema flexibility, less impedance mismatch.
  • The relational model wins on joins, many-to-one and many-to-many relationships; data tends to get more interconnected as features are added.
  • "Schemaless" really means schema-on-read (implicit, interpreted by readers) versus schema-on-write (explicit, enforced by the database).
  • Declarative query languages (SQL, CSS, Cypher, SPARQL, Datalog) let the optimizer change execution and parallelize without changing queries; imperative APIs cannot.
  • Graph models suit data where anything may relate to anything; variable-length traversals are concise in Cypher/SPARQL and clumsy in SQL.
  • Relational and document databases are converging; a hybrid is a good direction.

Introduction: layered data models

  • Applications stack data models; each layer is represented in terms of the one below and hides its complexity.
  • Every model embeds assumptions: some operations are fast and natural, others awkward or unsupported.
  • This chapter covers layer 2 (storage and query models). Chapter 3 covers how they are implemented (layer 3).
1. App objects, data structures, APIs 2. JSON / tables / graph (this chapter) 3. Bytes on disk, memory, network (Ch. 3) 4. Currents, light, magnetic fields built on
Each layer hides the one below behind a clean data model.

Relational Model Versus Document Model

  • Relational model (Codd, 1970): data in relations (tables), each an unordered collection of tuples (rows).
  • Dominant since the mid-1980s (25-30 years). Roots: business transaction and batch processing on mainframes. Goal: hide internal representation behind a cleaner interface.
  • Competitors (network, hierarchical, object, XML databases) came and went; relational generalized well to most of the web.

The Birth of NoSQL

  • "NoSQL" (2010s) names no particular technology; it began as a 2009 meetup hashtag, later reinterpreted as Not Only SQL.
  • Driving forces:
    • Greater scalability: very large datasets or very high write throughput.
    • Preference for free and open source software.
    • Specialized query operations poorly supported by the relational model.
    • Frustration with restrictive relational schemas; desire for a more dynamic, expressive model.
  • Likely future: relational alongside many nonrelational stores, called polyglot persistence.

The Object-Relational Mismatch

  • OO application code vs tables/rows/columns needs an awkward translation layer: the impedance mismatch.
  • ORMs (ActiveRecord, Hibernate) cut boilerplate but cannot hide the differences.
  • Example: a LinkedIn résumé. Names appear once per user (columns); positions, education, contact info are one-to-many. Three representations:
    1. Normalized: separate tables with a foreign key to users (traditional SQL, pre-SQL:1999).
    2. Structured datatypes / XML / JSON columns that can be queried and indexed (Oracle, DB2, SQL Server, PostgreSQL; JSON in DB2, MySQL, PostgreSQL).
    3. Encode as JSON/XML in a text column, interpreted by the application; usually cannot be queried by the database.
  • A résumé is a self-contained document, so JSON fits (MongoDB, RethinkDB, CouchDB, Espresso). Locality: one query instead of many queries or a multi-way join.
  • One-to-many relationships form a tree; JSON makes it explicit.

Example 2-1 holds the profile as one JSON document: scalar fields (user_id 251, names, region_id, industry_id) plus nested positions and education arrays and a contact_info object.

Relational (shredded) users positions education contact_info FK user_id; many queries or joins Document (tree) user 251 positions education contact Co-chair Harvard one place, one query
Figures 2-1 and 2-2 simplified: one-to-many data shredded into tables vs one JSON tree.

ORM means Object-Relational Mapping. Imagine the LinkedIn application is written in Java. Its User object contains a name and a list of Position objects. Java naturally represents this as an object nested inside another object. A normalized SQL database instead represents it as one row in users and many rows in positions, linked by user_id. That difference in structure is the object-relational impedance mismatch.

// Java application model
class User {
    Long id;
    String name;
    List<Position> positions;
}

// Relational database representation
users:     (id=101, name='Alice')
positions: (user_id=101, company='Amazon')
           (user_id=101, company='Google')

Without an ORM, the developer writes SQL, executes it, reads rows from the result set, creates a User object, and manually fills the positions list. An ORM such as Hibernate or Active Record maps classes to tables and fields to columns, generates SQL for ordinary create/read/update/delete operations, and reconstructs objects from database rows.

// Hibernate / JPA example (simplified)
@Entity
class User {
    @Id Long id;
    String name;
    @OneToMany(mappedBy = "user")
    List<Position> positions;
}

User alice = entityManager.find(User.class, 101L);
// Typical SQL for the user:
// SELECT id, name FROM users WHERE id = 101;

Why can't the ORM make the mismatch disappear? Relational databases use foreign keys, joins, transactions, and query sets; Java uses object references, collections, and methods. For example, loading 100 users and then lazily opening each user's positions can trigger 101 SQL queries (one for the users, plus one per user). This is the N+1 query problem. A join fetch or carefully designed batch fetch can reduce the extra queries, but the engineer must still understand the SQL that runs.

How does this connect to SQL vs NoSQL?
Storage choiceWhere Alice's positions liveTypical trade-off
Normalized SQLSeparate users and positions tablesGreat for shared relationships and joins; object assembly needed
SQL with JSONBA queryable JSON array in a PostgreSQL columnNested locality plus SQL, but document updates and constraints need thought
JSON as plain textSerialized JSON string in a text columnApplication parses it; ordinary text storage cannot query nested keys as structured data
Document NoSQLNested positions array within one MongoDB-style documentNatural whole-profile reads; cross-document joins/consistency can be more involved

Important: An ORM is not a third database model or an alternative to SQL/NoSQL. It's a library in the application that maps language objects to a relational database. The book compares normalized tables, structured JSON in SQL, opaque serialized JSON, and native document databases because they each handle nested application data differently.

Many-to-One and Many-to-Many Relationships

  • Why store region_id/industry_id as IDs, not strings like "Greater Seattle Area"? Standardized lists give consistent spelling, no ambiguity, easy updates, localization, and better search (the list knows Seattle is in Washington).
  • ID vs text is a question of duplication. An ID has no human meaning, so it never needs to change. Duplicated human-meaningful text must be updated everywhere: write overhead and inconsistency risk.
  • Removing duplication is the key idea of normalization. Rule of thumb: duplicating values that could live in one place means the schema is not normalized.
  • Normalizing needs many-to-one relationships (many people in one region), which fit documents poorly: joins are easy in relational, often weak in document stores (RethinkDB yes, MongoDB no, CouchDB only predeclared views, at time of writing).
  • Without database joins, the application emulates them with multiple queries, shifting work into app code.
  • Data becomes more interconnected as features are added:
    • Organizations and schools as entities: each with its own page and logo, referenced from résumés.
    • Recommendations: one user recommends another; the recommendation must show the author's current photo, so it references the author's profile.
  • These need many-to-many relationships: each résumé can still be one document, but references to organizations, schools and users require joins.
Résumé A (document) position education recommendation Résumé B (document) position education Organization School User B references need joins
Figure 2-4 simplified: documents inside dotted boxes, shared entities referenced many-to-many.

Are Document Databases Repeating History?

  • The many-to-many debate predates NoSQL. IBM's IMS (built for Apollo stock-keeping, released 1968, still maintained) used the hierarchical model: a tree of nested records, much like JSON.
  • IMS handled one-to-many well, made many-to-many hard, had no joins. Developers chose between duplicating (denormalizing) data and manually resolving references: the same problems document databases face today.
  • Two proposed fixes: the relational model (won) and the network model (faded). Their "great debate" ran through the 1970s.

The network model

  • Standardized by CODASYL (the CODASYL model); generalizes the hierarchy: a record can have multiple parents, enabling many-to-one and many-to-many.
  • Links were pointer-like (stored on disk), not foreign keys. A record was reached only by following an access path from a root along chains of links.
  • Queries moved a cursor through record lists; with many paths to a record, programmers tracked them in their heads.
  • Efficient on 1970s hardware (slow tape seeks), but code was complicated and inflexible: changing access paths meant rewriting handwritten query code.
  • In CODASYL the join was effectively done at insert time; relational joins on foreign keys happen at query time.

The relational model

  • All data laid out in the open: a table is just a collection of rows. No nested structures or access paths. Read any rows matching any condition, look up by key, insert without worrying about relationships.
  • The query optimizer picks execution order and indexes, which is effectively the access path, chosen automatically.
  • New query patterns: declare a new index, and queries use it without being changed. Adding features is easier.
  • Key insight: optimizers are hard to build, but you build one once and every application benefits. Hand-coding paths is easier for one query; the general solution wins long term.
Hierarchical one parent each Network (CODASYL) many parents; follow path Relational Query optimizer path chosen automatically
Who picks the access path: the programmer (hierarchical, network) or the optimizer (relational).

Comparison to document databases

  • Documents revert to the hierarchical model in one way: nested one-to-many records live inside the parent.
  • For many-to-one and many-to-many, relational and document are not fundamentally different: a unique ID (foreign key / document reference) resolved at read time by a join or follow-up queries.

Relational Versus Document Databases Today

Comparing only the data model (fault tolerance is Chapter 5, concurrency Chapter 7):

DocumentRelational
Main argumentSchema flexibility, locality, closer to app data structuresJoins, many-to-one and many-to-many support
Best fitTree of one-to-many, whole tree loaded at onceInterconnected data
WeaknessCan't refer directly to nested items; weak joinsShredding a document into tables: cumbersome schema, complex code
SchemaSchema-on-readSchema-on-write

Which data model leads to simpler application code?

  • Document-like data (tree, loaded whole) → document model. Shredding it relationally gives cumbersome schemas.
  • Nested items need paths like "the second position of user 251"; fine if nesting is shallow. Weak joins may not matter (e.g. event analytics).
  • With many-to-many: denormalizing forces the app to keep copies consistent; emulating joins with multiple requests moves complexity into the app and is usually slower than an in-database join.
  • It depends on the relationships: for highly interconnected data, document is awkward, relational acceptable, graph most natural.

Schema flexibility in the document model

  • Most document databases (and JSON in RDBMSes) enforce no schema; XML support often has optional validation. Readers get no guarantee about fields.
  • "Schemaless" is misleading: readers assume an implicit schema. Better terms: schema-on-read vs schema-on-write.
  • Analogy: dynamic (runtime) vs static (compile-time) type checking. No right or wrong answer.
  • Format changes show the difference. Example: split full name into first_name/last_name.
  • Schema-on-read: write new documents with the new fields; app code fills first_name from name when reading old ones.
  • Schema-on-write: a migration, ALTER TABLE users ADD COLUMN first_name text; then an UPDATE that splits name.
  • Schema changes' slow reputation is not entirely deserved: most RDBMSes run ALTER TABLE in a few milliseconds. Exception: MySQL copies the whole table (minutes to hours of downtime on large tables), though tools work around it.
  • UPDATE on a large table is slow everywhere (every row rewritten). Alternative: leave first_name NULL and fill it in at read time, as a document database would.
  • Schema-on-read helps when data is heterogeneous: many object types (impractical as one table each), or structure set by external systems that may change at any time.
  • When all records share a structure, schemas usefully document and enforce it (more in Chapter 4).
Schema-on-write Writer DB checks Storage Reader explicit schema, like static typing Schema-on-read Writer Any keys App interprets Reader implicit schema, like dynamic typing
Where the structure is enforced: at write time by the database, or at read time by the code.

The real problem: you built LinkedIn with 100 million profiles. Originally each profile had name: "John Smith". Your product now needs first_name and last_name. How do you introduce the new format while old records and older application instances still exist?

A schema describes the fields, types, and constraints data is expected to follow. Schema-on-write means the database checks structural rules when data is inserted or changed. Schema-on-read means the consumer decides how to interpret the shape of the stored record when it is loaded. An apparently “schemaless” collection still has an implicit schema because application code expects particular fields.

Old profile
{
  "id": 101,
  "name": "John Smith"
}
New profile
{
  "id": 101,
  "first_name": "John",
  "last_name": "Smith"
}
Approach A: Schema-on-read (flexible document model)

Start writing new documents with the new fields. Leave the millions of existing documents unchanged. The reader supports both layouts:

def display_name(user):
    if "first_name" in user:              # New records
        return user["first_name"] + " " + user.get("last_name", "")
    return user["name"]                 # Old records

This makes rollout inexpensive: no immediate database-wide rewrite. The trade-off is that every consumer that reads those documents must understand old and new formats, including background workers, analytics jobs, and other services. You can eventually migrate the old documents and remove the fallback. Also, parsing a person's real name into first and last names isn't universally reliable; the example is about schema evolution, not correct name parsing.

Approach B: Schema-on-write (traditional relational table)

Change the table definition first. In PostgreSQL, adding nullable columns is often a metadata-only operation:

ALTER TABLE users
  ADD COLUMN first_name TEXT,
  ADD COLUMN last_name TEXT;

Deploy application code that writes the new fields and temporarily supports the old name field. Then backfill old rows in manageable batches:

-- Illustrative only: real names need safer parsing.
UPDATE users
SET first_name = split_part(name, ' ', 1),
    last_name  = substr(name, length(split_part(name, ' ', 1)) + 2)
WHERE first_name IS NULL;

Why isn't this automatically fast? ALTER TABLE may only change metadata; a large UPDATE physically rewrites rows and generates I/O, transaction-log traffic, locks, and replication work. An online migration usually uses the sequence expand → support both versions → backfill → validate → remove old fields. You can also leave old rows with NULL new columns and compute a fallback at read time—SQL and NoSQL are not strict opposites here.

Which fits what workload?
ScenarioOften useful approachReason
Raw events from many external APIsFlexible documents + version-aware readersShapes vary and can change independently
Payments and financial ledger rowsExplicit schema, constraints, transactionsMissing or incorrectly typed values should fail early
Gradual rollout with old and new application versionsCompatible migration, regardless of database modelBoth versions must safely read/write during deployment

Modern document databases can enforce validation rules, and relational databases can store JSON with flexible fields. So the choice is less “SQL versus NoSQL” and more where you validate data, how you manage versions, and how much compatibility work the readers must do.

Data locality for queries

  • A document is stored as one continuous string (JSON, XML, or binary like MongoDB's BSON). Fetching it whole (e.g. to render a page) is faster than multiple index lookups and disk seeks across tables.
  • Only helps if you need large parts at once: the whole document is loaded even for a small part; updates usually rewrite the whole document (only size-preserving changes can be done in place).
  • Advice: keep documents small; avoid writes that grow them. These limits shrink where documents are useful.
  • Locality is not document-only: Spanner interleaves child rows in a parent table; Oracle has multi-table index cluster tables; Bigtable column families (Cassandra, HBase) do similar.

Convergence of document and relational databases

  • Most RDBMSes (not MySQL) have supported XML since the mid-2000s, with local modification, indexing and querying inside documents.
  • JSON support: PostgreSQL 9.3+, MySQL 5.7+, IBM DB2 10.5+.
  • Document side: RethinkDB supports relational-like joins; some MongoDB drivers resolve references (client-side join, slower: extra round-trips, less optimized).
  • Codd's original model allowed nonsimple domains (a value could be a nested relation).
  • The models complement each other; a hybrid of relational and document is a good route for future databases.

Query Languages for Data

  • SQL is declarative; IMS and CODASYL used imperative code (typically COBOL iterating one record at a time).
  • Imperative: tell the computer which operations to perform in which order (loop over animals, push sharks into a list).
  • Declarative: specify the pattern of the result (conditions, sorting, grouping, aggregation), not how. The optimizer chooses indexes, join methods, and order.
sharks = σ family = "Sharks" (animals)          -- relational algebra
SELECT * FROM animals WHERE family = 'Sharks';  -- SQL
  • Benefits of declarative:
    • Concise; hides engine details, so performance can improve without query changes (SQL promises no order, so records may move to reclaim disk space).
    • Easier to parallelize: CPUs gain cores, not clock speed; declarative specifies only the result, not an ordered algorithm.

Declarative Queries on the Web

  • Example: an ocean-animals site highlights the selected page title (<li class="selected"><p>Sharks</p>) with a blue background.
  • CSS: li.selected > p { background-color: blue; }. The selector declares the pattern: <p> whose direct parent is an <li> with class selected.
  • XSL/XPath equivalent: li[@class='selected']/p. Both are declarative.
  • Imperative JavaScript with the DOM API needs nested loops over elements. Longer, harder to read, and:
    • If selected moves, the blue stays until page reload; CSS removes it automatically.
    • Using a faster new API needs a rewrite; browsers can speed up CSS/XPath without breaking compatibility.

MapReduce Querying

  • MapReduce: model for bulk processing across many machines, popularized by Google. MongoDB and CouchDB support a limited form for read-only queries over many documents (Chapter 10 covers it in general).
  • Between declarative and imperative: query logic lives in code snippets the framework calls repeatedly. Based on functional map (collect) and reduce (fold/inject).
  • Example: a marine biologist counts sharks sighted per month. In PostgreSQL: filter family = 'Sharks', GROUP BY date_trunc('month', observation_timestamp), sum(num_animals).
db.observations.mapReduce(
  function map() { emit(year + "-" + month, this.numAnimals); },
  function reduce(key, values) { return Array.sum(values); },
  { query: { family: "Sharks" }, out: "monthlySharkReport" });
  • The query filter is declarative (a MongoDB extension). map runs once per matching document and emits (month key, count). Pairs are grouped by key; reduce runs once per key; output goes to monthlySharkReport.
  • Two December 1995 shark observations (3 and 4 animals) → emit("1995-12", 3), emit("1995-12", 4) → reduce("1995-12", [3, 4]) = 7.
  • map and reduce must be pure functions (only their input, no extra queries, no side effects), so the database can run them anywhere, in any order, and rerun on failure.
  • MapReduce is low level. SQL can run as a MapReduce pipeline or without it; nothing ties SQL to one machine.
  • Usability problem: two carefully coordinated functions are harder than one query, and declarative languages give the optimizer more room. So MongoDB 2.2 added the declarative aggregation pipeline.
  • The pipeline chains a $match stage (family Sharks) and a $group stage (by year and month, $sum of animals). Expressiveness like a subset of SQL, in JSON syntax. Moral: a NoSQL system may accidentally reinvent SQL in disguise.
documents 25 Dec 1995 Sharks, 3 12 Dec 1995 Sharks, 4 map ("1995-12", 3) ("1995-12", 4) group by key 1995-12: [3, 4] reduce sum = 7 pure functions: any order, anywhere, rerun on failure
The shark-count example: map emits per document, reduce runs once per key.

Graph-Like Data Models

  • Mostly one-to-many (trees) or no relationships → document model. Very common, complex many-to-many → model as a graph.
  • A graph has vertices (nodes, entities) and edges (relationships, arcs). Examples: social graphs (people), the web graph (pages and links), road or rail networks (junctions and lines).
  • Known algorithms: shortest path for car navigation; PageRank for web page popularity.
  • Graphs need not be homogeneous: Facebook keeps one graph with many vertex types (people, locations, events, checkins, comments) and edge types.
  • Running example (Figure 2-5): Lucy from Idaho and Alain from Beaune, France, married and living in London.
  • Models covered: property graph (Neo4j, Titan, InfiniteGraph) and triple-store (Datomic, AllegroGraph). Declarative languages: Cypher, SPARQL, Datalog. Imperative alternatives exist: Gremlin, and Pregel for processing (Chapter 10).
North America United States Idaho (state) within within Europe France Beaune within within* London within* Lucy Alain married born_in born_in lives_in
Figure 2-5 simplified (intermediate regions collapsed into within* chains). Lucy's birthplace is a state; her residence is a city.

Property Graphs

  • Vertex: unique ID, outgoing edges, incoming edges, properties (key-value pairs).
  • Edge: unique ID, tail vertex (start), head vertex (end), a label for the relationship kind, properties.
  • Think of it as two relational tables, vertices and edges, with properties in a PostgreSQL json column and indexes on tail_vertex and head_vertex.
  • Important aspects:
    1. Any vertex can connect to any other; no schema restricts associations.
    2. Given a vertex, find incoming and outgoing edges efficiently, so traverse forward and backward (hence both indexes).
    3. Different labels store many kinds of information in one graph with a clean model.
  • Easy here, hard relationally: different regional structures per country (France: départements and régions; US: counties and states), a country within a country, varying granularity (residence a city, birthplace a state).
  • Graphs are good for evolvability: e.g. add allergen vertices linked to people and foods, then query what is safe to eat.
vertices vertex_id (PK) properties (json) edges edge_id (PK) tail_vertex (indexed) head_vertex (indexed) label properties (json) outgoing: by tail incoming: by head
Example 2-2 as tables: both endpoint indexes allow traversal in either direction.

The Cypher Query Language

  • Cypher: declarative query language for property graphs, created for Neo4j (named after a Matrix character, unrelated to cryptography).
  • Insert: vertices get symbolic names; edges use arrows, e.g. (Idaho) -[:WITHIN]-> (USA) (Idaho is tail, USA is head).
  • Query: people who emigrated from the US to Europe, i.e. a BORN_IN edge to somewhere within the US and a LIVES_IN edge to somewhere within Europe.
MATCH
  (person) -[:BORN_IN]->  () -[:WITHIN*0..]-> (us:Location {name:'United States'}),
  (person) -[:LIVES_IN]-> () -[:WITHIN*0..]-> (eu:Location {name:'Europe'})
RETURN person.name
  • Execution options: scan all people and check birthplace/residence; or (with an index on name) start from the US and Europe vertices, follow incoming WITHIN edges to all contained locations, then incoming BORN_IN/LIVES_IN edges to people.

Graph Queries in SQL

  • Possible, but difficult. Relational queries usually know their joins in advance; graph queries may traverse a variable number of edges.
  • LIVES_IN may point at a street, city, district, region, state; each may be WITHIN another. Cypher's :WITHIN*0.. means "follow WITHIN zero or more times", like * in a regex.
  • Since SQL:1999, recursive common table expressions (WITH RECURSIVE; PostgreSQL, DB2, Oracle, SQL Server) express this: build sets in_usa/in_europe by repeatedly following incoming within edges, find people via born_in/lives_in, then intersect.
  • It takes 29 lines in SQL vs 4 in Cypher: different models suit different use cases.

Triple-Stores and SPARQL

  • Mostly equivalent to property graphs, in different words.
  • All data is a triple: (subject, predicate, object), e.g. (Jim, likes, bananas).
  • The subject is a vertex. The object is either:
    1. A primitive value: predicate + object = a property key and value, e.g. (lucy, age, 33) ≈ {"age":33}.
    2. Another vertex: predicate = edge label, e.g. (lucy, marriedTo, alain).
  • Written in Turtle (subset of Notation3). Vertices are _:someName, meaningful only within the file. Semicolons say several things about one subject.
(lucy, age, 33) lucy {"age": 33} object = value (lucy, marriedTo, alain) lucy alain marriedTo object = vertex subject = tail object = head
A triple's object is either a property value or another vertex (an edge).

The semantic web

  • Triple-stores are independent of the semantic web (Datomic is a triple-store unrelated to it; it actually uses 5-tuples, with two versioning fields).
  • Idea: sites publish machine-readable data too. RDF (Resource Description Framework) lets sites publish in a consistent format, combinable into a "database of everything".
  • Overhyped in the early 2000s and not realized in practice. Still, triples can be a good internal data model.

The RDF data model

  • Turtle is a human-readable RDF format; RDF/XML does the same far more verbosely. Tools like Apache Jena convert between formats.
  • Designed for internet-wide exchange: subjects, predicates and objects are often URIs (e.g. <http://my-company.com/namespace#within>), so your within won't clash with another party's.
  • The URI need not resolve; it is just a namespace, declared once as a prefix.

The SPARQL query language

  • SPARQL (SPARQL Protocol and RDF Query Language, "sparkle"): query language for RDF triple-stores. It predates Cypher, whose pattern matching borrows from it.
  • The emigration query is even more concise than in Cypher (core patterns):
?person :bornIn  / :within* / :name "United States".
?person :livesIn / :within* / :name "Europe".
  • Variables start with ?. ?person :bornIn / :within* ?location matches Cypher's (person) -[:BORN_IN]-> () -[:WITHIN*0..]-> (location).
  • RDF uses predicates for both properties and edges, so the same syntax matches properties: ?usa :name "United States".

Graph Databases Compared to the Network Model

Are graph databases CODASYL in disguise? No:

CODASYLGraph database
SchemaSpecifies which record type nests in whichAny vertex can link to any other
AccessOnly by traversing an access pathDirectly by unique ID, or via an index
OrderingChildren are ordered sets; inserts must handle positionVertices and edges unordered; sort at query time
QueriesImperative, hard to write, broken by schema changesImperative optional; declarative Cypher/SPARQL available

The Foundation: Datalog

  • Datalog: much older (studied in the 1980s), less known, but the foundation later query languages build on. Used by Datomic and by Cascalog (for large datasets in Hadoop). It is a subset of Prolog.
  • Data model like triples, generalized: predicate(subject, object), e.g. within(usa, namerica)., born_in(lucy, idaho).
  • Queries are built from rules that define new, derived predicates (not stored), here within_recursive and migrated. Rules can call other rules or themselves.
  • Rule 1: a location is within_recursive of its own name. Rule 2: if within(Location, Via) and Via is within Name, so is Location. Rule 3 (migrated): a person's birth and living locations are recursively within BornIn and LivingIn.
  • Query ?- migrated(Who, 'United States', 'Europe'). returns Who = 'Lucy'.
  • Uppercase words are variables; predicates match like in Cypher/SPARQL.
  • A rule applies when all right-hand predicates of :- match; the left side is then as if added to the database.
  • Derivation: rule 1 on name(namerica, ...) → within_recursive(namerica, 'North America'); rule 2 with within(usa, namerica) → within_recursive(usa, ...); rule 2 with within(idaho, usa) → within_recursive(idaho, 'North America').
  • Different thinking: less convenient for one-off queries, but rules combine and are reused, so it copes better with complex data.
stored facts derived facts name(namerica, 'N. America') within(usa, namerica) within(idaho, usa) within_recursive(namerica, 'N. America') within_recursive(usa, 'N. America') within_recursive(idaho, 'N. America') rule 1 rule 2 rule 2 each derived fact feeds the next rule application
Figure 2-6 simplified: repeated rule application proves Idaho is in North America.

Summary

  • History: data began as one big tree (hierarchical), which handled many-to-many poorly; the relational model solved that.
  • Some applications don't fit relational either. NoSQL diverged two ways:
    1. Document databases: self-contained documents, rare relationships between them.
    2. Graph databases: anything potentially related to everything.
  • Document, relational and graph are all widely used, each good in its domain. One can emulate another (graph in relational), but often awkwardly: no one-size-fits-all system.
  • Document and graph databases usually don't enforce a schema, easing change; but the app still assumes structure. The question is explicit (on write) or implicit (on read).
  • Each model has its query language or framework: SQL, MapReduce, MongoDB's aggregation pipeline, Cypher, SPARQL, Datalog; plus CSS and XSL/XPath as parallels.
  • Not covered: genome sequence-similarity search (GenBank), LHC-scale physics data (hundreds of petabytes, custom solutions), full-text search (Chapter 3, Part III).

Condensed from Designing Data-Intensive Applications by Martin Kleppmann (O'Reilly, 2017). Parts I-III (complete book), 12 chapters.