skip to content

In pgvector, when would you pick IVFFlat over HNSW, and why does an IVFFlat index built on an empty table have poor recall?

level: seniorimportance: should knowfreq 38%

answer

  1. graph versus clustered lists
  2. IVFFlat trains on existing rows
  3. lists at build, probes at query
  4. HNSW graph in maintenance_work_mem
  5. the little-data notice

basics

~20 s

pgvector's HNSW has the better speed-recall tradeoff but builds slower and uses more memory; IVFFlat builds faster and smaller. IVFFlat runs k-means on existing rows at build time, so an index built on an empty table has meaningless lists and poor recall.

solid answer

~50 s

HNSW builds a multilayer graph: better query speed at a given recall, no training step so it can be created on an empty table, but slower to build and larger, and fast only while the graph fits in `maintenance_work_mem` - past that pgvector logs `hnsw graph no longer fits into maintenance_work_mem` and the build slows sharply. IVFFlat samples the existing rows, runs k-means to choose `lists` centres (default 100) and searches `ivfflat.probes` of them per query (default 1). It builds faster with less memory, which suits a large table rebuilt often or a tight build window. Because the centres come from the rows present at build time, an index created on an empty or tiny table - pgvector emits `ivfflat index created with little data` - clusters badly; drop it and recreate it after loading. Start with `rows / 1000` lists up to 1M rows, `sqrt(rows)` beyond, and `sqrt(lists)` probes.

code

sql · 16 lines
sql
-- after the initial load of about 1M tickets
CREATE INDEX CONCURRENTLY support_tickets_embedding_ivf_idx
    ON support_tickets USING ivfflat (embedding vector_cosine_ops)
    WITH (lists = 1000);

-- from another session while the build runs
SELECT phase, tuples_done, tuples_total
FROM pg_stat_progress_create_index;

BEGIN;
SET LOCAL ivfflat.probes = 32;
SELECT id, subject
FROM support_tickets
ORDER BY embedding <=> (SELECT embedding FROM support_tickets WHERE id = 42)
LIMIT 10;
COMMIT;

go deeper

for a junior

Recall that pgvector offers HNSW and IVFFlat, and that an IVFFlat index must be built after the table has data.

for a middle

Explain lists, ivfflat.probes and their defaults, and why k-means at build time makes an empty-table IVFFlat index useless.

for a senior

Show you would pick the method from build window and memory, watch builds in pg_stat_progress_create_index, and plan IVFFlat rebuilds as data drifts.

for a principal

Frame index choice as an operating cost: rebuild cadence, build memory headroom and recall targets, revisited when the corpus or model changes.

## Two approximate index methods | | HNSW | IVFFlat | |---|---|---| | Structure | multilayer graph of neighbours | vectors grouped into `lists` around k-means centres | | Training | none; can be built on an empty table | k-means on a sample of existing rows at build time | | Build speed and memory | slower, more memory | faster, less memory | | Speed-recall tradeoff | better | lower | | Query knob | `hnsw.ef_search` (default 40) | `ivfflat.probes` (default 1) | | Build options | `m` (16), `ef_construction` (64) | `lists` (100, range 1-32,768) | | Types | `vector`, `halfvec`, `bit`, `sparsevec` | `vector`, `halfvec`, `bit` | HNSW is the usual choice for interactive search. IVFFlat earns its place when **build time or build memory** is the binding constraint: a large table rebuilt often, for example after switching embedding models, or a server where an HNSW build cannot get enough memory. ## IVFFlat's build, and the empty-table trap An IVFFlat build runs through these phases, visible in `pg_stat_progress_create_index`: 1. `initializing` 2. `performing k-means` - on a sample of the rows present now, to choose `lists` centres 3. `assigning tuples` - each row goes to its nearest centre 4. `loading tuples` - the lists are written to the index The centres come only from the rows present at build time. Create the index on an empty or tiny table - a habit carried over from B-tree indexes, which are often created before the data load - and pgvector emits `NOTICE: ivfflat index created with little data`, with the detail that this will cause low recall and the hint to drop the index until the table has more data. Later inserts are still indexed, but each one is filed under the nearest of the original, badly placed centres, so the lists stay unbalanced and a query that probes one list finds few true neighbours. The same mechanism makes recall drift as data changes: inserts never move the centres, so periodic rebuilds with `REINDEX INDEX CONCURRENTLY` are part of running IVFFlat on a changing table. ## Sizing lists and probes pgvector's starting points: - `lists`: `rows / 1000` for up to 1M rows, `sqrt(rows)` above that - 1,000 lists for 1M tickets, about 2,000 for 4M. - `ivfflat.probes`: `sqrt(lists)` - about 32 for 1,000 lists - set per query with `SET LOCAL`. - More probes raise recall and cost speed. Setting probes equal to `lists` searches every list, which is exact search, and the planner then will not use the index at all. - More lists make each list smaller and each probe cheaper, at a recall cost for the same number of probes. ## HNSW's build and memory HNSW needs no data to start, but its build is fast only while the whole graph fits in `maintenance_work_mem`. When it stops fitting, the build carries on with `NOTICE: hnsw graph no longer fits into maintenance_work_mem after N tuples` and the detail that building will take significantly more time - it does not fail. How large `maintenance_work_mem` can safely be on a given server is a memory-tuning question; pgvector's own warning is not to set it so high that it exhausts the server's memory. Other levers: - Load the data first, then build the index; it is faster than inserting into an existing graph. - Parallel workers (`max_parallel_maintenance_workers`, default 2) speed up builds of both index types. - Build with `CREATE INDEX CONCURRENTLY` on a live table so writes are not blocked. - Smaller elements - `halfvec`, or a binary-quantized expression index - shrink the graph so more of it fits. ## Choosing for a support-ticket corpus - A few million tickets, steady inserts, interactive similarity search: HNSW, built once and maintained incrementally. - Tens of millions of tickets re-embedded and rebuilt on a schedule within a tight window: IVFFlat, built after the load, with `ivfflat.probes` tuned against measured recall. - Either way, compare against an exact search before and after the switch; the right index is the one that meets the recall target within the latency and build budgets.

  • What happens if you set ivfflat.probes equal to the index's lists value?
    Every list is searched, so the result is exact; pgvector notes that the planner then will not use the index, since a scan does the same work more simply.
  • How do you follow a long pgvector index build?
    Query `pg_stat_progress_create_index` from another session. HNSW reports `initializing` then `loading tuples`; IVFFlat reports `initializing`, `performing k-means`, `assigning tuples` and `loading tuples`, and its `tuples_done` / `tuples_total` progress fills in only during `loading tuples`.
  • Why can a pgvector IVFFlat index lose recall months after it was built?
    Its centres are fixed at build time. New rows are filed under the nearest existing centre, so as the data drifts the lists grow unbalanced and probing a few of them misses neighbours. Rebuild periodically, for example with `REINDEX INDEX CONCURRENTLY`.

  • Create the IVFFlat index on the empty table so every row is indexed as it arrives
  • HNSW needs a training step, so it cannot be created on an empty table
  • Raising ivfflat.probes requires rebuilding the index
  • lists is a query-time setting you can change with SET
  • The hnsw graph no longer fits NOTICE means the index build failed