Sub topic 13
Combining vector search with WHERE filters
This chapter assumes you can build an HNSW or IVFFlat index and run an ORDER BY embedding <=> ... LIMIT k query. It also assumes you know what EXPLAIN shows. Here you will see why adding a WHERE clause to an approximate vector query can return fewer rows than you asked for, and how to fix that.
Why filters change the behavior
Real queries rarely ask for the nearest neighbors in the whole table. They ask for the nearest neighbors among rows that match something else, such as one category, one tenant, or documents published this year.
With exact search, a filter is simple. PostgreSQL discards the rows that don't match, sorts the survivors by distance, and returns the top k. With an approximate index, the order of operations is different.
An HNSW or IVFFlat index is an ordered source of candidates. It knows nothing about your category_id column. When the planner uses the vector index, the scan produces its candidates first, and PostgreSQL then applies the WHERE condition to them. This is called post-filtering.
Here is the query we will work with. It uses the items table from earlier chapters, extended with a category column.
ALTER TABLE items ADD COLUMN category_id integer;
CREATE INDEX items_category_idx ON items (category_id);
SELECT id, content
FROM items
WHERE category_id = 1
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5;
EXPLAIN
SELECT id FROM items
WHERE category_id = 1
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5;The post-filtering problem
Suppose the HNSW index has hnsw.ef_search = 40, the default. The scan collects about 40 candidates near the query vector. PostgreSQL then keeps only the candidates where category_id = 1.
If category 1 holds 10% of the table, you can expect roughly 4 of the 40 candidates to survive. Your query asks for LIMIT 5, so it returns 4 rows or fewer. Nothing raises an error. The result is just short.
The same thing happens with IVFFlat. The index reads the rows in the ivfflat.probes closest lists, then filters them. A selective filter can leave few or no rows.
The more selective the filter, the worse this gets. A filter matching 0.1% of rows can return zero rows from an index scan even though matching rows exist.
What the planner chooses
PostgreSQL's planner picks between two broad plans for a filtered vector query.
- Vector index scan, then filter. Fast, but subject to the short-result problem above.
- Filter index scan, then exact sort. The planner uses the B-tree on
category_idto find matching rows, then sorts them by distance. The result is exact, and the cost grows with the number of matching rows.
The planner estimates which is cheaper from table statistics. When the filter is selective, it tends to choose plan 2, which is correct and cheap because few rows match. When the filter matches a large share of the table, it tends to choose plan 1. Run EXPLAIN and look at the scan node.
In the EXPLAIN output, a node such as Index Scan using items_embedding_hnsw means plan 1. A node such as Index Scan using items_category_idx followed by a Sort means plan 2.
Strategies for filtered search
There is no single best approach. The right one depends on how selective the filter is and how many distinct filter values you have.
| Strategy | How it works | Best when | Cost |
|---|---|---|---|
| Raise `hnsw.ef_search` or `ivfflat.probes` | Collects more candidates before filtering | The filter is mildly selective | Slower queries |
| Iterative index scans | Keeps scanning the index until enough rows pass the filter | Filters vary and you want one general fix | Extra scan work, with limits |
| B-tree index on the filter column | Lets the planner skip the vector index and sort exactly | The filter matches few rows | Exact sort cost grows with matches |
| Partial index | Builds a vector index over only the rows matching a condition | A few fixed filter values are queried often | One index per value |
| Partitioning | Splits the table by filter column, with indexes per partition | Many values, each large enough to index | Schema and maintenance overhead |
Raise the candidate count
The simplest fix is to make the index return more candidates. This works only up to a point, because the cap is a fixed number you choose in advance. HNSW accepts values up to 1000.
SET hnsw.ef_search = 200;
SELECT id, content
FROM items
WHERE category_id = 1
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5;For IVFFlat, raise ivfflat.probes instead, which reads more lists.
Use iterative index scans
pgvector 0.8.0 added iterative index scans. If the first batch of candidates does not produce enough rows after filtering, the index scan continues and fetches more. It stops when it has enough rows or reaches a limit.
SET hnsw.iterative_scan = strict_order;
SET hnsw.max_scan_tuples = 20000;
SELECT id, content
FROM items
WHERE category_id = 1
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5;The modes for HNSW are off (the default), strict_order, and relaxed_order. Strict order returns rows in exact distance order among the candidates found. Relaxed order may return rows slightly out of order but usually has better recall. hnsw.max_scan_tuples limits how many index entries the scan visits, 20000 by default. A very selective filter can still return fewer than k rows once that limit is reached.
IVFFlat has the matching setting ivfflat.iterative_scan, which accepts off and relaxed_order. It is bounded by ivfflat.max_probes.
If you use relaxed order, re-sort the output so the final order is correct. A materialized common table expression (CTE) makes the re-sort run after the index scan.
SET hnsw.iterative_scan = relaxed_order;
WITH relaxed AS MATERIALIZED (
SELECT id, content, embedding <=> '[3,1,2]' AS distance
FROM items
WHERE category_id = 1
ORDER BY distance
LIMIT 5
)
SELECT id, content, distance
FROM relaxed
ORDER BY distance + 0;Check your installed version before relying on these settings. They do not exist before pgvector 0.8.0.
Use a partial index
If you filter on a small set of known values, index only those rows. The index is smaller, and every candidate it returns already satisfies the filter.
CREATE INDEX items_cat1_hnsw
ON items USING hnsw (embedding vector_cosine_ops)
WHERE category_id = 1;The planner uses this index only when the query's WHERE clause implies the index condition. A query with WHERE category_id = 1 can use it. A query with WHERE category_id = 2 cannot.
Partition the table
With many filter values, such as one per tenant, a partial index per value becomes hard to manage. List partitioning by the filter column gives each value its own storage and its own vector index.
CREATE TABLE docs (
id bigserial,
tenant_id integer NOT NULL,
embedding vector(3),
PRIMARY KEY (tenant_id, id)
) PARTITION BY LIST (tenant_id);
CREATE TABLE docs_t1 PARTITION OF docs FOR VALUES IN (1);
CREATE INDEX docs_t1_hnsw ON docs_t1
USING hnsw (embedding vector_cosine_ops);A query with WHERE tenant_id = 1 is pruned to docs_t1 and uses only that partition's index.
Checking filtered results
Compare the indexed filtered query against an exact run, as in the recall chapter. For filtered queries, also compare row counts.
BEGIN;
SET LOCAL enable_indexscan = off;
SELECT count(*) FROM (
SELECT id FROM items
WHERE category_id = 1
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5
) t;
COMMIT;If the exact run returns 5 rows and the indexed run returns 3, the filter is cutting into your candidates.
Common errors
- Assuming
LIMIT 5always returns 5 rows when a matching set exists. - Testing with one filter value and then deploying to values with very different selectivity.
- Building a partial index and querying with a condition the planner cannot match to it.
- Using relaxed order and trusting the output order without a re-sort.
- Forgetting to run
ANALYZEafter bulk loads, which leaves the planner with bad selectivity estimates.
Exercise
A query filters on a column that matches about 1% of the table and uses an HNSW index with the default hnsw.ef_search of 40. It asks for LIMIT 10 but returns only 1 row. Why does this happen, and name two changes that could fix it.
Show answer
The HNSW scan collects about 40 candidates, and the filter is applied afterward. With a 1% filter, only about 0.4 of those candidates are expected to match, so the query returns very few rows. Fixes include enabling iterative scans (SET hnsw.iterativescan = strictorder), raising hnsw.ef_search, creating a partial index for the filter value, or adding a B-tree index on the filter column so the planner can filter first and sort exactly.
Exercise
You run EXPLAIN on a filtered vector query and see "Index Scan using itemscategoryidx" followed by a Sort node. Is the result exact or approximate, and why?
Show answer
It is exact. The planner used the B-tree index to find every row matching the filter and then sorted all of them by distance, so no approximate vector index was involved.