You need to store a profile like Bill Gates on LinkedIn. One profile has one name, many past jobs, many schools, and links to companies and other people. The choice you make now decides if reads are one lookup or many joins.
Key points
You must store user 251 with first name, last name, summary, region, industry, photo, positions, education, and contact info.
Numbered requirements:
The tension is locality versus linkage. Requirement (1) wants everything in one place. Requirements (2) and (3) want shared references. Requirement (4) wants easy evolution.
Operable: tap requirements to feel the pull. (1) pulls toward locality. (2) and (3) pull toward linkage. (4) sits in the middle.
Think in layers. Your objects sit on JSON or tables. That model sits on bytes on disk. Each layer hides the layer below.
Now think in shapes. A relation is an unordered set of rows. A document is a self contained tree. A tree fits a resume. A table fits a shared list.
Picture user 251 as a root with branches for positions and education. That is the document shape. Picture separate piles for users, positions, education, contact_info, regions, and industries linked by IDs. That is the relational shape.
Operable: switch shape. Same user 251, two physical pictures.
In the normalized relational form, you create users, positions, education, contact_info, regions, and industries. Each position row carries user_id 251. Region us:91 and industry 131 live once in their own tables.
Read path for one profile. Query users by user_id. Query positions by user_id. Query education by user_id. Query contact_info by user_id. Or do a messy multiway join. You then join region and industry IDs to get display names.
Write path for a rename. IDs never need to change. If Seattle changes its display name or you localize Philanthropy, you update one row. This breaks (2) if you instead copy plain text everywhere, because some copies update and others do not.
In JSON you store one document for user 251. Positions is an array with two entries. Education is an array with two entries. Contact info is a nested object with blog and twitter. Region and industry remain IDs.
Read path for one profile. One query returns the whole tree. This serves (1) well. Storage is one continuous encoded string in JSON, XML, or BSON.
Write path for a nested item. You cannot point directly to the second position. You must say the second item in positions for user 251. Updates usually rewrite the whole document. Only size preserving edits are easy in place.
Failure case. Add recommendations. User 467 writes a recommendation for user 251. The recommendation must show the author name and photo. If the author changes the photo, all shown copies must change. If you denormalize the photo into each recommendation, that breaks (3) on update. If you store a reference to user 467, you now need a join or follow up queries. Early document stores had weak join support. RethinkDB supported joins. MongoDB did not at the time of writing. CouchDB only supported joins in predeclared views. So you emulate the join in application code with extra round trips. That is slower and more complex.
Operable: press Run to replay the resume read for user 251. Count queries and joins.
4 queries + 1 join step
1 query, 0 joins
Operable: pick a photo strategy, then change the author photo and watch consistency versus query cost.
The hierarchical model in IBM IMS stored nested trees like JSON. It was good for one to many data. It made many to many hard. It had no joins. Developers either duplicated data or resolved references by hand.
The network model or CODASYL generalized the tree. A record could have multiple parents. That models many to one and many to many. Links were like stored pointers. The only access was an access path from a root by following chains.
The problem with access paths was rigidity. Query code moved a cursor record by record. Programmers tracked many paths in their heads. If you lacked a path, you rewrote query code. Adding a new access pattern meant rewriting the application.
The relational model laid data open as tables. You select rows by condition. You insert without fixing pointers first. Foreign keys are resolved at query time, not at insert time. This breaks the old rigidity, but it moves work to the query optimizer. The optimizer picks order and indexes once for all apps.
Lesson for today. Document stores returned to hierarchical nesting for one to many data. For many to one and many to many they use document references, which are IDs like foreign keys. That part is not fundamentally different from relational. The debate returns when data gets interconnected.
Operable: drag the era slider. Watch the same resume idea change shape.
An imperative query lists steps and order. A declarative query lists pattern and result shape. SQL follows relational algebra.
SELECT * FROM animals WHERE family = 'Sharks';
The database can move records, add an index, or parallelize across cores. The query still works. Imperative list code may depend on order and must be rewritten to use a new index. The same gap appears in browsers. CSS declares li.selected > p and the browser updates styling automatically. The JavaScript loop over li elements needs manual updates and misses automatic cleanup.
Price of declarative. The language is less general. You trust the optimizer. Optimizers took years of research. But you build it once and all apps benefit.
Operable: add an index and a core. See which code survives untouched.
SELECT * FROM animals WHERE family = 'Sharks'State: works before and after. Optimizer picks the new path.
for each animal in order: if family match, collectState: order dependent. Rewrite to use the index.
Schema on write means the database enforces structure. Schema on read means code assumes structure when reading. Document stores and JSON in relational systems often use schema on read. The term schemaless is misleading because readers still assume fields.
Change example for requirement (4). Split name into first_name and last_name.
Document style fix in application code:
if (user && user.name && !user.first_name) {
// Documents written before Dec 8, 2013 do not have first_name
user.first_name = user.name.split(" ")[0];
}Relational style fix with migration:
ALTER TABLE users ADD COLUMN first_name text; -- PostgreSQL variant (illustrative host, chapter grounded syntax): UPDATE users SET first_name = split_part(name, ' ', 1);
ALTER TABLE is milliseconds in most systems. MySQL at the time of writing copied the whole table, so large alters could take minutes or hours. UPDATE rewrites every row and is slow on large tables. The workaround is the same as documents. Leave NULL and fill at read time.
Price list. Schema on read helps when data is heterogeneous or controlled by outside systems. Schema on write helps when all records should share shape, because it documents and enforces the contract. Schema changes have a slow reputation that is only partly deserved.
Operable: size the users table, then compare full UPDATE versus lazy fill at read time for the name split.
blocking migration
UPDATE cost
long downtime risk
Documents win when you read most of the document together. They lose when you read a small slice of a large document, because the store loads the whole string. They lose on growing writes, because growth forces rewrite. Guidance from the field is keep documents small and avoid size increasing writes.
Locality is not unique to documents. Google Spanner can interleave child rows inside parent rows. Oracle has multi table index cluster tables. Cassandra and HBase use column families for similar locality. Relational systems added XML since the mid 2000s with indexing inside documents. PostgreSQL since version 9.3 and IBM DB2 since version 10.5 added JSON with query and index support. The models are converging toward a hybrid.
Operable: grow the document. The slice you need stays fixed, so waste grows.
Goal. Count shark sightings per month from an observations table or collection. Filter family equals Sharks. Group by month. Sum num_animals.
SELECT date_trunc('month', observation_timestamp) AS observation_month,
sum(num_animals) AS total_animals
FROM observations
WHERE family = 'Sharks'
GROUP BY observation_month;Notes on lines that matter. WHERE filters before grouping. date_trunc('month', ...) normalizes timestamps to month starts. GROUP BY plus sum aggregates. You do not name indexes or join order. The optimizer does.
db.observations.mapReduce(
function map() {
var year = this.observationTimestamp.getFullYear();
var month = this.observationTimestamp.getMonth() + 1;
emit(year + "-" + month, this.numAnimals);
},
function reduce(key, values) {
return Array.sum(values);
},
{
query: { family: "Sharks" },
out: "monthlySharkReport"
}
);Notes on lines that matter. query is declarative and MongoDB specific. map runs once per matching document and emits month string to count. Pairs group by key. reduce runs once per month key and sums. Output goes to monthlySharkReport. Functions must be pure. No extra queries. No side effects. That lets the system run and retry anywhere in any order.
Sample input to output. Two December 1995 shark documents with 3 and 4 animals emit ("1995-12", 3) and ("1995-12", 4). Reduce sees ("1995-12", [3, 4]) and returns 7.
Operable: play the worked trace for December 1995. Two docs in, one sum out.
Press Play. Map must stay pure so the system can run and retry anywhere.
Relational shredding needs users plus positions plus education plus contact_info plus regions plus industries. JSON nesting for user 251 is one object with arrays:
{
"user_id": 251,
"first_name": "Bill",
"last_name": "Gates",
"region_id": "us:91",
"industry_id": 131,
"positions": [
{"job_title": "Co-chair", "organization": "Bill & Melinda Gates Foundation"},
{"job_title": "Co-founder, Chairman", "organization": "Microsoft"}
],
"education": [
{"school_name": "Harvard University", "start": 1973, "end": 1975},
{"school_name": "Lakeside School, Seattle", "start": null, "end": null}
],
"contact_info": {
"blog": "http://thegatesnotes.com",
"twitter": "http://twitter.com/BillGates"
}
}Use this to rehearse aloud. State the read path for each model. State where the join lives.
Operable: filter by design motive. Each card keeps its why.
Rule from the chapter. Document like trees fit when you load the whole tree at once. Analytics event logs may never need many to many joins. Highly connected data favors relational as acceptable and graph models as most natural.
Consistency, one place update, localization, and search. Seattle implies Washington through the region table, not through the string. Plain text duplicates human meaning and breaks (2) on rename.
When you add many to many links like recommendations. You either denormalize and add consistency code, or emulate joins with multiple queries. That moves database work into the app and is usually slower.
No hand maintained access paths. Declare a new index and queries use it. The optimizer owns order and index choice. That serves fast feature change.
Pick schema on read for heterogeneous or externally controlled shapes. Pick schema on write when all records must share shape and you want enforcement and documentation. Both can do lazy migration at read time.
Declarative hides order and enables optimizer and parallel gains. MapReduce mixes declarative filter with user map and reduce functions, but restricts them to pure functions for flexible placement and retry.
Q1Predict. You store company name as plain text in every position. The company rebrands. What breaks? Cite the requirement number. What single schema change fixes it?
Some copies update and others do not, so Greater Seattle Area style renames fail. One row update via ID fixes (2). Plain text duplicates human meaning.
Q2Compare. Profile page load needs positions plus education plus contact info. Show the query count for shredded tables versus one JSON document. When would the JSON win shrink?
Shredded queries users, positions, education, contact_info plus joins for us:91 and 131. Nested returns the whole tree at once for (1). Slice reads load the whole string, so locality win fades.
Q3Choose under tradeoff. You must add recommendations where photo updates must appear everywhere, and you must ship fast with no downtime for a name split. Pick document reference versus denormalized copy for photos, and pick read time fill versus full UPDATE for names. Defend each pick by naming what breaks (1), (3), or (4) if you choose the other path.
Copies break (3) on photo change, all shown copies must change. Full UPDATE breaks (4) with slow rewrite on large tables. References need extra queries but stay correct, and lazy fill ships with no downtime.