Full-Text Indexes

Why a B-tree cannot serve this at all

SELECT * FROM docs WHERE body LIKE '%storage engine%';

A B-tree on body is useless here, and not by a small margin — the planner will not consider it. The index is ordered by the whole string from its first character, so a pattern with no fixed prefix offers no bound to seek to. It degrades to a sequential scan with a pattern match per row.

Three separate things break at once, and it is worth naming them separately because each one shapes a different part of the inverted index:

GranularityThe indexable unit is a word, not a row value — one row yields hundreds of keys
Cardinality directionA B-tree is best when a key names few rows; a term names very many, and the job is intersecting those sets
OrderingResults must come back by relevance — a number computed per query, in no order the index could be sorted in

The inverted index

three documents, and the index over them

docs
  1  "the quick brown fox"
  2  "the quick storage engine"
  3  "brown bear, brown fox"

term dictionary          postings   (docID, tf, [positions])
  bear      df=1         (3, 1, [3])
  brown     df=2         (1, 1, [3])  (3, 2, [1,4])
  engine    df=1         (2, 1, [4])
  fox       df=2         (1, 1, [4])  (3, 1, [5])
  quick     df=2         (1, 1, [2])  (2, 1, [2])
  storage   df=1         (2, 1, [3])

Positions are what make a phrase query possible: "storage engine" is the intersection of two posting lists followed by an adjacency check on the positions. They are also usually the largest component of the index — frequently larger than the doc-ID postings themselves — which makes dropping them (index_options: docs_and_freqs) the standard first lever when index size becomes a problem, at the cost of phrase search.

Three ways to store the term dictionary, and the choice is load-bearing:

  • Sorted array + binary search. Fine in memory; on disk it is a seek per probe.
  • A B-tree over terms. What PostgreSQL GIN does. Its leaf entry holds either a short posting list inline or, once the list outgrows what fits, a pointer to an entire posting tree — a second B-tree keyed by TID. So a common term and a rare term are stored in structurally different ways under the same index.
  • An FST (finite-state transducer). Lucene's. A minimal acyclic automaton mapping term → ordinal/offset, sharing both prefixes and suffixes. A million distinct terms compresses to a few megabytes and stays resident, so the dictionary lookup costs zero disk seeks. And because it is an automaton, it composes with other automata — which is the entire trick behind fuzzy search below.

Analysis is lossy, irreversible, and must be symmetric

The analysis pipeline for the sentence The Quick Brown Foxes were Running, with one column per token position, 1 to 6. Tokenize gives The, Quick, Brown, Foxes, were, Running. Lowercase gives the, quick, brown, foxes, were, running. Stopwords removes the at position 1 and were at position 5. Stem turns foxes into fox and running into run. The PostgreSQL tsvector is brown at 3, fox at 4, quick at 2, run at 6. Positions 1 and 5 are simply absent: removing a stopword does not renumber the tokens around it, which keeps phrase distance correct across the gap.
Analysis drops and rewrites tokens, but never renumbers them

Two consequences that people reliably get wrong:

It is irreversible

You cannot reconstruct the document from the index — the original casing, the stopwords, the unstemmed forms are all gone. Anything you intend to display must be stored separately (Lucene's stored fields, Elasticsearch's _source). "The index is the data" is false for full text in a way it is not for any index in Part II.

It must be symmetric

The same analysis runs over the query. Index running as run, then query for running un-stemmed, and you get zero hits — silently, with no error and a perfectly healthy-looking index.

Posting lists: compression, and intersection that isn't a merge

Doc IDs within a posting list are ascending, so store the gaps:

A posting list of ascending doc IDs, 12, 14, 19, 27, 28, 40, stored as gaps: 12, 2, 5, 8, 1, 12. Each gap is the difference from the previous doc ID. The largest raw ID, 40, needs 6 bits; the largest gap, 12, needs only 4 — small numbers compress.
Sorted doc IDs are stored as gaps — small numbers, few bits

Then either variable-byte encoding (one continuation bit per byte — simple, roughly one byte per small gap) or, in Lucene, FOR + PForDelta: take a fixed block of 128 doc IDs, find the bit width needed for the largest delta in that block, bit-pack all 128 at that width, and store the handful of outliers separately. A whole block decodes in a few dozen branch-free, SIMD-friendly instructions.

And layered over those blocks, a skip list: each block records its last doc ID, so advance(target) binary-searches the skip data and jumps straight to the right block without decoding any of the ones before it. That is the SSTables and sparse indexes part's sparse index, one layer up the stack — a static directory over a sorted immutable file, safe for exactly the same reason (the segment is never mutated).

why intersection is leapfrog, not merge

"the"            df = 98,000,000
"photosynthesis" df =     12,400

linear merge:   walk both lists in lockstep     → 98 M steps
leapfrog:       for each docID in the SHORT list, advance() the long one to ≥ it
                → ~12,400 advances, each a few skip-list hops

The cost of an AND is set by the RAREST term, not the commonest one.

For terms and filters dense enough that skipping stops paying, the posting list is materialised as a bitmap instead — Roaring bitmaps store dense chunks as bitsets and sparse chunks as sorted arrays, so an AND becomes a word-at-a-time loop. PostgreSQL does the same thing under different names: a long GIN posting list becomes a posting tree, and the executor builds a TID bitmap and switches to a Bitmap Heap Scan.

Scoring — and why the ranking formula dictates the file layout

score(q, d) = Σt ∈ q IDF(t) · f(t,d) · (k₁ + 1) ⁄ [ f(t,d) + k₁ · (1 − b + b · |d| / avgdl) ]

BM25. IDF(t) = ln(1 + (N − df(t) + 0.5) / (df(t) + 0.5)); k₁ ≈ 1.2 controls saturation, b ≈ 0.75 controls length normalization.

The formula is not the interesting part. Where each symbol has to come from is, because that is what determines the index's physical layout:

SymbolMeaningWhere it must be stored
f(t,d)term frequency in the documentIn every posting, next to the doc ID
df(t)how many documents contain the termIn the term dictionary entry
|d|document lengthA separate per-document norms file — quantized to one byte in Lucene
N, avgdlcorpus size and mean lengthPer-segment metadata

k₁ is what fixes classic tf-idf's runaway linearity: term frequency saturates, so the twentieth occurrence of a word contributes almost nothing over the tenth. b normalizes for length, so a 10,000-word page can't outrank a precise 200-word one by sheer volume.

The part that actually makes it fast: WAND and block-max WAND. A query matching 98 M documents does not score 98 M documents. Keep a heap of the current best k; keep, per term, an upper bound on the score it can possibly contribute; then any document whose maximum achievable score — the sum of the upper bounds of the terms it could match — falls below the current k-th best can be skipped without ever being scored. Block-max refines this by storing a per-block maximum in the skip data, so entire 128-document blocks are discarded at once.

This is why top-10 over hundreds of millions of documents returns in milliseconds — and it is also why full-text search is not composable with arbitrary sorting. Ask for the same query ordered by date instead of relevance and the entire skipping apparatus turns off: with no score threshold there is nothing to prune against, and the engine must genuinely enumerate every match. "Sort by newest" is a far more expensive feature than it looks on the UI.

The part that belongs in this guide: segments are SSTables

The write problem is severe. One 500-word document produces a couple of hundred distinct terms, scattered across the whole term space — indexing it in place would mean a couple of hundred random page updates per row. No in-place structure survives that. Lucene's answer:

  1. A document is analyzed into an in-memory buffer. It is not searchable yet.
  2. A refresh (every 1 s by default in Elasticsearch) turns the buffer into a new segment — a set of immutable files: term dictionary FST, postings, positions, norms, doc values, stored fields. Now it is searchable.
  3. A delete removes nothing. It clears a bit in that segment's liveDocs bitset. An update is a delete plus an insert into the newest segment.
  4. A search queries every segment and merges the per-segment results.
  5. Background merges — tiered by default — rewrite several segments into one, dropping deleted documents in the process.
  6. Durability is a separate translog, fsynced per request by default and replayed on restart — because a refresh is not a commit.
The Lucene write path in two lanes. Visibility lane: an analyzed document goes into an in-memory buffer, which is not yet searchable — the counterpart of a memtable. A refresh, every second by default in Elasticsearch, turns the buffer into a new immutable segment, the counterpart of an SSTable, and from that moment the document is searchable. Tiered merges rewrite several segments into one and drop deleted documents, the counterpart of compaction. Durability lane: the same document is appended to the translog, fsynced per request and replayed on restart, the counterpart of a WAL — durability, not visibility.
The Lucene write path is a memtable flush — except the flush is the moment of visibility
Lucene / ElasticsearchPart I equivalentWhere
In-memory indexing bufferMemtableMemtable, flush and ref-counting
SegmentSSTableSSTables and sparse indexes
RefreshMemtable flushMemtable, flush and ref-counting
liveDocs bit clearedTombstoneConcurrency, tombstones and compaction
MergeCompactionSee Concurrency, tombstones and compaction, Compaction strategies
Tiered merge policySize-tiered compactionCompaction strategies
TranslogWALWAL
Commit pointManifest update + fsyncMemtable, flush and ref-counting
Every segment queriedRead amplification ∝ file countSee Bloom filters, Numbers on disk

And because it is the same machine, it presents the same bills:

  • Read amplification — every query touches every segment. A shard sitting at 400 segments is slow for precisely the reason the Numbers on disk part's 1,500-SSTable table was slow.
  • Space amplification — deleted documents occupy disk until a merge rewrites their segment. Elasticsearch's deleted_docs is the Concurrency, tombstones and compaction part's tombstone bloat with a different name.
  • Write amplification — a document's postings are rewritten once per merge tier it passes through, exactly as the Compaction strategies part describes.
  • Visibility lag — the 1-second refresh interval is the price of not building a segment per document.

The one genuine difference is a sign flip on visibility. RocksDB's memtable is searchable and its flush is invisible to readers; Lucene's buffer is not searchable and its flush is the exact moment of visibility. Everything else is the same structure — which is why "why did search get slow" and "why did my LSM get slow" have the same answer (file count), the same fix (merge/compact harder), and the same cost for forcing it (a full rewrite of the data, _forcemerge being every bit as violent as a manual full compaction).

PostgreSQL GIN takes the other route — and reinvents the memtable anyway

GIN is a B-tree over terms and must be updated in place, so it hits the two-hundred-random-page-updates problem head on. Its answer is fastupdate = on (the default):

PostgreSQL GIN with fastupdate on. An INSERT appends to the pending list: append-only, unsorted pages off the metapage — a memtable in all but name. The pending list is flushed into the main GIN B-tree, which maps each term to an inline posting list or to a posting tree. The flush is done either by autovacuum, or synchronously by whichever backend’s INSERT pushes the list past gin_pending_list_limit, 4 MB. Every query must scan the unsorted pending list linearly as well as search the tree.
GIN’s pending list is a memtable bolted onto a B-tree

And it pays memtable-shaped costs for it. Every query must scan the pending list linearly — it is unsorted — in addition to searching the tree, so a large pending list slows reads; and the flush is a foreground stall aimed at one arbitrary transaction rather than backpressure applied evenly to all writers (see Memtable, flush and ref-counting). The symptom is a query or an INSERT that is normally 2 ms and occasionally 900 ms, with nothing in the plan to explain it.

Levenshtein automata — Lucene

fox~1 compiles the query term and its maximum edit distance into a DFA accepting every string within distance 1, then intersects that automaton with the term dictionary's FST. The walk yields the matching terms directly, at a cost proportional to the matched subtree rather than to the number of distinct terms. The naïve alternative — comparing the query against a million terms one at a time — is orders of magnitude slower, and is why the dictionary being an automaton rather than a sorted list matters.

Trigram indexes — pg_trgm

How PostgreSQL serves LIKE '%storage%' at all. Strings are decomposed into 3-grams (sto, tor, ora, rag, age, plus padded prefixes) and those are GIN-indexed. The pattern is decomposed the same way; the index returns rows containing all of its trigrams; and the executor then rechecks the real LIKE — because containing the trigrams does not prove containing the substring.

Note that the trigram path is structurally identical to the Multidimensional indexes part's MBR recheck: a cheap conservative approximation in the index, an exact and expensive confirmation outside it. Filter and refine is not a spatial technique or a text technique. It is what every index does once its keys stop being the values themselves.

Where Sections 20 and 21 converge

Both sections end at the same wall from opposite sides. The Multidimensional indexes part's exact box queries die somewhere around 10–20 dimensions, when MBRs overlap so thoroughly that pruning stops pruning. This part's lexical matching cannot retrieve a document that shares no token with the query — "car" will never find "automobile," no matter how good the analyzer is, because the index has no representation of meaning.

The modern answer to both is one structure: embed the object as a dense vector of 384–1536 dimensions and search it approximately — HNSW's navigable small-world graph, or IVF-PQ's coarse centroids over quantized residuals. Which means surrendering the one property every index in this guide has provided so far: the guarantee that it returns all the matches. That is why production retrieval is usually hybrid — BM25 for the cases where exactness is the requirement (a part number, an error string, a rare proper noun), ANN for semantic similarity, and the two ranked lists fused (reciprocal-rank fusion) rather than one chosen.

The Invariants

  • Guarantees: Given the same analyzer on both sides, the index returns every document containing the query's terms, ranked by a function that needs no access to the documents themselves — and top-k retrieval answers without scoring most of the matches.
  • Does not guarantee: Recoverability of the original text, stability across an analyzer change, or any match for what the analyzer normalized away. And the skipping that makes it fast applies only to relevance ordering — sort by anything else and every match must be enumerated.