Sub topic 10
Combining vector search with metadata filters
Real queries rarely ask only for "the most similar items". They ask for the most similar items that are in stock, written after 2023, or visible to this user. This chapter assumes you know what an ANN index is, how HNSW and IVF work at a high level, and basic SQL WHERE clauses.
Why filtering is hard for ANN indexes
An HNSW or IVF index is built only from vectors. It knows nothing about categories, dates, or permissions. Metadata is stored next to the vectors, and the filter has to be applied somewhere around the index search. The choice of where determines both correctness and speed.
Three strategies
| Strategy | How it works | Main risk |
|---|---|---|
| Post-filtering | Run ANN for the top k, then drop results that fail the filter | Fewer than k results, possibly none |
| Pre-filtering | Find matching rows first, then search only those vectors | Slow if the index cannot be used on the subset |
| In-index (filtered) search | Check the filter while traversing the index and skip non-matching items | Graph traversal can get stuck or lose recall on very selective filters |
The key quantity is selectivity: the fraction of rows that pass the filter. A filter that keeps 50% of rows is mild. A filter that keeps 0.1% is severe.
Post-filtering and its failure mode
Suppose you ask for the top 10 and only 5% of items match your filter. On average, 10 candidates contain 0.5 matching items. The query often returns zero or one result, even though many valid matches exist further away.
The usual workaround is to over-fetch. You request more candidates than k, filter them, then trim. This helps, but you must guess the multiplier, and it fails for rare filters.
Pre-filtering and in-index filtering
With pre-filtering, a normal index (for example a B-tree on category) finds the matching rows. If few rows match, computing exact distances over them is cheap and gives perfect recall. If many match, scanning them all is too slow, so the database falls back to the vector index.
Filtered HNSW checks the filter on each visited node. Non-matching nodes may still be traversed to reach matching ones, but they are not returned. When the filter is very selective, the search may visit many nodes before finding enough matches, so latency rises and recall can drop.
A worked example in pgvector
The query planner in Postgres chooses between the vector index and the ordinary index.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE items (
id bigserial PRIMARY KEY,
category text,
embedding vector(3)
);
INSERT INTO items (category, embedding) VALUES
('a', '[1, 0, 0]'),
('b', '[0, 1, 0]'),
('a', '[0.9, 0.1, 0]');
CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops);
CREATE INDEX ON items (category);
SELECT id, embedding <=> '[1, 0, 0]' AS cosine_distance
FROM items
WHERE category = 'a'
ORDER BY embedding <=> '[1, 0, 0]'
LIMIT 2;In pgvector, the HNSW index returns up to hnsw.ef_search candidates (default 40), and the WHERE clause is applied to them afterward. This is post-filtering. A selective filter can therefore return fewer rows than LIMIT. Raising hnsw.ef_search widens the candidate pool. Newer pgvector versions also offer iterative index scans that keep searching until enough rows match. Check the documentation for your installed version.
Practical guidance
- Measure selectivity for your common filters before choosing a strategy.
- Index metadata columns you filter on.
- For very selective filters, exact scan over the matching subset is often faster and more accurate than ANN.
- For filters that split data into separate groups (such as tenant), consider partitioning or one index per group.
- Always test recall with filters applied, not only without them.
Exercise
A query asks for the top 10 results with a filter that only 2% of items satisfy. The system uses post-filtering over the top 10 ANN candidates. About how many results do you expect, and what are two ways to fix it?
Show answer
About 0.2 results on average, so usually none. Fixes: over-fetch many more candidates (for example raise ef_search or request several hundred and trim), or use pre-filtering or exact scan over the matching rows, or a database that applies the filter during index traversal.