B-tree, hash and inverted indexes
An index is not one thing. A B-tree, a hash index and an inverted index each make one kind of question fast: ranges, exact matches, or words. Here is how each is laid out, and so what it can and cannot answer.
01 Three questions, three shapes
A shop's database gets three kinds of question all day. Each is fast with the right index and slow with the wrong one, because each index is built around one shape of question.
02 B-tree: keep the keys in order
A B-tree stores the keys sorted, in pages, with a few levels of pages above that point to ranges of keys. Finding one key is a walk from the top, one page per level. Because the bottom level is in order, every key between two values sits in one run, so the same walk answers ranges too.
- in the range
- first one past it
Find 12 by walking down the tree, read right until 31, stop. Ordering is what makes ranges, ORDER BY and prefix matches cheap.
This is why B-tree is the default in Postgres, MySQL's InnoDB and most other databases: it answers =, <, >, BETWEEN, ORDER BY and prefix matches, all from one structure. The price is a walk of a few pages per lookup, where a hash index typically reads about one bucket.
03 Hash: jump to one bucket
A hash index runs each key through a hash function and stores it in the bucket the result picks. To look a key up, hash it and read that one bucket. Two keys that collide share a bucket and are told apart by comparing them.
- bucket checked
- empty bucket
Hash 51ee, go to bucket 2, compare the two tokens there. On average, the cost does not grow with the table. But the buckets are in no useful order, so a range has nowhere to start.
A good hash function scatters keys on purpose: 12 and 13 land in unrelated buckets. That is what spreads the load, and it is also why a hash index cannot answer <, >, BETWEEN or ORDER BY. It knows about equality and nothing else.
04 Inverted: from words to documents
Neither of those helps with words. A B-tree on description sorts whole strings, so a word in the middle of one has no place in the order. An inverted index flips the data around: for each word, it stores the list of documents that contain it, called a posting list. Search engines are built on them, and in Postgres a GIN index over a tsvector is one.
| id | text | terms stored |
|---|---|---|
| 1 | fast red cars | fast red car |
| 2 | slow blue boats | slow blue boat |
| 3 | fast boats | fast boat |
| 4 | red bikes for sale | red bike sale |
| 5 | fast bikes | fast bike |
| 6 | fast boats for sale | fast boat sale |
Before storing, the text is split into terms, common words such as for are dropped, and words are reduced to a stem, so boats is stored as boat. A query for several words fetches each posting list and keeps the documents they share.
- looked up
- being compared
- on both lists
- just added
- not fetched yet
The query is fast boats. Postgres's English text search turns it into the terms fast and boat, the same way it turned every document into terms when the index was built. Nothing is looked up yet.
05 Which index answers what
| Query | B-tree | Hash | Inverted (GIN) |
|---|---|---|---|
| token = '51ee' | yes | yes | no |
| price BETWEEN 10 AND 30 | yes | no | no |
| ORDER BY price LIMIT 10 | yes, no sort needed | no | no |
| name LIKE 'ana%' | yes, with text_pattern_ops or C collation | no | no |
| doc @@ 'fast & boat' | no | no | yes |
| tags @> ARRAY['sale'] | no | no | yes |
06 Making each one in Postgres
On Postgres 16, the hash index is used for = and ignored for a range on the same column:
Bitmap Heap Scan on peopleRecheck Cond: (first_name = 'Jo'::text)-> Bitmap Index Scan on people_first_hashIndex Cond: (first_name = 'Jo'::text)
GatherWorkers Planned: 1-> Parallel Seq Scan on peopleFilter: ((first_name > 'Jo'::text)AND (first_name < 'Jp'::text))
A text-search index is only used when the query uses the same expression it was built on. Index to_tsvector('english', description) and then query to_tsvector(description) without the 'english', and Postgres will not match them.
07 When the wrong kind bites
WHERE name LIKE '%boat%'A wildcard at the startNo B-tree helps, and a word index only matches whole terms. For substrings, Postgres has the pg_trgm extension, which builds an inverted index over three-letter pieces.LIKE 'ana%' with en_US collationPrefix search ignoredUnder most collations, a plain B-tree is not used for LIKE. Build it with text_pattern_ops, or use the C collation.USING hash ... UNIQUEExpecting hash to do morePostgres hash indexes cover one column and cannot enforce uniqueness. Before Postgres 10 they were not crash-safe either, so old advice says to avoid them.UPDATE products SET description = ...Inverted indexes are dear to updateChanging one description touches the posting list of every word in it. GIN softens this by queueing new entries in a pending list, which makes some searches slower until it is merged.