Sub topic 10
Combining vector search with metadata filters
This chapter assumes you know how an approximate nearest neighbor (ANN) index such as HNSW or IVF works, and that you can read basic Python and SQL. It covers why a filter and a vector index interact badly, the three ways systems combine them, and how to choose a strategy for your data.
Why filters are needed
Real queries rarely ask only for "the nearest vectors". They ask for the nearest vectors that also satisfy a condition:
- Documents that this user is allowed to see.
- Products that are in stock and under a given price.
- Passages from a specific language, tenant, or date range.
The extra fields stored next to each vector are called metadata (also called payload or attributes). A filter is a predicate over that metadata, such as category = 'a' or created_at > '2026-01-01'.
With exact search, filtering is easy. You discard non-matching rows and rank the rest. With an ANN index the situation is harder, because the index was built to answer "what is near this point?" and knows nothing about your predicates. Two things then go wrong. The index may return too few matches, or it may spend far more work than expected to find them.
Selectivity decides everything
The selectivity of a filter is the fraction of rows that pass it. A filter that keeps 50% of rows has low selectivity in the sense of being permissive. A filter that keeps 0.1% of rows is highly selective. The vocabulary varies between systems, so state it as a percentage when you discuss it with others.
Selectivity matters because a good strategy for a permissive filter fails on a restrictive one, and the reverse. Most of the design choices below are different answers to the question "what do we do at each selectivity?"
Three strategies
Post-filtering
Post-filtering runs the ANN search first and applies the filter to the results. It is simple and works with any index.
Its weakness is that the filter can remove most or all of the candidates. If you ask for the top 10 and only 1% of rows match, you expect about 0.1 matching results. The usual workaround is to over-fetch, for example requesting the top 1,000 and filtering down to 10. That costs more work, and it still fails when the filter is selective enough.
Pre-filtering
Pre-filtering first finds the rows that pass the filter, then searches only among them. The results are correct, and you always get up to k matches if that many exist.
The problem is the index. An HNSW graph is built over all vectors. If you remove most nodes, the remaining ones may no longer be connected, so graph traversal gets stuck or misses neighbors. For very selective filters, systems often skip the ANN index and run an exact scan over the matching rows. When only a few thousand rows match, that is fast and gives perfect recall.
Filtering during traversal
The third approach checks the predicate while the index is searched. In a graph index, the search still walks through non-matching nodes to stay connected, but it only adds matching nodes to the result set. In an IVF index, the scan of each chosen cluster skips rows that fail the filter.
This gives the best results across a wide range of selectivities, and many dedicated vector databases implement some version of it. It has its own costs. Search can visit many nodes that never become results, so latency rises as the filter gets more restrictive, and the result quality depends on how the implementation handles disconnected regions.
| Strategy | Strength | Weakness | Fits best when |
|---|---|---|---|
| Post-filter | Works with any index | Too few results for selective filters | Filter keeps most rows |
| Pre-filter plus exact scan | Perfect recall on the matching set | Slow when many rows match | Filter keeps few rows |
| Filter during traversal | Good balance across selectivities | Latency grows as the filter tightens, and behavior depends on the engine | Mixed or unknown selectivity |
Seeing the post-filter problem in code
The following script uses exact scoring so the effect is not mixed up with ANN error. About 1% of the rows are labeled rare. Post-filtering takes the top 10 and then keeps only the rare ones. Pre-filtering restricts the candidates first.
import numpy as np
rng = np.random.default_rng(0)
n, d, k = 10000, 64, 10
vectors = rng.normal(size=(n, d)).astype("float32")
vectors /= np.linalg.norm(vectors, axis=1, keepdims=True)
category = np.where(rng.random(n) < 0.01, "rare", "common")
query = rng.normal(size=d).astype("float32")
query /= np.linalg.norm(query)
scores = vectors @ query # cosine similarity, since all vectors are unit length
# Post-filter: take the global top k, then drop rows that fail the filter.
top = np.argsort(-scores)[:k]
post = [int(i) for i in top if category[i] == "rare"]
# Pre-filter: restrict to matching rows, then rank only those.
matching = np.flatnonzero(category == "rare")
pre = matching[np.argsort(-scores[matching])[:k]]
print("matching rows:", len(matching))
print("post-filter results:", len(post))
print("pre-filter results:", len(pre))The post-filter count is usually 0 or 1, while the pre-filter count is 10. The same pattern appears with a real ANN index, with the added problem that over-fetching raises the work per query.
Choosing by selectivity
A query planner, or you as the designer, can pick a path from the estimated selectivity.
The thresholds depend on the engine, the index parameters, and the hardware, so measure them on your own data instead of copying numbers from another system.
Filtering in pgvector
A vector extension inside a relational database lets the planner combine a vector index with ordinary indexes. That is useful, but the behavior is easy to misread. Here is a table with a filter column, a regular index on that column, and an HNSW index. The settings are explained below.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE IF NOT EXISTS items (
id bigserial PRIMARY KEY,
category text,
embedding vector(3)
);
CREATE INDEX IF NOT EXISTS items_category_idx ON items (category);
CREATE INDEX IF NOT EXISTS items_embedding_idx
ON items USING hnsw (embedding vector_cosine_ops);
-- Search wider than the default of 40 candidates.
SET hnsw.ef_search = 100;
-- Available in pgvector 0.8.0 and later: keep scanning the index
-- until enough rows pass the filter.
SET hnsw.iterative_scan = relaxed_order;
SELECT id, embedding <=> '[1, 0, 0]' AS cosine_distance
FROM items
WHERE category = 'a'
ORDER BY embedding <=> '[1, 0, 0]'
LIMIT 10;In this setup the HNSW scan produces up to hnsw.ef_search candidates, and Postgres applies WHERE category = 'a' to them afterward. This is post-filtering. With the default settings, a selective filter can therefore return fewer than 10 rows, even when more than 10 matching rows exist.
The hnsw.iterative_scan setting changes this. The index keeps producing candidates until the LIMIT is filled or a scan limit is reached. With relaxed_order, results can be slightly out of distance order, so wrap the query in an outer ORDER BY if exact ordering matters. The strict_order mode keeps the order exact.
For a filter on a small set of known values, a partial index avoids the problem. It indexes only the matching rows:
CREATE INDEX IF NOT EXISTS items_embedding_a_idx
ON items USING hnsw (embedding vector_cosine_ops)
WHERE category = 'a';The planner uses this index only for queries whose WHERE clause implies category = 'a'. It works well for a handful of categories. It does not scale to thousands of tenants, because each partial index takes space and build time. In that case, table partitioning by tenant is the usual alternative.
Other ways to reduce the problem
- Partition by the filter field. If every query filters on tenant or language, keep a separate index per value. This gives pre-filtering at no query cost, but too many small indexes are expensive to manage.
- Encode coarse filters in the index structure. Some systems let you build the index so that vectors with the same key are stored together. This is common for multi-tenant workloads.
- Index the metadata fields. Engines that filter during traversal still need a fast way to evaluate the predicate or build the allow-list of matching IDs. Declare payload indexes on fields you filter by.
- Raise the search width. A larger
efSearchin HNSW, or a largernprobein IVF, gives more candidates before filtering and so improves the yield. It also raises latency. - Re-rank after filtering. Retrieve more candidates than you need, filter, and re-rank the survivors with exact distances.
Edge cases to test
- Zero matches. A filter that matches nothing should return an empty result quickly. Some engines still walk the index until a limit is reached.
- Correlated filters. If the filter correlates with the query, for example searching for cooking documents while filtering to the cooking category, post-filtering works well. If they are anti-correlated, it works badly. Test with realistic queries, not random ones.
- Changing selectivity. A filter on a date range can match 90% of rows today and 1% next year. A strategy tuned today may break later.
- Access control. Security filters must never be best-effort. If a system could return unauthorized rows under any strategy, enforce the check again after retrieval.
- Recall measurement. Compute the ground truth with the same filter. Comparing filtered ANN results to unfiltered exact results gives a misleading recall number.
Exercise
A table has 5 million vectors. A query asks for the 10 nearest vectors where tenant_id = 42, and tenant 42 owns 2,000 rows. The index is HNSW with post-filtering and a candidate list of 100. The query often returns only one or two rows. Explain why, and give two changes that would fix it.
Show answer
The filter keeps 2,000 of 5 million rows, which is 0.04%. Of the 100 candidates the index returns, you expect about 0.04 matches, so almost all are discarded after the search. Fixes: (1) build a separate index per tenant, or partition the table by tenant, so the search only sees that tenant's rows; (2) for a filter this selective, fetch the 2,000 matching rows through a normal index on tenant_id and scan them exactly. Enabling iterative scans or filtering during traversal would also help, but the partitioned or exact approach gives the most predictable latency here.
Exercise
In the Python example, why does the pre-filter result always contain 10 rows while the post-filter result usually does not?
Show answer
Pre-filtering ranks only the rows labeled rare, which number about 100, so it can always supply 10. Post-filtering ranks all 10,000 rows first and keeps the 10 best overall. Only about 1% of those are rare, so the expected count is about 0.1.