SENIORCHAPTER 20

Vector databases and ANN indexes

HNSW and IVFFlat in pgvector over the shop's product embeddings: recall against latency, build time and memory, the knobs that trade them, the filter that silently empties your results, and when Postgres stops being enough

55 MINAI ENGINEERINGUPDATED 2026-11-02
PREDICT

product_embeddings_big has 50,000 rows and an HNSW index with pgvector's defaults. About 2% of rows have category = 'software'. The planner uses the HNSW index for: SELECT id FROM product_embeddings_big WHERE category = 'software' ORDER BY embedding <=> $1 LIMIT 10. How many rows come back?

In the embeddings chapter you stored 5,000 product vectors and searched them with ORDER BY embedding <=> q LIMIT 5. There was no index. Postgres computed 5,000 cosine distances, sorted them and kept five. That is exact nearest-neighbour search, and its recall is perfect by construction. It is also linear: twice the rows, twice the work. At 5,000 rows of 768 dimensions that is 15 MB of vectors and a few milliseconds. At ten million rows it is 30 GB read per query.

An approximate nearest-neighbour (ANN) index gives up the guarantee. It returns rows that are probably among the nearest, in a time that grows far more slowly than the table. How probably, how much faster, how long the index takes to build and how much memory it needs are the four numbers this chapter is about, and the two index types in pgvector sit at different points on all four.

Recall is the number you are trading

Recall at k for one query is the share of the true k nearest neighbours that the index returned. Average it over a set of queries and you have the index’s recall. It is not the same number as retrieval recall in the RAG chapter, which asked whether the chunk with the answer was in the top k. An index with 0.95 recall at 10 misses, on average, half a true neighbour per query; whether that half-neighbour is the one holding the answer is a separate question. The two multiply: an index can only lose answers your embedding found.

Measuring index recall needs ground truth: the exact top k for each query. In Postgres you get it by turning the index off for one transaction:

BEGIN;
SET LOCAL enable_indexscan = off;   -- exact search: a sequential scan and a sort
SELECT id FROM product_embeddings_big ORDER BY embedding <=> $1 LIMIT 10;
COMMIT;

There is a trap in comparing ids. Catalogue data is full of near-duplicates (the same product in three sizes, the same text with a different number), and two vectors at the same distance from the query are equally correct answers. If the exact search returns one and the index returns the other, an id comparison counts a miss that is not a miss. ANN-Benchmarks, the standard benchmark for these indexes, counts a returned neighbour as correct if its distance is no greater than the distance of the k-th true neighbour plus 0.001. The lab’s harness uses the same rule.

HNSW: a graph you descend

Hierarchical Navigable Small World graphs (Malkov and Yashunin, 2016) are the index most vector databases default to, and pgvector has had one since version 0.5.0. The structure is a stack of proximity graphs. The bottom layer contains every vector, each linked to a few of its near neighbours. Each layer above contains a random subset of the one below, thinning out exponentially, as in a skip list. A search enters at the top layer, walks greedily towards the query until no neighbour is closer, drops a layer, and repeats. The upper layers cover long distances in few hops; the bottom layer refines.

layer 2layer 1layer 0 (all rows)queryentry pointdashed: greedy descent; layer 0 keeps the ef_search best candidates

Three knobs control it, and pgvector’s defaults are worth knowing by heart:

Knob Where Default What it buys What it costs
m WITH (m = 16) at build 16 links per node per layer; more links, fewer dead ends, better recall memory and build time grow roughly in proportion
ef_construction WITH (ef_construction = 64) at build 64 candidates considered when linking a new node; a better-connected graph build time
hnsw.ef_search SET hnsw.ef_search = 100 per query 40 candidates kept during a search; better recall query latency, roughly linear

ef_search is the one you tune in production, because it needs no rebuild: set it per session or per transaction with SET LOCAL. It also caps the result: an HNSW scan returns at most ef_search rows, so a LIMIT 100 with the default of 40 returns 40. The other two are fixed when you build; changing them is a REINDEX.

Build time and memory are HNSW’s costs. Every insert searches the graph to find its neighbours, so building is a search per row: minutes for a few hundred thousand 768-dimensional vectors on a laptop, hours for tens of millions. Builds are far faster when the whole graph fits in maintenance_work_mem, which defaults to 64 MB in Postgres. When it stops fitting, pgvector says so: NOTICE: hnsw graph no longer fits into maintenance_work_mem after 17000 tuples, with the detail ‘Building will take significantly more time’. Raise it for the session that builds (SET maintenance_work_mem = '2GB'), within what the server can spare. You can also raise max_parallel_maintenance_workers (2 by default), though the planner decides whether a given build runs in parallel.

The index stores each vector in full plus its neighbour lists, so for 768 float32 dimensions it is about the size of the table: roughly 4 KB per row, 4 GB per million rows. For query latency it must stay in memory; a search touches a few hundred pages scattered across the index, and if those come from disk each costs a random read. HNSW also needs no training step, so you can create it on an empty table and insert afterwards, at the price of every insert paying a graph search.

IVFFlat: cells you probe

IVFFlat (an inverted file of flat, uncompressed vectors) takes the older approach, the one FAISS made standard. At build time it runs k-means on the table to find lists centroids, then files every vector under its nearest centroid. A query compares itself with all centroids, picks the ivfflat.probes nearest lists, and scans those lists exactly.

Knob Where Default Starting point from the pgvector README
lists WITH (lists = 50) at build none; you choose rows / 1000 up to 1M rows, sqrt(rows) above
ivfflat.probes SET ivfflat.probes = 10 per query 1 sqrt(lists)

Its virtues are build speed and simplicity: k-means plus one pass, typically ten or more times faster than HNSW on the same table. Its weaknesses follow from the same design. The centroids come from the data present at build time, so an index built on an empty or half-loaded table has poor centroids, and rows inserted later are filed under centroids that no longer describe the distribution; recall drifts down until you rebuild. A query near the border of two cells misses neighbours in the cell next door unless you probe more, and each extra probe scans another 1/lists of the table. When probes gets large enough, the planner decides a sequential scan is cheaper and stops using the index altogether; at probes = lists that is guaranteed, and in the lab it happens well before.

The pgvector README sums up the comparison: HNSW ‘has better query performance than IVFFlat (in terms of speed-recall tradeoff), but has slower build times and uses more memory.’ Default to HNSW. Pick IVFFlat when you rebuild often from a static snapshot and build time dominates, or when you are memory-constrained in a way that HNSW’s neighbour lists push over the edge.

Filtered search: where most production bugs are

Real queries have a WHERE. Products in stock, documents this tenant may read, chunks from this year. The three ways Postgres can answer a filtered nearest-neighbour query behave very differently.

Index scan, then filter. The ANN index produces candidates in distance order and the executor applies the filter. This is the Predict’s failure. With HNSW the candidates stop at ef_search; the README’s own example is that a condition matching 10% of rows leaves about 4 of the default 40. The query returns fewer rows than its LIMIT and nothing tells you. The pgvector FAQ lists it under ‘Why are there less results for a query after adding an HNSW index?’

Iterative index scans (pgvector 0.8.0 and later) fix this by continuing the scan when too few rows survive. They are off by default:

SET hnsw.iterative_scan = relaxed_order;   -- or strict_order; ivfflat.iterative_scan likewise
SET hnsw.max_scan_tuples = 20000;          -- the default ceiling on tuples visited

strict_order guarantees results in exact distance order; relaxed_order allows slight disorder and gets better recall, and you can restore order with a materialised CTE that re-sorts the relaxed results (the README shows the pattern; on Postgres 17 the outer ORDER BY needs distance + 0). The scan stops at hnsw.max_scan_tuples (20,000 by default) or, for IVFFlat, ivfflat.max_probes. A filter that matches 0.01% of a ten-million-row table needs about 100,000 tuples to find ten matches, so it hits the ceiling and comes back short; that query wants a different plan.

Filter first, then exact search. A B-tree on the filter column lets Postgres fetch the matching rows and compute their distances exactly. For selective filters this is both faster and perfect: 2% of 50,000 rows is 1,000 distance computations, well under a millisecond of arithmetic. The README’s first advice on filtering is this one, and pgvector 0.8.0 changed the cost estimates so the planner prefers it more often when it is the better plan. Check with EXPLAIN: a Bitmap Heap Scan on the filter index followed by a sort is exact search, and an Index Scan using ..._hnsw is approximate.

For a filter with a few distinct values, a partial index per value (CREATE INDEX ... USING hnsw (embedding vector_cosine_ops) WHERE category = 'software') gives each value its own graph; for many values, partitioning the table by the filter column does the same at scale. Multi-tenant systems usually end up with a mix: exact search for small tenants, an ANN index for large ones.

Memory is the constraint that decides the architecture

Write the arithmetic down before you choose. A 768-dimensional float32 vector is 3,072 bytes. A million of them is 3 GB of table and roughly another 3 to 4 GB of HNSW index; ten million is 60 to 70 GB. The working set must fit in RAM for the latencies in this chapter, so the question ‘can Postgres do this?’ is mostly ‘does this fit on one machine, alongside everything else the database does?’

pgvector offers three levers, in increasing order of what they give up:

Lever How Index size for 768 dims Recall cost
half precision expression index on (embedding::halfvec(768)) with halfvec_cosine_ops; query with the same cast about half usually negligible for retrieval embeddings; measure
fewer dimensions a Matryoshka model truncated to 256 dimensions, as in the embeddings chapter one third a few points of retrieval quality
binary quantisation index binary_quantize(embedding)::bit(768) with bit_hamming_ops, fetch 100 candidates, re-rank by the full vectors about 1/32 for the vectors large before re-ranking; small after, if the candidate pool is big enough

All three keep the full-precision column in the table, so the final ordering can always be exact over a candidate set. The README also notes that HNSW indexes on vector support up to 2,000 dimensions and on halfvec up to 4,000, which matters for 3,072-dimensional models: you cannot index them as vector at all.

Two operational costs remain. Deleting or updating many rows leaves dead tuples in the graph, and vacuuming an HNSW index is slow; the README’s advice is to reindex first (REINDEX INDEX CONCURRENTLY, then VACUUM). And an index build on a large table is a long, memory-hungry operation you schedule, not something that happens in a migration at deploy time.

When Postgres is enough, and when it is not

The case for keeping vectors in Postgres is everything around the vectors. The embedding lives in the same row as the product, so a search joins to price, stock and permissions in one query, inside one transaction, with one backup, one access-control model and one thing to operate. Filters are SQL. The data you embed is the data you already have, so there is no second copy to keep in sync. For most applications (a support corpus, a catalogue, a few million chunks) this is the right answer, and the lab’s numbers show why: a millisecond per query at recall above 0.95 on a laptop.

The case for a dedicated vector database (Qdrant, Milvus, Weaviate, Vespa, Pinecone and others) starts where those advantages run out:

  • Scale beyond one node’s memory. Hundreds of millions of vectors need sharding. Postgres can shard with Citus or similar, but vector-first systems do it natively and add disk-resident indexes (the DiskANN family) and built-in quantisation that keep costs down when the index cannot live in RAM.
  • A search workload that must scale separately from the transactional one. An HNSW scan is CPU-heavy; a few hundred queries per second of it on the primary competes with checkout. Read replicas help, up to a point.
  • Filtering built into the graph traversal. Some engines apply filters during the graph walk rather than after it, which handles very selective filters that iterative scans in pgvector cannot.
  • Features you would otherwise build: native hybrid search with BM25, multi-vector representations, per-tenant isolation at large tenant counts.

The cost is a second system: ingestion that keeps it consistent with the source of truth, another set of credentials and backups, and joins that now happen in your application. Teams that move early often move back. Move when a measurement says one of the bullets above is true for you, not before.

LAB Measure HNSW and IVFFlat on the product embeddings ~55 MIN
YOU NEEDDocker with labs/databases running and the vector extension enabledproduct_embeddings filled with 5,000 products by embed.py from the embeddings chapterthe labs/ai uv project with psycopg (added in the embeddings chapter)about 1 GB of free disk inside Docker for the 50,000-row table and its indexes

Five thousand rows are too few to see an index matter. You will grow the table to 50,000 rows from your real embeddings, then measure exact search, HNSW at several settings, filtered search, half precision and IVFFlat with one harness. No model calls, no API cost. Work in labs/ai/embeddings/ (cd labs/ai/embeddings from the root of your checkout).

1. Grow the table. product_embeddings_big holds your 5,000 real vectors followed by jittered copies of them: each copy is a real vector plus small uniform noise, re-normalised, and keeps its source product’s category. It also creates 200 query vectors near real products but equal to none of them. Create grow.sql:

-- product_embeddings_big: the real vectors, then jittered copies of them, :n rows in all.
-- Each copy keeps its source product's category, so filtered search has something to filter on.
DROP TABLE IF EXISTS product_embeddings_big, bench_queries;
CREATE TABLE product_embeddings_big (
  id         bigint PRIMARY KEY,
  product_id bigint NOT NULL,
  category   text   NOT NULL,
  embedding  vector(768) NOT NULL
);
INSERT INTO product_embeddings_big (id, product_id, category, embedding)
SELECT g.i, s.product_id, p.category,
       CASE WHEN g.i <= s.cnt THEN s.embedding
            ELSE l2_normalize(s.embedding + (SELECT array_agg((random() - 0.5) * 0.035)
                                             FROM generate_series(1, 768) WHERE g.i > 0)::vector(768))
       END
FROM generate_series(1, :n) AS g(i)
JOIN (SELECT product_id, embedding,
             row_number() OVER (ORDER BY product_id) AS rn,
             count(*) OVER () AS cnt
      FROM product_embeddings) s
  ON s.rn = 1 + (g.i - 1) % (SELECT count(*) FROM product_embeddings)
JOIN products p ON p.id = s.product_id;

-- 200 query vectors near real products but not equal to any stored row.
CREATE TABLE bench_queries AS
SELECT row_number() OVER () AS qid,
       l2_normalize(embedding + (SELECT array_agg((random() - 0.5) * 0.07)
                                 FROM generate_series(1, 768) WHERE product_id > 0)::vector(768)) AS embedding
FROM (SELECT product_id, embedding FROM product_embeddings ORDER BY random() LIMIT 200) r;

ANALYZE product_embeddings_big, bench_queries;
SELECT count(*) AS rows, pg_size_pretty(pg_total_relation_size('product_embeddings_big')) AS size
FROM product_embeddings_big;
docker compose -f ../../databases/compose.yaml exec -T db psql -U atlas shop -v n=50000 < grow.sql
INSERT 0 50000, SELECT 200, then about 50000 | 205 MB after a few seconds. The WHERE g.i > 0 inside the noise subquery looks pointless; it makes the subquery depend on the outer row, so Postgres runs it once per row instead of once for the whole statement, and every copy gets its own noise. The noise is small (a cosine of about 0.96 between a product and its copy), so this table is easier for an index than a real 50,000-product catalogue would be: treat the recall numbers below as an upper bound and the method as the thing you keep.

2. The harness. bench.py runs the 200 queries once as an exact scan to get the truth, then once per setting you sweep, and prints recall at 10, the mean number of rows returned, p50 and p95 latency, and the plan Postgres chose. Create it:

"""Recall@10 and latency of nearest-neighbour search on product_embeddings_big."""
import argparse, os, statistics, time
import psycopg

DSN = os.environ.get("SHOP_DSN", "postgres://atlas:atlas@localhost:5432/shop")
K = 10
SQL = ("SELECT id, embedding <=> %(q)s::vector AS d FROM product_embeddings_big {where} "
       "ORDER BY {expr} LIMIT %(k)s")
EXPR = {"vector": "embedding <=> %(q)s::vector",
        "halfvec": "embedding::halfvec(768) <=> %(q)s::halfvec(768)"}

def search(conn, queries, where, params, expr=EXPR["vector"]):
    """Run every query once; return per-query latencies (ms) and result distances."""
    sql, lat, out = SQL.format(where=where, expr=expr), [], []
    for q in queries:
        t = time.perf_counter()
        rows = conn.execute(sql, {"q": q, "k": K, **params}).fetchall()
        lat.append((time.perf_counter() - t) * 1000)
        out.append([d for _, d in rows])
    return lat, out

def recall(truth, got):
    """ann-benchmarks' definition: a result counts if it is no further than the k-th
    true neighbour plus 1e-3, so near-duplicate vectors at equal distance are not misses."""
    total = 0.0
    for t, g in zip(truth, got):
        if not t:
            continue
        thr = t[min(K, len(t)) - 1] + 1e-3
        total += sum(d <= thr for d in g[:K]) / min(K, len(t))
    return total / len(truth)

def plan(conn, where, params, q, expr):
    rows = conn.execute("EXPLAIN (COSTS OFF) " + SQL.format(where=where, expr=expr), {"q": q, "k": K, **params})
    return next((r[0].strip(" ->") for r in rows if "Scan" in r[0]), "?")

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--set", default="", help="a GUC to sweep, e.g. hnsw.ef_search=10,40,160")
    ap.add_argument("--also", nargs="*", default=[], help="fixed GUCs, e.g. hnsw.iterative_scan=relaxed_order")
    ap.add_argument("--category", help="filter: WHERE category = this")
    ap.add_argument("--halfvec", action="store_true", help="order by the halfvec expression")
    a = ap.parse_args()
    expr = EXPR["halfvec" if a.halfvec else "vector"]
    where, params = ("WHERE category = %(c)s", {"c": a.category}) if a.category else ("", {})
    with psycopg.connect(DSN, autocommit=True, prepare_threshold=None) as conn:
        queries = [r[0] for r in conn.execute("SELECT embedding::text FROM bench_queries ORDER BY qid")]
        conn.execute("SET enable_indexscan = off")            # exact answers: a full scan
        lat, truth = search(conn, queries, where, params)
        print(f"{'exact':34} recall 1.000  rows {statistics.mean(map(len, truth)):5.1f}  "
              f"p50 {statistics.median(lat):6.1f} ms  p95 {statistics.quantiles(lat, n=20)[18]:6.1f} ms")
        conn.execute("RESET enable_indexscan")
        for kv in a.also:
            name, value = kv.split("=")
            conn.execute(f"SET {name} = '{value}'")
        name, values = a.set.split("=") if a.set else ("", "-")
        for v in values.split(","):
            if name:
                conn.execute(f"SET {name} = {v}")
            search(conn, queries[:20], where, params, expr)          # warm the cache
            lat, got = search(conn, queries, where, params, expr)
            label = f"{name}={v}" if name else "defaults"
            print(f"{label:34} recall {recall(truth, got):.3f}  rows {statistics.mean(map(len, got)):5.1f}  "
                  f"p50 {statistics.median(lat):6.1f} ms  p95 {statistics.quantiles(lat, n=20)[18]:6.1f} ms  "
                  f"{plan(conn, where, params, queries[0], expr)}")

if __name__ == "__main__":
    main()
uv run bench.py
Two lines, both with recall 1.000 and the plan Seq Scan on product_embeddings_big: with no index, ‘approximate’ search is exact search. Note the p50, typically tens of milliseconds and up to about 100 ms in Docker on a laptop, most of it reading 150 MB of vectors (they are stored out of line in TOAST, since each is 3 KB). That is your baseline. prepare_threshold=None stops psycopg preparing the statement after five runs, so every query is planned with its real parameters, as your application’s would be.

3. Build HNSW with the defaults, and watch it run out of memory.

docker compose -f ../../databases/compose.yaml exec -T db psql -U atlas shop <<'SQL'
\timing on
SHOW maintenance_work_mem;
CREATE INDEX product_embeddings_big_hnsw ON product_embeddings_big
  USING hnsw (embedding vector_cosine_ops);
SELECT pg_size_pretty(pg_relation_size('product_embeddings_big_hnsw')) AS index_size;
SQL
64MB, then NOTICE: hnsw graph no longer fits into maintenance_work_mem after some 17,000 tuples, the detail ‘Building will take significantly more time’, and a build time of a few minutes. The index is about 200 MB: as large as the vectors themselves, because it stores them. Note the time; you are about to beat it.

4. Rebuild with enough memory.

docker compose -f ../../databases/compose.yaml exec -T db psql -U atlas shop <<'SQL'
\timing on
DROP INDEX product_embeddings_big_hnsw;
SET maintenance_work_mem = '512MB';
CREATE INDEX product_embeddings_big_hnsw ON product_embeddings_big
  USING hnsw (embedding vector_cosine_ops);
SQL
No notice, and a build two to four times faster than step 3; on a laptop, around a minute. SET applies to this session only, which is how you want it: a 512 MB allowance on every maintenance operation in a busy production database is a way to run out of memory. On a real server you size it to the graph (about 4 KB per 768-dimensional row) and set it in the session that builds.

5. Sweep ef_search.

uv run bench.py --set hnsw.ef_search=10,20,40,80,160,400
The plan switches to Index Scan using product_embeddings_big_hnsw, and p50 falls to around a millisecond: one to two orders of magnitude below exact search. Recall climbs with ef_search, from somewhere between 0.85 and 0.99 at 10 to 0.98 or more at 40, and flattens near 1.0 above that, while latency keeps rising roughly in proportion. The useful row is the knee: the smallest ef_search whose recall you can live with. That number is per dataset; on your real corpus you would measure it with real queries the same way.

6. Filtered search: overfiltering, iterative scans, and the plan that beats both. Pick a rare category and a common one:

docker compose -f ../../databases/compose.yaml exec -T db psql -U atlas shop -c \
  "SELECT category, count(*), round(100.0 * count(*) / sum(count(*)) OVER (), 1) AS pct
   FROM product_embeddings_big GROUP BY 1 ORDER BY 2 LIMIT 3;"

Use the rarest category from that list in place of software below. The planner may prefer a sequential scan for a rare filter, which would hide the problem, so the first run forbids it:

uv run bench.py --category software --also enable_seqscan=off \
  --set hnsw.iterative_scan=off,relaxed_order,strict_order
With iterative_scan=off the rows column shows the bug: about one row per query instead of ten, and recall to match, because the 40 candidates mostly fail the filter. With relaxed_order the rows column returns to 10.0 and recall rises sharply, at a few milliseconds per query. strict_order also returns ten rows, sometimes with lower recall than relaxed; the README recommends relaxed for recall and a re-sorting CTE when order matters.

Now give the planner the option the README recommends first, an index on the filter column, and let it choose freely:

docker compose -f ../../databases/compose.yaml exec -T db psql -U atlas shop -c \
  "CREATE INDEX product_embeddings_big_category ON product_embeddings_big (category); ANALYZE product_embeddings_big;"
uv run bench.py --category software --also hnsw.iterative_scan=relaxed_order
The plan is Bitmap Heap Scan on product_embeddings_big: fetch the rare category’s rows through the B-tree, compute their distances exactly, sort. Recall is 1.000 and latency is a millisecond or two. For a selective filter, exact search over the filtered rows beats any approximate index. Re-run with your most common category and see whether the planner switches back to the HNSW index; whichever it picks, the harness tells you what it cost in recall.

7. Half precision.

docker compose -f ../../databases/compose.yaml exec -T db psql -U atlas shop <<'SQL'
\timing on
SET maintenance_work_mem = '512MB';
CREATE INDEX product_embeddings_big_hnsw_half ON product_embeddings_big
  USING hnsw ((embedding::halfvec(768)) halfvec_cosine_ops);
SELECT relname, pg_size_pretty(pg_relation_size(oid)) FROM pg_class
WHERE relname LIKE 'product_embeddings_big_hnsw%';
SQL
uv run bench.py --halfvec --set hnsw.ef_search=10,40
The halfvec index is half the size of the float32 one (about 100 MB against 200 MB), and the harness, which still reports each result’s full-precision distance, shows recall within a point or so of step 5. The query has to order by exactly the indexed expression, embedding::halfvec(768) <=> q::halfvec(768), or the planner cannot use the index; the --halfvec flag switches to that expression. At a million rows this is the difference between 4 GB and 2 GB of index to keep in memory.

8. IVFFlat. Drop both HNSW indexes so the planner cannot pick them, build IVFFlat with the README’s starting point of rows / 1000 lists, and sweep probes:

docker compose -f ../../databases/compose.yaml exec -T db psql -U atlas shop <<'SQL'
\timing on
DROP INDEX product_embeddings_big_hnsw, product_embeddings_big_hnsw_half;
CREATE INDEX product_embeddings_big_ivf ON product_embeddings_big
  USING ivfflat (embedding vector_cosine_ops) WITH (lists = 50);
SELECT pg_size_pretty(pg_relation_size('product_embeddings_big_ivf'));
SQL
uv run bench.py --set ivfflat.probes=1,3,7,15,30
The build takes seconds where HNSW took a minute or more, and the index is about the size of the vectors again. On this clustered data recall may already be high at probes=1, but compare latency at equal recall: each probe scans a fiftieth of the table exactly, so IVFFlat needs several times HNSW’s latency to reach the same recall, and the cost rises in proportion with probes. Watch the plan column: at some probe count the planner decides a sequential scan is cheaper and switches to Seq Scan, with recall 1.000 and exact-search latency. That is the README’s warning about high probe counts, arriving well before probes = lists.
Build the IVFFlat index before the data arrives, as a migration that creates the table and its indexes up front would. Drop product_embeddings_big_ivf, then in one transaction rename the table to pe_full, run CREATE TABLE product_embeddings_big (LIKE pe_full INCLUDING ALL), create the IVFFlat index on the empty table, and INSERT INTO product_embeddings_big SELECT * FROM pe_full. Postgres prints NOTICE: ivfflat index created with little data and ‘This will cause low recall’, and the probes sweep shows it: recall at probes=1 falls to around 0.3, because every centroid was computed from no data and the rows are filed under meaningless cells. Nothing else warns you; the queries are fast and return ten rows each. Rebuild the index (REINDEX INDEX product_embeddings_big_ivf) and recall comes back. HNSW has no training step and does not suffer this, but it has its own build-time trap: rebuild it WITH (m = 4, ef_construction = 16) and recall at ef_search=40 drops sharply, because a node with four links has too few routes to its true neighbours for a larger candidate list to recover. The knobs you set once, at build, cap what the knob you tune at query time can buy back.
ARTEFACT Write the vector index decision record ~45 MIN
YOU PRODUCEA vector index configuration decision record

Template

# Decision record: vector index for <search feature>
Owner <engineer, team>. Approver <role>. Date <date>. Status <proposed | accepted>.

## 1. Decision needed
<which index, on which table, by when, and what happens if we do nothing>

## 2. What was measured
Table <rows, size>. Queries <count, how chosen>. Truth <exact scan, recall rule>.
| Option | Recall at 10 | Rows returned | p50 / p95 | Index size | Build time |
Filtered queries: <filter, share of rows, recall with and without iterative scans>

## 3. Chosen index and parameters
<index type, operator class, m, ef_construction, ef_search, maintenance_work_mem>
Why, and why not the others: <one line each>

## 4. Re-index plan
Who <role>. When <window>. How <steps, memory setting, concurrent build>.
Checked by <recall sample>. Rollback <what stays in place until the new index passes>.

## 5. How this could be wrong
<one way, and what would show it>

## 6. Trigger to revisit
<measured threshold or event, who watches it, how often>

## 7. Out of scope
<what this record does not decide>
WORKED EXAMPLE

A search engineer on the shop’s team writes this record; the head of engineering approves it. Figures come from the lab’s expected outputs, where the chapter gives a range; the exact values are what your own run prints.

Decision needed. Approve an HNSW index on product_embeddings_big (50,000 rows, about 205 MB) before search ships. Without one, every query is an exact scan: a p50 of tens of milliseconds, up to about 100 ms.

Measured.

Option Recall at 10 p50 Index size Build
Exact scan 1.000 tens of ms none none
HNSW, ef_search 40 0.98 or more about 1 ms about 200 MB about a minute at 512 MB
HNSW on halfvec within a point of that about 1 ms about 100 MB not given; time yours
IVFFlat, lists 50 varies with probes several times HNSW’s about the vectors’ size seconds

A filter on the rarest category returned about 1 row per query with iterative scans off, and 10.0 with relaxed_order.

Chosen. HNSW on halfvec (halfvec_cosine_ops), m 16, ef_construction 64, hnsw.ef_search 40, hnsw.iterative_scan = relaxed_order, and a B-tree on category so the planner can run rare filters as exact search.

Re-index. The search engineer rebuilds with maintenance_work_mem set to 512 MB in the session that builds, keeps the old index in place, and drops it only once a 200-query recall sample meets the threshold below. Assumed: a monthly window.

Could be wrong. The table is jittered copies, so recall is an upper bound. A recall sample on real queries below the figure above would show it.

Revisit. Sampled recall under 0.95 (assumed), or the index no longer fitting in memory.

Out of scope. Choosing a dedicated vector database.

Now you

You are a search engineer at Ojaline, the online marketplace that delivers in 9 cities. Its search team runs semantic product search on an HNSW index, and a nightly catalogue sync re-upserts changed listings as a delete plus an insert. Write the decision record for the index configuration behind that search. Reuse your own bench.py runs from the lab: the ef_search sweep, the filtered run, the halfvec run and the IVFFlat sweep. Add the effect of the nightly delete plus insert on the graph, using the chapter’s note on dead tuples and reindexing. Ojaline’s catalogue size and its filters are not given here, so choose them and state them as assumptions. The head of engineering for search reads the record to decide which index and settings go live, and how often it is rebuilt.

Self-check

DECIDE

Your company's support search holds 8 million chunks embedded at 1,024 dimensions, in a Postgres 17 primary with 64 GB of RAM that also serves the ticketing application. Every query filters on tenant_id. There are 2,000 tenants: most have under 5,000 chunks, the largest has 600,000. The HNSW index on vector is 33 GB, p95 search latency has crept to 450 ms, and recall measured on a sample is 0.97 for large tenants and 0.6 for small ones. A colleague proposes moving search to a dedicated vector database. What do you do first?

READING
  1. PAPER
    Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs Malkov and Yashunin, 2016

    The HNSW paper. Short and readable: the layered graph, why the upper layers give logarithmic search, and the neighbour-selection heuristic that keeps the graph navigable. Every vector database's default index is this algorithm. Read: sections 3 and 4 for the algorithm and the roles of M and ef; skim the experiments.

  2. CODE
    pgvector README

    The reference for everything in the lab: HNSW and IVFFlat options and defaults, build-time memory, filtering and iterative scans, half-precision and binary-quantised indexes, and the FAQ on missing results. Read the Indexing, Filtering and Performance sections in full.

  3. POST
    pgvector 0.8.0 released pgvector, 2024

    The release that added iterative index scans and changed how the planner costs ANN indexes against B-trees. Short; read it to understand why filtered queries behave differently on 0.7 and 0.8.

  4. PAPER
    ANN-Benchmarks: A Benchmarking Tool for Approximate Nearest Neighbor Algorithms Aumüller, Bernhardsson and Faithfull, 2018

    How the field measures ANN indexes: recall with a distance tolerance, queries per second, build time and index size, plotted as trade-off curves rather than single numbers. The lab's recall rule comes from here. Read: section 3 on the quality measures; the recall-versus-queries-per-second plots.

  5. PAPER
    The Faiss library Douze et al., 2024

    The library that made IVF and product quantisation standard, written up by its authors. The clearest account of the space of index designs (flat, IVF, graph, quantised) and the trade-off each makes between speed, memory and accuracy. Read: the sections on IVF indexes and on vector compression; skip the GPU material.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Evaluation: building an eval set →