8. SQL vs NoSQL
8.4 What kinds of NoSQL databases are there?
NoSQL databases
In the office: Not every record suits a ledger. A key cabinet where each hook has a tag, a folder cabinet with one folder per story, a logbook with one page per day that only ever gets new lines at the bottom, and a pinboard of photos connected by string.
In the system: "NoSQL" just means "not only SQL": databases that don't use the relational table model, usually to make one way of reading and writing very fast and very easy to spread across many machines. There are four main families.
Figure: each family is built around one way of asking for data.
8.4.1 Key-value stores
In the office: A wall of hooks with tags. You hand over a tag, you get what's on the hook. You can't ask "which hooks hold red keys?"
In the system: Store and fetch a value by its exact key. The database doesn't look inside the value. Extremely fast and easy to spread across machines (split by key). Examples: Redis, Memcached, DynamoDB (which adds more features). Bookstore use: cart:7 → {42: 2, 43: 1}, sessions, caches (Chapter 12).
8.4.2 Document stores
In the office: The folder cabinet: one folder holds a customer's whole story, and different folders can hold different kinds of papers.
In the system: Store documents, usually JSON-like, with nested fields and lists. Unlike key-value, the database understands the inside, so you can query and index fields (find books where tags contains "systems"). Each document can have a different shape. Examples: MongoDB, Couchbase, Firestore. Bookstore use: a product catalogue where a book, an e-book and a gift card each need different fields.
8.4.3 Wide-column stores
In the office: A logbook per day: new lines are only ever added at the bottom, and you read a whole day's page at once.
In the system: Data is grouped by a partition key, and inside each partition, rows are sorted by a clustering key. Built for huge write volumes spread across many machines, and for reading one partition's rows in order. You design tables around your queries, not around your entities. Examples: Cassandra, HBase, Google's Bigtable. Bookstore use: every page view and click, partitioned by book and day.
8.4.4 Graph databases
In the office: The pinboard with photos joined by string: "who knows whom" is right there to follow.
In the system: Store nodes (people, books) and edges (bought, follows, wrote) as first-class things, so following connections several hops out is fast. In a relational database, each hop is another join. Examples: Neo4j, Amazon Neptune. Bookstore use: "people who bought this also bought..." or spotting rings of fake accounts.
Memory code: "Hook, folder, logbook, pinboard." Key-value, document, wide-column, graph.