Why Filtered Vector Search Misses Results: Exact Baselines, Iterative Scans and pgvector Acceptance Tests

Too few vector-search results do not prove that evidence is absent, and a full result set does not prove that exact neighbors were recovered. An eight-vector example for PostgreSQL 18 and pgvector 0.8.7 compares exact filtered calculation with bounded approximate search, then tests sparse filters, missed neighbors, version mismatches and exhausted budgets.

For vector search constrained by tenant or document status, establish an exact baseline on the same eligible set before evaluating the approximate index’s result count, recall and latency. Increasing LIMIT or receiving three results does not establish a fix. Distinguish filtering, search termination and changing data versions before choosing exact calculation, a larger bounded search or a different index scope.

Separate result count, neighbor recall and business evidence

A request for three current equipment instructions returns one result. Perhaps only one is visible, or perhaps search stopped too early. Even three returned results can omit the closest eligible item. First identify whether acceptance concerns count, distance ordering or evidence needed to answer the question. These outcomes can differ; an HTTP success status cannot substitute for any of them.

The environment here is PostgreSQL 18 with pgvector 0.8.7, using HNSW, one document-embedding version and Euclidean distance, or L2. HNSW means Hierarchical Navigable Small World: an approximate method that reduces distance calculations through graph traversal. The original paper describes its hierarchy and bounded candidate search.[2] Approximation permits missed exact neighbors; it does not permit arbitrary distance calculations.

Assume a trusted backend has already established the tenant and allowed document states, queries are read-only, and vectors and metadata reside in the same database. Inputs include the query vector, tenant, status, result limit k, data snapshot and retrieval-configuration version. Outputs should include chunk ID, source revision, distance, actual count and completion status. This is a proposed application contract, not a claim that the database automatically supplies these business fields.

All vectors, time budgets and acceptance thresholds below are constructed examples whose arithmetic has been checked. No performance experiment was run on the stated database deployment. Two-dimensional vectors make set changes visible; they do not represent a real semantic model. High-dimensional embeddings, hybrid retrieval, reranking and generated answers require separate business-sample acceptance. These eight rows establish no product accuracy rate.

Eight records explain why correct conditions can still yield too few results

Fix the query vector at q=(0,0). Each record contains id, tenant, status, source_revision and embedding. D1 belongs to B, is active and has vector (1,0); D2 belongs to B, is active and has (2,0); D3 belongs to A, is active and has (3,0); D4 belongs to A, is expired and has (4,0). D5 belongs to B, is active and has (5,0). D6, D7 and D8 belong to A and are active, with vectors (6,0), (7,0) and (8,0). Initially every source revision is one.

L2 is the square root of the sum of squared coordinate differences, so these records have distances one through eight from q. The request specifies tenant A, active status and k=3. Its eligible set is D3, D6, D7 and D8; the exact top three are D3, D6 and D7, at distances three, six and seven. Although D4 is closer than some eligible items, its expired status excludes it. Filling a count cannot justify returning it.

Now simulate a deterministic, reproducible incorrect workflow: retain only the nearest four records globally, then apply tenant and status conditions. The global four are D1, D2, D3 and D4; filtering leaves only D3. This asks a different question from finding the nearest three within the eligible set. Even perfectly recovering the global nearest four cannot guarantee the filtered top three.

This manual truncation illustrates query semantics; it does not predict HNSW’s node visitation order. The pgvector 0.8.7 documentation explains that filtering is applied after an approximate index scan and can therefore produce too few results. Iterative scans can continue until enough results are found or a scan limit is reached.[1] Actual omissions also depend on graph structure, data distribution and configuration. The example is not a fixed database execution trace.

Compare the single returned item D3 with the eligible exact top three. Neighbor recall is one divided by three. Count fulfillment is also one divided by three, but that equality is incidental. A separate hypothetical result set D3, D7 and D8 fills the requested count while achieving neighbor recall of only two thirds. Keeping both counterexamples prevents acceptance from treating three returned rows as proof of repair.

Establish a trustworthy exact baseline first

The baseline and tested query must share tenant, status, query vector, distance function and data version. Comparing an A-scoped approximate query against an administrator’s unrestricted database result creates meaningless omissions. Identity and authorization are prerequisites. Optimizing search scope does not authorize bypassing isolation, and an ordinary WHERE clause is not a complete security mechanism.

For a small acceptance test, put an approved finite snapshot into a comparison table without an approximate index. Calculate every eligible vector’s distance, then sort by distance and a stable identifier. Another approach uses a materialized common table expression to form all eligible rows before calculating and sorting distances in an outer query. Whichever approach is chosen, inspect the plan to confirm that the supposed baseline has not reused an approximate nearest-neighbor index.

A structural query example is: WITH eligible AS MATERIALIZED (SELECT id, embedding FROM chunks WHERE tenant_id = 'A' AND status = 'active') SELECT id, embedding <-> '[0,0]' AS distance FROM eligible ORDER BY distance, id LIMIT 3. A real system must parameterize input, use its actual fields and restricted identity, and inspect the plan. This illustrative SQL was not run for this article; its expected output follows from the eight records above.

Compare exact and approximate results on a frozen snapshot or within the same read-only Repeatable Read transaction. PostgreSQL 18 maintains the corresponding snapshot view within that transaction.[5] This prevents data changes from contaminating the comparison, but does not establish that every source record has arrived or remove required revocation checks at delivery. Long transactions impose maintenance costs; controlled static samples may suit large tests better.

Let E be the exact top-k set and A the returned eligible set. Neighbor recall is the size of their intersection divided by the size of E. If fewer than k eligible records exist, use the actual exact-result count as the denominator rather than inventing missing neighbors. If E is empty, record “no eligible candidates” separately instead of treating zero divided by zero as a perfect score. Define acceptable ties at the cutoff in advance to avoid labeling equivalent results as regressions.

The two implementation paths have different costs

The first path applies structured conditions to reduce the population, then calculates exact distances over the remaining vectors. A conventional condition index may be sufficient when a tenant or document type accounts for few records. This provides a clear result baseline, but computation grows with the filtered population. A fast eight-record example does not establish the same deadline for a million eligible records.

The second path retains conditions on an approximate index, enables tested iterative search and bounds both work and elapsed time. It suits a still-large eligible population where the application can accept validated neighbor error. Measure computational savings together with eligible-result quality. Very selective conditions can increase the work needed to find enough candidates; testing only unfiltered queries misses that behavior.

For the version used here, consider SET LOCAL hnsw.iterative_scan = strict_order within a transaction, while recording hnsw.ef_search, hnsw.max_scan_tuples and memory-related settings.[1] strict_order constrains distance ordering among returned results; it does not make approximate search exact. Larger scans are not the only repair. A request’s tuning must also not accidentally persist as session state for the next tenant.

A few stable categories may justify partial indexes. Many categories, or a need for clearer workload isolation, may justify evaluating partitions or separate tables. PostgreSQL partial indexes cover a predicate-defined subset; queries must match their applicability conditions, and changing distributions create maintenance work.[4] An independent index for every user-selected filter is usually unmanageable. Start with stable boundaries supported by workload evidence.

On the eight-record acceptance dataset, the first path should produce D3, D6 and D7. Do not invent an HNSW run for the second path: actually record whether it recovers those items and how scanning and latency change. If a small tenant repeatedly requires scanning many irrelevant vectors, it may be routed to an accepted exact path. Such routing still needs scale conditions, an owner and regression evidence.

Locate omissions through execution evidence

For each test, retain the query ID, identity scope, expected eligible population, k, database and extension versions, index configuration, actual returned IDs and source revisions. Also record whether status filtering, source deletion or application deduplication removed candidates. Full document text usually need not enter operational logs. A controlled source reference supports investigation without turning tuning logs into another sensitive repository.

PostgreSQL distinguishes EXPLAIN, which displays a plan, from EXPLAIN ANALYZE, which actually executes the query and reports node-level row counts and execution information.[3] Run read-only diagnostics in an approved environment with actual roles and parameters recorded. Check whether an approximate index was used, how many rows survived filtering and whether a separate sort occurred. Record client end-to-end latency as well: estimated plan costs are not promises in milliseconds.

Many rows removed by filtering do not by themselves prove filtering caused the problem. Run the exact baseline on the same snapshot first. If it also lacks the target, investigate source loading, status definitions and embedding versions. If the baseline contains it but approximate search does not, investigate search scope. If retrieval returned it but final context omitted it, investigate deduplication and truncation. Evidence should locate the repair; changing the embedding model is not the default answer.

The existing enterprise knowledge-base hybrid retrieval method follows evidence across lexical search, vector search, fusion and reranking. This article adds a comparison inside the vector channel, between exact and index results on a fixed eligible set. Combine the two: establish candidate recovery under agreed conditions, then follow candidates into the answer. A downstream reranker cannot score a chunk that was never retrieved.

Latency tests should cover high- and low-share filters, large and small tenants, and no-result conditions, with concurrency, warm or cold caches and query-vector sources fixed. Report P95, timeouts, actual count and neighbor recall together. Timed-out requests remain in the request ledger. Showing only the mean latency of successful requests after raising search parameters conceals the degradation paths that most need evaluation.

Four failure tests need a repair and a repeat test

Test one is a sparse filter. Use the original eight records, tenant A, active status and k=3; the exact expectation is D3, D6 and D7. Deliberately run global-top-four-then-filter first. Observe only D3 and mark it as failing the requirement. Repair through calculation within the eligible set or continued search on an accepted approximate path. Repeat with the original and more selective samples, recording count, recall and deadline outcomes separately.

Test two fills the count while missing a neighbor. Feed the evaluator a preset result D3, D7 and D8, at distances three, seven and eight. The expected evaluation is count passed and neighbor recall two thirds; these must not collapse into one passing value. This does not claim that the database must return that combination. It tests whether the acceptance program recognizes such an error. After correcting metric logic, apply the same comparison to actual index results.

Test three has too few eligible records by design. In a new controlled branch, expire D7 and D8 while keeping D3 and D6 active. The exact expectation is two results. Returning two should mean that the eligible population is too small, not automatically trigger larger scans. A third result calls for investigation of expired or other-tenant records. Restore the statuses and retest the three-result expectation so the repair does not classify every short result as normal.

Test four uses mismatched versions. Save the exact set at snapshot V1, then expire D6 to create V2. The test system should reject a comparison between the V1 baseline and V2 index results as incomparable, rather than count it as recall degradation. With both queries aligned to V2, the exact top three are D3, D7 and D8. Repair version binding, repeat the change sequence, and retain both sets with their respective versions.

Each repair must retain the original failing query and a positive case. More scanning might fix the first test; it cannot fix the third test’s genuinely limited eligible population or the fourth test’s invalid comparison. Linking trigger, expected result, observed evidence, change and repeat test is what separates algorithmic limitations, implementation defects and evidence that does not exist.

Handle exhausted budgets, permission changes and invalid vectors explicitly

Add a budget branch with a constructed service deadline of 200 milliseconds. This is an example team agreement, not a universal standard. Apply controlled delay or sufficient load in an isolated test environment to trigger the deadline. Expect an explicit incomplete status, or a separately accepted fallback with enough remaining budget. Do not return one item and describe it as an exhaustive search of relevant material. Record whether cancellation actually reaches the database.

Scan settings do not provide complete resource isolation. Per-request limits, concurrency and shared tenant capacity jointly determine load. If larger searches restore recall but time out other requests, compare narrower partitions, selective exact calculation or reduced query scope. Never automatically remove tenant or status conditions during pressure to “restore success”; that changes the business and authorization boundary.

Permissions or validity may change after retrieval but before reranking. Frozen snapshots help quality comparisons, while production delivery must follow the actual revocation contract. If a subsequent check fails, discard affected evidence and report the state. Do not send unauthorized candidate text to an external model and rely on filtering the final answer. Internal index-node traversal and authorization to deliver content are different boundaries.

Input acceptance should cover wrong dimensions, non-finite values, missing vectors, wrong distance metrics, and different embedding versions with identical dimensions. Clues include quarantined imports, query-configuration mismatches and degradation in the exact baseline too. Correct representations and source state, then rebuild or update affected records and recheck ID sets. Increasing candidate count cannot repair all these conditions.

When distances tie, a stable ID makes exact testing reproducible; it does not imply stronger business relevance. If k cuts through a tie, record mandatory closer items and an interchangeable boundary set. Any eligible item from that tied set should not count as an index-quality regression. Source authority, revision and content support still determine evidence priority.

Maintain evidence as scale and data change

Retain acceptance curves grouped at least by eligible population and selectivity. Here selectivity means the fraction of the searched population satisfying the conditions, not model confidence. Two requests may both ask for ten results while having one hundred and one million eligible records respectively. One global average cannot explain the computation, memory and omission risks of the same parameter in both situations.

Rerun representative samples and inspect index maintenance after continued deletion, updates, re-embedding or changes in tenant distribution. Include maintenance windows, build-time resource contention, index size and fallback capacity in costs. Monitoring only new-document counts will miss stale status. Sample document IDs, revisions and validity conditions against authoritative sources.

Release a complete configuration package: distance metric, embedding version, condition template, search settings, result limit, deadline, fallback rules and quality thresholds. Roll back to the previously accepted package rather than merely lowering one parameter. If fallback uses exact retrieval, establish that expected load is supportable. Unvalidated full-table calculation is not an automatically safe backup.

A reusable acceptance record should contain query and filter scope; same-version exact set; actual eligible set; count fulfillment; neighbor recall; tie handling; timeout or termination reason; client latency; whether source evidence answers the question; and repair and repeat-test receipts. Retain at least one empty set, one set smaller than k, one full-count result missing a neighbor and one version-change sample. Every number should trace back to record IDs.

Make deployment decisions by use. Approximate omissions may be acceptable for reference material a person can inspect. Tasks that must find every relevant clause or fully reconcile records require structured exhaustive queries or another completeness mechanism: nearest-neighbor output alone cannot prove exhaustive coverage. Put that scope in the interface contract so retrieval-speed improvements are not mistaken for complete business evidence.

References

  1. [1] pgvector — README v0.8.7: Filtering and Iterative Index Scans
  2. [2] Malkov & Yashunin — Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs (2018, v4)
  3. [3] PostgreSQL 18 — Using EXPLAIN
  4. [4] PostgreSQL 18 — Partial Indexes
  5. [5] PostgreSQL 18 — Transaction Isolation
Back to insights
鲁ICP备2024109755号-2
Drag to move. Right-click, touch and hold, or press Shift+F10 to choose a corner.