Practical technical guides / AI engineering: retrieval

Selective Filters Starve Post-Filtered Vector Search: Overfetch, Pre-Filter or Iterate

A post-filtered approximate search returns about 4 of 10 rows for a 10 percent filter and none for clustered ones. Compare overfetch, pre-filter and iterative scans.

By Sandeep Belgavi · Published 2026-11-26

A post-filtered approximate search returns about 4 of 10 rows for a 10 percent filter and none for clustered ones. Compare overfetch, pre-filter and iterative scans.

Ten results requested, four returned

A retrieval step for an agent at Belgavi's Book Store looks simple: embed the customer's question, ask the vector store for the ten nearest catalogue entries, and restrict them to books currently on promotion. In SQL with pgvector it is one statement with a WHERE clause and ORDER BY embedding distance LIMIT 10. With an approximate index the answer often contains fewer than ten rows, sometimes none, while the table holds hundreds of matching books. The agent then answers from four documents, or says nothing relevant exists.

The pgvector documentation states the mechanism plainly: with approximate indexes, filtering is applied after the index is scanned, and with HNSW and the default hnsw.ef_search of 40, a condition that matches 10 percent of rows returns only about 4 rows on average. This guide works through why, shows the cases where the documented average is optimistic, and compares the four fixes: overfetching, exact pre-filtering, iterative index scans and partitioning.

Post-filtering is sampling from a neighbourhood

An approximate nearest-neighbour index returns a bounded candidate list around the query. With HNSW in pgvector the bound is hnsw.ef_search; with IVFFlat it is the number of probed lists. The WHERE clause is then evaluated on those candidates. The number of results is therefore the number of candidates that happen to satisfy the filter, and you can estimate it as the candidate count multiplied by the filter's selectivity among the candidates.

That last phrase is the trap. The selectivity that matters is local: the share of matching rows near the query, not the share in the whole table. For a filter that is independent of content, such as a promotion flag assigned without regard to subject, the two are similar. For a filter that correlates with content, they can be wildly different. Restricting to a shelf of history books while the query is about cookery asks for rows that are rare in the query's neighbourhood even if they are common in the table.

Measure it on a synthetic catalogue

The companion example builds 20,000 synthetic book vectors in 16 dimensions, grouped into 20 topic clusters, and runs exact search in pure Python. Exact search is an idealised index: its candidates are the true nearest neighbours, so real approximate indexes can only do worse. Four filters are applied to a query near topic 0.

filter                                matching rows  post-filter  overfetch x4  x10  x40  iterative visits
promo flag, 10 percent, independent        2020           4            10        10   10        120
rare flag, 1 percent, independent           212           1             4         7   10        560
topic 3 only, 5 percent                    1000           0             0         0   10       1360
farthest topic, 5 percent                  1000           0             0         0    0      17840

The 10 percent independent filter reproduces the documented average exactly: 4 of 40 candidates survive. The 1 percent filter leaves 1. The two topic filters match 5 percent of the table each, yet the first 40 candidates contain none of them, because every candidate comes from the query's own topic cluster. Even 40 times overfetch, 1,600 candidates, finds nothing from the farthest topic.

Fix one: overfetch, and what it costs

The simplest fix is to ask the index for more candidates than you need and filter afterwards. In pgvector that means raising hnsw.ef_search for the query, which the documentation shows with SET LOCAL inside a transaction so it applies to one query. For independent filters this works and the arithmetic is predictable: to expect ten survivors at selectivity s you need about 10 divided by s candidates, so 100 for a 10 percent filter and 1,000 for a 1 percent filter. The example's recall against the exact answer was 1.0 at four times overfetch for the 10 percent filter, but only 0.4 and 0.7 at four and ten times for the 1 percent filter.

Overfetching has two weaknesses. Cost rises with the candidate count, so very selective filters become expensive. And for correlated filters no fixed factor is safe, because the local selectivity can be zero for a long way out from the query.

Fix two: pre-filter with an exact index

When the filter is selective, the documentation's first suggestion is an ordinary index on the filter column. PostgreSQL then finds the matching rows through a B-tree and computes exact distances for those rows only.

-- Author: Sandeep Belgavi. Exact nearest neighbours within a selective filter.
CREATE INDEX ON catalogue (shelf_id);
SELECT id, title FROM catalogue
WHERE shelf_id = 42
ORDER BY embedding <-> $1
LIMIT 10;

Exact search over 212 rows is cheap and its recall is 1.0 by definition. Over 200,000 rows it is not. The documentation summarises the trade-off: exact indexes work well for conditions that match a low percentage of rows, and approximate indexes can work better otherwise. Check which plan the query actually uses with EXPLAIN, because the planner chooses between them from its estimates, and a stale estimate can send a selective query through the approximate index.

Fix three: iterative index scans

Since pgvector 0.8.0, an approximate index scan can continue past the first candidate list until enough rows satisfy the filter. Setting hnsw.iterative_scan to strict_order keeps results in exact distance order; relaxed_order allows slight reordering and the documentation notes it gives better recall, with a materialized CTE available to restore strict order afterwards. The scan stops when it has enough results or when it reaches hnsw.max_scan_tuples, 20,000 by default, or ivfflat.max_probes for IVFFlat.

-- Author: Sandeep Belgavi. Let the approximate scan continue until the filter is satisfied.
BEGIN;
SET LOCAL hnsw.iterative_scan = strict_order;
SET LOCAL hnsw.max_scan_tuples = 20000;
SELECT id, title FROM catalogue
WHERE promo
ORDER BY embedding <-> $1
LIMIT 10;
COMMIT;

The iterative column of the table shows how far the idealised scan had to go in batches of 40: 120 candidates for the 10 percent filter, 560 for the 1 percent filter, 1,360 for the nearby topic and 17,840 for the farthest topic. That last number is close to the default visit limit, which is the point of the limit: on a real index a correlated filter can make the scan walk most of the graph, and the bound turns an unbounded query into a short result list that you must detect.

Fix four: partition or index per value

For a filter with a few distinct values, the documentation suggests partial indexes, one approximate index per value. For many values, it suggests list partitioning. In both cases each index only contains rows that already satisfy the filter, so post-filtering never happens. This is also the documented answer for multitenancy: a shared approximate index lets one tenant's vectors affect another's recall and speed. Partitioning by tenant isolates both.

What the agent must not assume

Whatever the strategy, the retrieval tool should report how many results it found against how many were requested, and the agent's code should treat a short result list as a signal rather than as the complete set of relevant documents. A tool that returns four rows silently teaches the model that four is everything. Return the count, the limit and whether the scan stopped at its tuple bound, so the agent can widen the query, ask a clarifying question or say that the catalogue section is sparse.

Choosing a strategy

Use an exact pre-filter when the filter matches a small share of rows, such as one shelf or one customer's documents. Use partial indexes or partitions when the filter has few, stable values, such as language or tenant. Use iterative scans when the filter is moderately selective and independent of content, and monitor how often a query reaches the tuple limit. Use plain overfetch only when you can bound the selectivity from below, and size it from that bound.

Verification

Build a labelled set of filtered queries, compute the exact answer with a sequential scan, and measure recall and result count for each strategy at your real index settings. Include correlated filters deliberately, because uniform random filters hide the worst case. Track the share of queries returning fewer rows than requested in production. The table above comes from the synthetic example, which uses exact search as an upper bound; numbers from a real HNSW index will be lower and depend on ef_search, graph parameters and data.

Primary references and authorship

Sources checked 2026-11-26. Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/filtered_vector_overfetch. Views are my own and do not represent any employer, past or present.