NoSQL databases
easy 26 minNoSQL is a family name for databases that do not use the relational model.
See it run
Four shapes of data, then what happens when the data has several copies.
Operations
Document
Insert JSON-like documents and query a field inside them.
Step 1 of 4
Insert a document
| document |
|---|
| name: Alice, age: 30 |
Alice is stored as one document with two fields. No table was declared.
Step 1: Insert a document
db.users.insertOne({name: "Alice", age: 30})db.users.insertOne({name: "Bob", age: 28, city: "Oslo"})db.users.find({age: {$gt: 25}})db.users.createIndex({age: 1})- Fast
- One whole record
- Slow
- Joins across records
Documents in one collection may have different fields. Readers must cope with that.
In the real world
The same nosql databases doing real jobs. Pick one and step through it.
Readings are keyed by date, so today's partition takes every write.
Step 1 of 3
Key by date
Every device writes to today's partition on Node A. B and C idle.
Step 1: Key by date
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Choosing the store before the questions
criticalThe model is fixed by the key. A new main question can mean rewriting all data.
Wrongtable: eventskey: ??? # decide laterRightquestion: last day of one devicekey: (device, day), sorted by timeA key with few values
criticalAll writes land on few machines.
Wrongpartition key = dateRightpartition key = (device, date)Two separate writes for two copies
majorThe second can fail, and nothing notices.
Wrongwrite(orders)write(orders_by_city) # may failRightwrite(orders)change stream -> orders_by_city# idempotent, with versionsAn unbounded partition or document
majorA list that grows for ever becomes slow and can hit a size limit.
Wronguser.events = [ ...every event... ]Rightevents keyed by (user, month)
Interview tips
How to explain it
- Four shapes, each for one kind of question.
- Data is arranged for reads and often copied.
- Copies bring consistency choices.
Memory trick: KDWG
- Kids Don't Want Greens.
- Key-value, Document, Wide-column, Graph.
- CAP: C or A while partitioned.
Reach for it when
- Writes exceed one machine and share a key.
- Records are uneven and read whole.
- Walks have unknown length.
Watch out for
- Hot keys.
- Copies without an owner.
- CP and AP labels without settings.