Sub topic 15
Measuring recall against exact search
An approximate index can return a different top-k than the true nearest neighbors, and nothing in the query result tells you so. This chapter shows how to measure that gap with the exact results pgvector can already produce. It assumes you have read the chapters on exact search, HNSW, IVFFlat, and index tuning. You should be comfortable with ORDER BY ... LIMIT vector queries, hnsw.ef_search, and ivfflat.probes.
What recall means here
Recall@k is the fraction of the true top-k neighbors that the approximate query also returned. If an exact query returns 10 ids and the indexed query returns 8 of those same ids, recall@10 for that query is 0.8.
Three details matter:
- Ground truth is the exact scan. Without an index, pgvector reads every row and sorts by distance, so its answer is correct by definition.
- Compare ids, not order. Recall measures set overlap. If you also care about ranking, measure that separately.
- Average over many queries. One query tells you almost nothing. A single query may hit a well-connected region of the graph, and the next may not.
Getting exact results from an indexed table
You do not need a second copy of the table without an index. Disable index scans for one transaction and the planner falls back to a sequential scan:
BEGIN;
SET LOCAL enable_indexscan = off;
SELECT id FROM items
ORDER BY embedding <=> '[3,1,2]'
LIMIT 10;
COMMIT;SET LOCAL lasts only until the transaction ends, so other queries on the same connection keep using the index. Plain SET enable_indexscan = off would stay in effect for the whole session, and you could forget to turn it back on.
Run the same query without the SET LOCAL line to get the approximate result. Before you trust that comparison, confirm the index was used:
EXPLAIN
SELECT id FROM items
ORDER BY embedding <=> '[3,1,2]'
LIMIT 10;The plan should show an Index Scan using items_embedding_hnsw (or your IVFFlat index). If it shows Seq Scan, both of your queries are exact and the recall figure will be a meaningless 1.0. This happens often on small tables, where the planner decides a sequential scan is cheaper.
A repeatable measurement in Python
The script below samples query vectors from the table, runs each one exactly and through the index, and averages the overlap. It assumes the items table and an HNSW index on embedding with vector_cosine_ops, as built in earlier chapters.
import numpy as np
import psycopg
from pgvector.psycopg import register_vector
K = 10
N_QUERIES = 100
conn = psycopg.connect('dbname=mydb', autocommit=True)
register_vector(conn)
def top_ids(query, exact, ef_search=None):
with conn.transaction():
if exact:
conn.execute('SET LOCAL enable_indexscan = off')
elif ef_search is not None:
conn.execute(
"SELECT set_config('hnsw.ef_search', %s, true)",
(str(ef_search),),
)
rows = conn.execute(
'SELECT id FROM items ORDER BY embedding <=> %s LIMIT %s',
(query, K),
).fetchall()
return {row[0] for row in rows}
def mean_recall(queries, ef_search):
scores = []
for q in queries:
truth = top_ids(q, exact=True)
found = top_ids(q, exact=False, ef_search=ef_search)
scores.append(len(truth & found) / len(truth))
return float(np.mean(scores))
queries = [
row[0]
for row in conn.execute(
'SELECT embedding FROM items ORDER BY random() LIMIT %s',
(N_QUERIES,),
)
]
for ef in (10, 40, 100, 200):
print(f'ef_search={ef:4d} recall@{K}={mean_recall(queries, ef):.3f}')set_config('hnsw.ef_search', value, true) is the same as SET LOCAL, but it accepts a bound parameter. A plain SET statement cannot take one.
Sampling queries from the table is convenient, but each sampled vector is also stored in the index, so it finds itself at distance 0. That slightly flatters recall. For a stricter test, use vectors that are not in the table, such as embeddings of real user queries or a held-out sample.
For IVFFlat, replace the set_config call with ivfflat.probes and sweep values such as 1, 5, 10, and 20.
Reading the results
A typical sweep might look like this (your numbers will differ):
| ef_search | recall@10 | Relative latency |
|---|---|---|
| 10 | 0.82 | lowest |
| 40 (default) | 0.94 | low |
| 100 | 0.98 | moderate |
| 200 | 0.99 | higher |
Choose the cheapest setting that meets your requirement. A search feature for browsing may tolerate 0.9. A retrieval step that feeds a language model, where a missed passage means a wrong answer, usually justifies 0.98 or higher. Time each setting as well as measuring recall, because recall is only half of the trade-off.
If recall plateaus below your target no matter how high you set ef_search or probes, the cause is in the build:
- For HNSW, rebuild with a larger
moref_construction. - For IVFFlat, check that the index was built after the table was loaded. Centroids chosen from an empty or tiny table give poor clusters, and
listsmay need adjusting.
Edge cases that distort the numbers
LIMIT larger than the search breadth. HNSW returns at most hnsw.ef_search candidates per scan. With the default of 40, LIMIT 100 cannot return more than 40 rows. Set ef_search at least as high as the largest LIMIT you use, and measure recall at that LIMIT.
Filtered queries. With a WHERE clause, the index finds candidates first and PostgreSQL filters them afterward. A selective filter can leave fewer than k rows, and recall against the filtered exact result drops. Measure these queries separately, with the same filter on both the exact and approximate side:
BEGIN;
SET LOCAL enable_indexscan = off;
SELECT id FROM items
WHERE category_id = 1
ORDER BY embedding <=> '[3,1,2]'
LIMIT 10;
COMMIT;An overall recall of 0.97 can hide a rare category at 0.40. If filtered queries matter, build your sample to cover them.
Ties. If several rows have the same distance to the query, the exact scan can pick any of them at the boundary of the top-k. Duplicate or near-duplicate vectors can therefore make recall appear slightly below 1.0 even when the index behaves correctly.
Changing data. Recall measured today describes today's index. After large inserts, deletes, or updates, run the measurement again. IVFFlat is more sensitive to this, because its centroids are fixed at build time.
Cost. Each exact query scans the whole table. On millions of rows, 100 exact queries is slow but acceptable offline. Run the evaluation on a replica or in a quiet period, not against a busy production primary. You can also compute the exact top-k once and cache it, then re-run only the indexed side when you change parameters.
Exercise
You run recall@10 on 200 sampled queries and get 0.99. EXPLAIN on the same query shows "Seq Scan on items". What does the 0.99 tell you about the index, and what do you do next?
Show answer
It tells you nothing about the index. The sequential scan is an exact search, so the "approximate" side was exact too, and any value below 1.0 is caused only by ties or by differences in the sampled data. Find out why the planner skipped the index (a small table, an operator that does not match the index's operator class, or a missing index), fix that so EXPLAIN shows an Index Scan, and then repeat the measurement.
Exercise
Your application uses LIMIT 50 on an HNSW index with the default hnsw.ef_search of 40. Recall@50 measures 0.78 even though recall@10 was 0.95. Why, and what is the fix?
Show answer
HNSW returns at most efsearch candidates per scan, so with efsearch = 40 the query cannot return 50 rows, and at least 10 of the true top-50 are always missed. Raise hnsw.ef_search to at least 50, ideally higher, and re-measure recall@50 at that value.