Sub topic 8
Why approximate search exists and what it costs in recall
This chapter explains why pgvector offers approximate indexes, what "recall" measures, and how an index can return results that differ from the exact answer. It assumes you can write basic SQL, know how to run queries in psql, and have read the earlier chapters on the vector type, the distance operators, and exact nearest-neighbor queries with ORDER BY and LIMIT.
Exact search and its cost
Recall the exact query from the previous chapter:
SELECT id, content
FROM items
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5;With no vector index, PostgreSQL computes the distance from the query vector to every row. It then sorts those distances, or keeps a running top five, and returns the closest rows. This is a sequential scan. The result is exact: no row in the table is closer than the ones returned.
The work grows linearly with the table. Each distance calculation touches every dimension of the vector. The cost per query is roughly:
- rows in the table, multiplied by
- dimensions per vector, multiplied by
- the cost of one arithmetic step.
For a table of a few thousand rows, this is fast enough that you should not add an index. For millions of rows with hundreds or thousands of dimensions, each query reads gigabytes of data. Latency rises to hundreds of milliseconds or seconds, and throughput falls because every concurrent query repeats the full scan.
A B-tree index cannot help here. A B-tree orders values along one dimension, so it can answer "which values are near 42?". Nearness in a high-dimensional space does not reduce to a single ordering, so no simple sorted structure can answer "which vectors are nearest to this one?" without checking many candidates.
The approximate trade
Approximate nearest-neighbor (ANN) indexes give up the guarantee of an exact answer to avoid scanning every row. An ANN index organizes vectors so that a query examines only a small, promising part of the data. The index returns the best rows it found in that part. Those rows are usually the true nearest neighbors, but not always.
pgvector provides two ANN index types:
- HNSW builds a layered graph of vectors. A query walks the graph toward the query vector.
- IVFFlat divides vectors into clusters, called lists. A query searches only the lists closest to the query vector.
Later chapters cover how to create and tune each one. Here, the key point is what they share: both skip data on purpose, and both can therefore skip a true neighbor.
What recall measures
Recall is the fraction of the true nearest neighbors that the approximate search returns.
recall@k = (true top-k rows found by the index) / kSuppose the exact top ten for a query is rows 1 to 10, and the index returns rows 1, 2, 3, 4, 5, 6, 7, 8, 11, and 12. Eight of the ten true neighbors were found, so recall@10 is 0.8. Rows 11 and 12 are not wrong in the sense of being random. They are probably the 11th and 12th nearest. The index replaced two true neighbors with near misses.
Recall is measured per query and then averaged over many queries. A reported recall of 0.95 means that, on average, 95% of the true top-k appear in the results.
Why recall can differ from correctness
For many applications, a missed neighbor is harmless. Embeddings are themselves approximate: the model that produced them does not guarantee that rank 4 is "more relevant" than rank 6. Returning the 6th-closest item in place of the 4th rarely changes what a user sees. Recall matters more when:
- you use vector search as a candidate step and a later stage cannot recover a missed row,
- you must deduplicate or find exact matches,
- you compare results across systems and need reproducibility.
Where the misses come from
Each index type misses neighbors for a specific reason.
| Index | Mechanism | Typical cause of a miss |
|---|---|---|
| HNSW | Greedy walk through a graph, keeping a candidate list of size `hnsw.ef_search` | The walk ends in a region of the graph that does not connect to a true neighbor, or the candidate list is too small to hold it |
| IVFFlat | Searches only the `ivfflat.probes` lists nearest the query | A true neighbor sits in a list that was not probed, often because it lies near a cluster boundary |
The IVFFlat case is easy to picture. The index assigns each vector to the nearest of lists cluster centers. A query vector near the border of two clusters has neighbors in both. With one probe, the search reads only one cluster and misses the neighbors on the other side.
The recall and speed dial
Both index types expose a query-time setting that moves along a trade-off:
- Searching more data raises recall and slows the query.
- Searching less data lowers recall and speeds the query.
You control this with hnsw.ef_search for HNSW and ivfflat.probes for IVFFlat. At the extreme, an IVFFlat search that probes every list reads all the data and is equivalent to exact search, with the added overhead of the index. An HNSW search with a very large ef_search approaches exact results but never carries a strict guarantee.
-- HNSW: larger ef_search means more candidates, higher recall, slower query
SET hnsw.ef_search = 100;
-- IVFFlat: more probes means more lists read, higher recall, slower query
SET ivfflat.probes = 10;Build-time settings also affect the ceiling. A graph built with a larger ef_construction is better connected, and an IVFFlat index built with a sensible lists value has better clusters. No query-time setting fully repairs a poorly built index.
Seeing the effect in a query
You can observe the difference between exact and approximate results by running the same query with and without the index. The transaction below turns off index scans for its duration, which forces an exact sequential scan:
BEGIN;
SET LOCAL enable_indexscan = off;
SELECT id FROM items
ORDER BY embedding <=> '[3,1,2]'
LIMIT 10;
COMMIT;SET LOCAL applies only until the transaction ends, so the rest of your session keeps using the index. Run the same SELECT outside the transaction with an HNSW or IVFFlat index in place and compare the two lists of ids. Any id present in the first list and absent from the second is a miss. A later chapter turns this comparison into a repeatable measurement.
Failure modes to expect
Several behaviors surprise people the first time they use an ANN index.
- Fewer rows than
LIMIT. An index scan returns only the candidates it collected. With a lowef_searchor few probes, combined with aWHEREfilter, the query can return fewer rows than you asked for, even when the table holds enough matching rows. The filtering chapter covers this in detail. - Results change after the index is created. A query that returned one list on a sequential scan can return a slightly different list once the planner starts using the index. This is expected, not a bug.
- Recall drifts as data changes. IVFFlat computes its cluster centers when the index is built. If you later insert many vectors with a different distribution, the old centers fit them poorly and recall falls. HNSW is less sensitive to this, but heavy deletes and updates can still degrade the graph until the index is rebuilt or vacuumed.
- The planner may ignore the index. For small tables, or when it expects a filter to remove most rows, PostgreSQL may choose a sequential scan, which returns exact results. Identical SQL can therefore be exact on one day and approximate on another.
- Wrong operator, no index. An index is used only when the query's operator matches the index's operator class. A mismatch silently falls back to an exact scan, which is correct but slow. The operator class chapter covers this.
Deciding whether to use an approximate index
Use these criteria to decide.
- Table size. Under roughly tens of thousands of rows, exact search is often fast enough. Measure before adding an index.
- Latency target. If exact search meets your latency target, keep it. You get perfect recall and no index to maintain.
- Tolerance for misses. If the application cannot accept any missed neighbor, use exact search or probe widely and verify.
- Write pattern. Heavy writes raise the maintenance cost of an index and can lower recall over time.
- Memory and build time. ANN indexes take time and memory to build and extra disk to store. A later chapter covers these costs.
A sound workflow is to start with exact search, add an index only when latency requires it, then measure recall and tune until the speed and recall meet your needs.
Summary of the idea
Exact search is correct and scales linearly with the table. Approximate indexes avoid that linear cost by examining only part of the data, which means a true neighbor can be skipped. Recall quantifies how often that happens. You tune query-time and build-time settings to place your application at a point on the recall and speed curve that you can defend.
Exercise
An IVFFlat index has lists = 100 and ivfflat.probes = 1. For one query, the exact top ten rows are known. The index returns nine of them plus one row that is not in the exact top ten. What is recall@10 for this query, and what is one change that would likely raise it?
Show answer
Recall@10 is 9/10 = 0.9, because nine of the ten true neighbors were returned. Raising ivfflat.probes (for example with SET ivfflat.probes = 10;) makes the search read more lists, which likely finds the missing neighbor at the cost of a slower query.
Exercise
A query uses an HNSW index with a cosine operator class, but EXPLAIN shows a sequential scan and the results are always exact. Give two plausible reasons.
Show answer
The query may use an operator that does not match the index's operator class (for example <-> against an index built with vector_cosine_ops), so the planner cannot use the index. Alternatively, the table may be small enough, or a filter selective enough, that the planner estimates a sequential scan is cheaper.