Sub topic 15
Measuring Recall Against Exact Search
Assume you know basic SQL and have an items table with an embedding vector(...) column. Also assume you have already created an HNSW or IVFFlat index. This chapter uses cosine distance, but the same method works with L2 or inner product.
What recall measures
An approximate nearest-neighbor index is allowed to skip some rows to answer quickly. Recall@k measures how many of the true top k rows it returns:
recall@k = approximate results that are also exact results / exact result count
For example, if the exact query returns 10 IDs and the indexed query returns 8 of those IDs, recall@10 is 0.8, or 80%.
The exact query is the reference result. It scans all eligible rows and sorts them by distance. It can be slow on a large table, but it provides the baseline needed to evaluate an approximate index.
Produce both result sets
The following example compares the top 10 results for the same query. The transaction-local setting disables index scans for the exact query. The temporary table remains available after the transaction ends.
DROP TABLE IF EXISTS exact_ids;
DROP TABLE IF EXISTS approx_ids;
BEGIN;
SET LOCAL enable_indexscan = off;
CREATE TEMP TABLE exact_ids AS
SELECT id
FROM items
ORDER BY embedding <=> '[3,1,2]'::vector
LIMIT 10;
COMMIT;
SET hnsw.ef_search = 40;
CREATE TEMP TABLE approx_ids AS
SELECT id
FROM items
ORDER BY embedding <=> '[3,1,2]'::vector
LIMIT 10;
SELECT
count(*)::numeric
/ NULLIF((SELECT count(*) FROM exact_ids), 0) AS recall_at_10
FROM exact_ids AS e
JOIN approx_ids AS a USING (id);For a meaningful test, use a table large enough that PostgreSQL chooses the approximate index. On a small table, a sequential scan may be faster, so the indexed query might still be exact. Check the plan:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id
FROM items
ORDER BY embedding <=> '[3,1,2]'::vector
LIMIT 10;For HNSW, look for an index scan using the HNSW index. For IVFFlat, look for its IVFFlat index. Run the test with several query vectors, not just one, because one query can produce an unusually good or bad result.
Interpret and improve the result
If recall is too low, increase the query-time search breadth. For HNSW, raise hnsw.ef_search. For IVFFlat, raise ivfflat.probes. These settings usually improve recall while increasing latency.
Compare recall at the same k, distance metric, filters, and query vectors. A cosine-distance query must use a cosine operator class, such as vector_cosine_ops. Otherwise, the comparison may measure a configuration error rather than index quality.
With a WHERE filter, compute the exact baseline using that same filter. If fewer than k rows satisfy the filter, divide by the number of exact eligible rows instead of assuming k.
Exercise
The exact query returns 10 IDs, and the approximate query shares 7 of them. What is recall@10?
Show answer
Recall@10 is 7 / 10 = 0.7, or 70%.