Why Your pgvector Filtered Search Returns Fewer Results Than LIMIT A pgvector filtered search returns fewer rows than its LIMIT because HNSW gathers its nearest candidates first — 40 at the default hnsw.ef_search — and the WHERE clause discards rows only afterwards, so a filter matching 10% of rows leaves about 4 results on average, according to pgvector's README. In an October write-up on DEV Community, developer jidonglab tested a table of 1.2 million chunks across 40 tenants and found that of 400 queries asking for ten rows, 147 came back short and 52 came back empty on default settings, with every empty result belonging to a tenant holding less than 3% of the table. pgvector 0.8.0 and later can keep searching when a filter leaves results short, but iterative index scans are off by default, and hnsw.ef_search tops out at 1,000, so raising it alone cannot reliably fill a LIMIT of 10 for very narrow filters. Before you buy a separate vector database or blame the embedding model, count the rows your retrieval query returns. The repair is usually cheap if you make the changes in the right order. - At the default setting, a filter matching 2% of rows returns nothing at all about 45% of the time if matches are spread evenly. - pgvector 0.8.0 and later can keep searching when a filter leaves you short, but iterative index scans are switched off by default. - The hnsw.ef search setting tops out at 1,000, so raising it alone can't reliably fill a LIMIT of 10 for very narrow filters. - A partial HNSW index suits a few fixed filter values, but Postgres may not use it for a parameterized WHERE clause. - For very small tenants, fetching their rows first and ranking every one gives exact results. - Any primary key or unique constraint on a partitioned table has to include the partition column. You ask for ten chunks and Postgres hands back four. When a pgvector filtered search returns fewer results than limit, the usual cause is the order of operations. The HNSW index gathers its nearest candidates first, 40 of them at the default hnsw.ef search , and your WHERE clause only gets to throw rows away afterwards. If one row in ten passes the filter, about four survive on average. The pgvector README says so itself: "If a condition matches 10% of rows, with HNSW and the default hnsw.ef search of 40, only 4 rows will match on average." And four is the middle of a spread. Some searches will get seven rows and others one. If matching rows are scattered evenly, your chance of getting all ten is about one in 200. For a RAG product this is a nasty way to fail. Your code receives a valid result set, the model writes a fluent answer from whatever arrived, and the first person to notice is a customer. HNSW is a graph. A search walks it toward your query vector while keeping a shortlist of the closest points found so far, and hnsw.ef search sets the length of that shortlist. Postgres takes rows from it in distance order and tests each one against your filter. With iterative scanning off, the search is over once the shortlist is used up. Why Is My RAG Retrieving Irrelevant Chunks, and Which Fix Comes First? https://startupfortune.com/why-is-my-rag-retrieving-irrelevant-chunks-and-which-fix-comes-first/ Irrelevant RAG chunks can come from a setting you've never touched. In pgvector's default HNSW setup, a filter matching 10% of rows leaves about four results on average, so the passage you need may vanish before any reranker or language model sees it. - why RAG retrieves irrelevant document chunks https://startupfortune.com/why-is-my-rag-retrieving-irrelevant-chunks-and-which-fix-comes-first/ - how to fix RAG PDF table retrieval https://startupfortune.com/why-is-my-rag-retrieving-irrelevant-chunks-and-which-fix-comes-first/ Your LIMIT doesn't make the shortlist any longer. Ask for 100 rows at the default setting and you'll get no more than the shortlist holds, even with no filter at all. Stacked filters shrink things fast. Say a tenant owns 10% of your chunks and a date range keeps 20% of those. If the two are unrelated, only 2% of the table qualifies, and the default search will find 0.8 matching rows on average. Real data is lumpier than that. A customer asking about their own product will probably land near their own documents and do better than the arithmetic predicts. A question phrased like another customer's content can do far worse. A developer posting as jidonglab on DEV Community put numbers on it in an October write-up. The test table held 1.2 million chunks across 40 tenants, from one with 410,000 chunks down to one with 600. Across 400 queries asking for ten rows each, 147 came back short on default settings and 52 came back empty. Every empty result belonged to a tenant holding less than 3% of the table. That's one developer's own test, so don't treat the counts as a benchmark. The pattern should still worry any founder, because your newest customer usually owns the smallest slice of the table. They get the thinnest retrieval during the very weeks they're deciding whether your product works. Check the query plan before you change a setting Run EXPLAIN ANALYZE, BUFFERS on the exact query your app sends, with a filter value that has been coming up short. You're looking for an index scan on your HNSW index with a line reading Rows Removed by Filter underneath. If the planner has picked an ordinary B-tree on the filter column and sorted the matches by distance, that search is exact, and missing rows have some other explanation. The planner can also change its mind in strange places. A public investigation on GitHub by the user tharindu-sankalpa ran PostgreSQL 18.6 and pgvector 0.8.7 on about 2.5 million vectors, synthetically expanded from 100,105 real text chunks. In that setup, a filtered query asking for 40 rows returned 18, quickly and without an error. Moving from a LIMIT of 40 to 41 flipped the plan, and query time jumped from 1.5 milliseconds to 358. Why Is My Prompt Cache Hit Rate Low and How Do I Get the Discount Back? https://startupfortune.com/why-is-my-prompt-cache-hit-rate-low-and-how-do-i-get-the-discount-back/ ProjectDiscovery's security testing platform, Neo, kept changing working memory inside the prompt section meant to be cached. After the team moved that material to the tail and made other fixes, the weekly hit rate jumped from 7.6% to 73.7% in one week. - why is my prompt cache hit rate low https://startupfortune.com/why-is-my-prompt-cache-hit-rate-low-and-how-do-i-get-the-discount-back/ - how to restore prompt caching discount https://startupfortune.com/why-is-my-prompt-cache-hit-rate-low-and-how-do-i-get-the-discount-back/ The author traced the trouble with the planner to missing statistics. Postgres gathers statistics on an indexed expression only when ANALYZE runs after that index exists, and the loading routine insert the data, build the indexes, start serving never ran it. If you filter on something like metadata- 'tenant' , run ANALYZE after creating its index. The data was largely synthetic, so borrow the diagnosis and leave the timings. Check your version too, with SELECT extversion FROM pg extension WHERE extname = 'vector'; . Iterative scans arrived in pgvector 0.8.0 on October 30, 2024. Move to a current release while you're there: the changelog shows 0.8.2 fixing a buffer overflow in parallel HNSW builds, 0.8.3 fixing index corruption during HNSW vacuuming, and 0.8.7 arriving on October 1, 2026. Managed database providers ship on their own schedules, and after the new package is installed you still need ALTER EXTENSION vector UPDATE; . Turn on the pgvector iterative index scan first This should be your first change to the search itself, and it ships switched off. Set hnsw.iterative scan and a search that runs short goes back into the graph for more candidates. It carries on until your LIMIT is filled or it reaches a ceiling on scanning or memory. It comes first because the extra work only happens when the first batch isn't enough. A tenant that owns a third of the table will usually fill ten rows from the opening shortlist and stop there. In the jidonglab test, switching to relaxed order without touching ef search cut the short results from 147 to three and removed every empty one. The 95th percentile latency moved from 18 milliseconds to 24. You get two modes. strict order returns rows in exact distance order. relaxed order lets some arrive slightly out of order in exchange for better recall, and I'd pick it for most RAG work, where the chunks are headed into a reranker or a single prompt anyway. If order does matter, wrap the search in a materialized CTE and sort again. Run this inside a transaction that starts with SET LOCAL hnsw.iterative scan = relaxed order; : js WITH hits AS MATERIALIZED SELECT id, embedding <= $1 AS distance FROM chunks WHERE tenant id = $2 ORDER BY distance LIMIT 10 SELECT FROM hits ORDER BY distance + 0; The odd + 0 is there for Postgres 17 and later, according to the README. If you also cut results off at a maximum distance, put that condition outside the CTE. Left inside, it can send the scan hunting for rows that don't exist until it hits its ceiling. The transaction matters if you pool connections. A plain session SET behind a transaction-mode pooler such as PgBouncer can stick to a server connection that your next query never touches, while someone else's query inherits it. When the scan still comes up short The main ceiling is hnsw.max scan tuples , 20,000 by default. It's approximate and doesn't limit the first pass. Take that 600-chunk tenant in a table of 1.2 million: its share is 0.05%, so 20,000 visited rows would hold about ten of its chunks if they were evenly spread. Filling a LIMIT of 10 becomes close to a coin toss. Raise the ceiling, and if recall doesn't improve, raise hnsw.scan mem multiplier , which starts at 1 and allows the scan a larger multiple of work mem . For a filter that narrow, I'd skip the graph altogether. Fetch the tenant's rows through a B-tree index, then rank every one of them: WITH own AS MATERIALIZED SELECT id, embedding FROM chunks WHERE tenant id = $1 SELECT id FROM own ORDER BY embedding <= $2 LIMIT 10; The result is exact. The jidonglab write-up measured 4 milliseconds for an exact scan of its smallest tenant, and combining that route with iterative scans left no short queries. The known correct chunk reached the top ten in 368 of the 400 searches, up from 241 at the start. On IVFFlat indexes the equivalent settings are ivfflat.iterative scan , which offers relaxed ordering only, and ivfflat.max probes . What hnsw.ef search can and can't fix when filtering Raising ef search is the reflex fix, partly because it's one line: SET LOCAL hnsw.ef search = 100; . The tempting formula is LIMIT divided by the share of rows that match. For ten results at 10%, that gives 100. At 100 you'd get ten matches on average, which still leaves roughly 45% of searches short. You'd need somewhere around 160 candidates before about 95 searches in 100 come back full, and around 800 for a filter matching 2%. The setting stops at 1,000. At a 1% match rate, even the maximum only averages ten, and below that it can't fill your LIMIT on average. These figures assume matches are spread independently of similarity, so use them to size the problem and then measure your own. The bill lands on every query that uses the setting, including those from large tenants that never had a problem. In the same DEV Community test, an ef search of 400 still left 19 queries short, with 95th percentile latency at 61 milliseconds. At 1,000, nine were short and latency reached 140 milliseconds. The setting still has a proper job, which is recall: how many of the true nearest rows the index finds. To measure it, run a sample of real queries twice, once normally and once inside a transaction with SET LOCAL enable indexscan = off; , which the README suggests for getting exact results. Count the overlap. If a full set of ten keeps missing chunks that the exact search finds, raise ef search in steps until the overlap is good enough or the latency isn't. Partial indexes suit filters you can name in advance A partial index builds the graph from matching rows only, so that condition has nothing left to discard: CREATE INDEX CONCURRENTLY ON chunks USING hnsw embedding vector cosine ops WHERE tenant id = 42 ; Use it for a handful of stable, busy values. One enormous customer is a good candidate, and so is a public help center that every anonymous visitor searches. Any further conditions in the query are still applied after the scan. The planner is picky here. PostgreSQL's documentation says a partial index can be used only if the system can tell at planning time that your WHERE clause implies the index condition, and warns that parameterized clauses don't work with one. This catches apps using prepared statements, where a plan built around the real value may use the index and a generic plan can't. Test with SET plan cache mode = force generic plan; and read the plan. If the index disappears, write that fixed value into the SQL from a list your code controls, never from raw user input. Each extra index also has to be stored, cached and updated on writes. Five of them can be sensible. Five hundred, one per customer, is a maintenance job you've handed yourself. Watch concurrent builds as well: a failed one leaves an invalid index that queries ignore but writes keep paying for, so drop it and build again. Partition when one filter shapes the whole table If nearly every query filters on the same column and it has many values, split the table on it. With PARTITION BY LIST tenant id and an HNSW index declared on the parent, each partition gets its own graph, and Postgres skips the partitions your WHERE clause rules out. The PostgreSQL documentation says the planner generally copes with up to a few thousand partitions fairly well, provided typical queries prune all but a few. This is schema work. Any primary key or unique constraint has to include the partition column. CREATE INDEX CONCURRENTLY isn't available on the partitioned parent, so a live system needs the longer route: create the parent index with ON ONLY , build each partition's index concurrently, then attach them. An existing table also has to be moved into the new layout or attached to it as a partition. Hash partitioning only gets you part of the way. Put 1,000 equal-sized tenants into 20 hash partitions and each tenant goes from 0.1% of the table to about 2% of its partition. The query is still filtering after the scan, so iterative scanning stays on. My order for a young RAG product is short. Upgrade, run ANALYZE and read the plan. Turn on relaxed order , give tiny tenants the exact route, and tune ef search against measured recall. Reach for a partial index when a few values carry heavy traffic and are still slow or short, and save partitioning for the point where your tenant count and table size justify a migration. Whatever you choose, log the number of rows returned next to the number requested, broken down by tenant. Also read: How to Remove a UCC Lien After Payoff When Your Lender Won't File https://startupfortune.com/how-to-remove-a-ucc-lien-after-payoff-when-your-lender-wont-file/ • How to Prevent Duplicate Tool Calls in AI Agents After a Timeout https://startupfortune.com/how-to-prevent-duplicate-tool-calls-in-ai-agents-after-a-timeout/ • How Does Visa Compelling Evidence 3.0 Work and What Should SaaS Teams Log? https://startupfortune.com/how-does-visa-compelling-evidence-30-work-and-what-should-saas-teams-log/ This article is posted in AI News https://startupfortune.com/category/ai/ , check it out for more related stories. Join the discussion Open in the community → https://startupfortune.com/community/ Almost there. Sign in and your reply posts straight away.