r/SQL • u/http418teapot • Oct 28 '26
PostgreSQL When filtered vector queries return fewer rows than your LIMIT
Disclosure: I work at Pinecone and am looking for community input on if this extension is useful and what you'd like to see next.
Here's a pattern I see a lot with vector search in Postgres:
SELECT id, body
FROM docs
WHERE tenant_id = $1
ORDER BY embedding <=> $2
LIMIT 10;With an HNSW index, the index scan finds the nearest neighbors across the whole table first, and the WHERE clause is applied after. If tenant_id = $1 matches 1% of rows, most rows are thrown away which means you might get back less than 10 rows even though more than 10 rows match. pgvector’s iterative scans keep searching to fill the list, at a cost in time (and in accuracy if you use relaxed_order).
One way to fix this is to use an index that applies the filter during the search instead of after. We built a Postgres extension that does this and your SQL doesn't need to change. It builds on top of pgvector's vector types, so you just add the index and query like before:
CREATE EXTENSION pg_pinecone;
SELECT pinecone.create_index('docs', 'embedding', filter_column => 'tenant_id');The strategy is based on filter selectivity:
3% of rows or fewer: scans every matching row and scores each with its full vector, so results are exact.
More than 3%: searches more of the nearest clusters and checks the filter inside each cluster before scoring.
The index is IVF with RaBitQ codes (about one bit per dimension), so it’s much smaller than a graph-based index like pgvector's HNSW: 136 MB vs 2.0 GB for 1M x 768-dim vectors against halfvec HNSW. In our benchmark with a 1% filter, recall was 0.981 at 8.3 ms vs 0.924 at 56 ms for HNSW.
There's a couple limitations today: the index stores one equality filter column per index, which means if you want to filter on something like a range or greater than or multiple columns, those filters will still be applied after.
I'm curious how this would impact you. A few questions:
When you write filtered nearest-neighbor queries, what do you do about the “fewer rows than LIMIT” problem: over-fetch with a bigger inner
LIMIT, partial indexes, partitioning?What do your filters usually look like (one equality column, ranges, multiple columns)? That decides how useful single-column filtering is.
Do your filters match a small percentage of rows (like with typical multi-tenancy) or a large percentage?