Notes

Part 7 of 10

Secondary indexes

So far each index mapped a key to a value, like a primary key index. A primary key names exactly one row, document, or vertex, and other records refer to it by that key. A secondary index, made in SQL with CREATE INDEX, lets you search by some other column. For example, an index on customer_id finds all orders for one customer. The big difference is that secondary keys repeat, since many orders share one customer. There are two common ways to handle that:

  • Each index entry holds a list of matching row IDs, like a postings list.
  • Each entry is made unique by adding the row ID to the end of the key.

Both B-trees and LSM-trees can store secondary indexes.

Storing values within the index

The index key is what queries search by. What sits next to the key can vary:

ChoiceWhat sits next to the key
Clustered indexThe whole row or document, inside the index itself
Reference by keyThe row's primary key, which is then looked up in the primary index
Reference to a heap fileThe row's location in a heap file, where rows are kept in no particular order
Covering indexA few chosen columns, plus a reference to the full row stored elsewhere

A heap file stores rows wherever there is room, either at the end or in space freed by deleted rows. A covering index (also called an index with included columns) can answer some queries by itself. If a query needs only the columns copied into the index, the database never opens the main row, and we say the index covers the query. The price is extra disk space and slower writes, since the copied data must be kept up to date.

With a heap file, a row can be updated in place if the new version is not bigger. If it grows, it must move. Then either every index is updated to point to the new spot, or a forwarding pointer is left at the old spot.

Keeping everything in memory

Everything above works around the quirks of disks, which force careful data layout. Disks are used because they keep data through power loss and cost less per GB than RAM. But RAM keeps getting cheaper and many datasets are small enough to fit, so in-memory databases are now practical, sometimes spread over several machines.

  • Some in-memory stores are only caches, where losing data on restart is fine.
  • Others stay durable using battery-backed RAM, a log of changes on disk, regular snapshots to disk, or copies on other machines.
  • After a restart they reload from disk or from another machine.
  • They still count as in-memory, because disk is only used as an append-only backup and all reads come from memory.

The surprising part is why they are fast. It is not mainly because they skip disk reads, since the operating system's file cache already keeps hot data in memory for a disk-based database. It is because they skip turning their in-memory structures into a disk format. Being in memory also makes some data models easy to offer that are hard on disk, like sorted sets or priority queues.