Sub topic 10
Creating and querying an IVFFlat index
This chapter assumes you can run exact nearest-neighbor queries with ORDER BY embedding <-> ... LIMIT k. It also assumes you know why approximate search trades recall for speed. IVFFlat is the older of the two approximate index types in pgvector. It builds quickly and uses little memory, but it needs more care than HNSW.
How IVFFlat works
IVFFlat stands for "inverted file with flat compression". The name describes two steps:
- At build time, pgvector runs k-means clustering on the vectors already in the table. This produces
listscluster centers, called centroids. Each row is assigned to the list of its nearest centroid. - At query time, pgvector compares the query vector to every centroid and picks the
probesnearest lists. It then scans only the rows in those lists and sorts them by exact distance.
"Flat" means the stored vectors are not compressed, so distances inside the chosen lists are exact. The approximation comes only from skipping lists. If a true neighbor sits in a list you did not probe, the query misses it.
Build the index after loading data
The k-means step needs representative data. If you create the index on an empty or tiny table, the centroids are poor and recall suffers for the life of the index. The IVFFlat build is only as good as the data present when it runs. Load your data first, then create the index.
The example below creates a table, loads 10,000 random three-dimensional vectors, and builds an index.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE items (
id bigserial PRIMARY KEY,
content text NOT NULL,
embedding vector(3)
);
INSERT INTO items (content, embedding)
SELECT 'row ' || i, ARRAY[random(), random(), random()]::vector
FROM generate_series(1, 10000) AS i;
CREATE INDEX items_embedding_ivfflat
ON items USING ivfflat (embedding vector_l2_ops)
WITH (lists = 10);If the table has too few rows for the number of lists, PostgreSQL prints a notice such as ivfflat index created with little data. The notice means the index will give low recall. Drop it and rebuild once the table is larger.
Choose the number of lists
The pgvector documentation suggests these starting points:
| Table size | Starting value for `lists` |
|---|---|
| Up to about 1 million rows | rows / 1000 |
| Over 1 million rows | square root of rows |
The trade-off works like this:
- More lists means each list is smaller, so each probe scans fewer rows. Queries get faster. Recall drops unless you raise
probes, because neighbors are spread across more lists. - Fewer lists means bigger lists and slower queries. Recall is higher for the same
probes.
Treat the table's numbers as a starting point and measure recall (a later chapter covers this).
Query and set probes
Query-time behavior is controlled by ivfflat.probes, which defaults to 1. A single probe is fast but often misses neighbors. A common starting value is the square root of lists.
SET ivfflat.probes = 3;
SELECT id, content
FROM items
ORDER BY embedding <-> '[0.5,0.5,0.5]'
LIMIT 5;Use SET LOCAL inside a transaction when you want the value to apply to one query batch only. A plain SET lasts for the whole session. This matters with connection pools, where a session is reused by unrelated requests.
BEGIN;
SET LOCAL ivfflat.probes = 5;
SELECT id FROM items
ORDER BY embedding <-> '[0.5,0.5,0.5]'
LIMIT 5;
COMMIT;Setting probes equal to lists makes the query visit every list. The results are then exact, but you pay the cost of a full scan plus the centroid comparison. At that point the index gives no benefit.
Match the operator class
The index only helps a query whose operator matches the index's operator class. IVFFlat supports these:
| Query operator | Operator class |
|---|---|
| `<->` (L2 distance) | `vector_l2_ops` |
| `<=>` (cosine distance) | `vector_cosine_ops` |
| `<#>` (negative inner product) | `vector_ip_ops` |
An index built with vector_l2_ops is ignored by a <=> query. The query still runs, but as an exact sequential scan. This is a common reason for "the index doesn't work".
Check that the index is used
Run EXPLAIN to confirm the plan:
EXPLAIN
SELECT id FROM items
ORDER BY embedding <-> '[0.5,0.5,0.5]'
LIMIT 5;Look for Index Scan using items_embedding_ivfflat. If you see Seq Scan plus a Sort, the planner chose an exact scan. On small tables this is often correct, because a sequential scan is cheap. It can also point to an operator mismatch or a missing LIMIT.
Build cost and memory
IVFFlat builds faster and uses less memory than HNSW. Two settings affect the build:
maintenance_work_memshould be large enough to hold the vectors used for k-means sampling. If it is too small, PostgreSQL reports a notice with the memory it needs, and the build slows down.max_parallel_maintenance_workersallows a parallel build in recent pgvector versions.
SET maintenance_work_mem = '1GB';
SET max_parallel_maintenance_workers = 4;
CREATE INDEX items_embedding_ivfflat
ON items USING ivfflat (embedding vector_l2_ops)
WITH (lists = 10);Data changes and index drift
The centroids are computed once, at build time. New rows are added to the list of their nearest existing centroid, so inserts work immediately. But if the data's distribution changes later, for example after you load a large batch of different content or switch embedding models, the old centroids no longer fit. Lists become unbalanced and recall falls.
The fix is to rebuild. Use REINDEX INDEX CONCURRENTLY items_embedding_ivfflat; to avoid blocking writes. If you re-embed all rows with a new model, rebuild the index from scratch with the new data.
Filters
A WHERE clause on an approximate index is applied after the index returns candidates. If you probe 3 lists and the filter removes most of what they contain, you get fewer than LIMIT rows. This is not an error. Raise probes, or, with pgvector 0.8.0 or later, enable iterative scanning so the index keeps scanning more lists until it has enough rows:
SET ivfflat.iterative_scan = relaxed_order;
SET ivfflat.max_probes = 30;relaxed_order can return results slightly out of order, so re-sort if exact ordering matters.
IVFFlat or HNSW
| Concern | IVFFlat | HNSW |
|---|---|---|
| Build time and memory | Lower | Higher |
| Query speed at a given recall | Usually lower | Usually higher |
| Needs data present before building | Yes | No |
| Handles shifting data | Needs rebuilds | Better |
Choose IVFFlat when build time or memory is the limiting factor and your data is stable. Otherwise HNSW is usually the safer default.
Common mistakes
- Creating the index on an empty table, then wondering why recall is poor.
- Leaving
probesat 1 and accepting low recall. - Using
SETon a pooled connection and leaking the setting to other requests. - Indexing with one operator class and querying with another.
- Never rebuilding after the data changes substantially.
Exercise
A table has 500,000 rows. You build an IVFFlat index with vector_cosine_ops and lists = 500. Queries using ORDER BY embedding <-> q LIMIT 10 are slow, and EXPLAIN shows a sequential scan. What is wrong, and what starting value would you try for ivfflat.probes?
Show answer
The query uses <-> (L2), but the index uses vector_cosine_ops, which only serves <=>. Either query with <=> or rebuild the index with vector_l2_ops. A reasonable starting probes value is the square root of lists, so about 22 (round to 22 or 23), then adjust after measuring recall.