I once stress-tested a retrieval service. Pure vector queries had a P99 of 20 ms; adding a single filter condition, “only look at documents in this department,” pushed it to 300 ms, and recall dropped too. The code hadn’t changed, the index hadn’t changed—just one extra filter parameter. The cause turned out to be: on the filtered subset, the vector store no longer used the graph index and degraded to a scan one by one.
After that, when I choose a vector store, the first thing I do isn’t compare whose pure ANN is faster—it’s test ANN with filter conditions.
The easiest place to go off track in selection discussions is evaluating “vector database” as a standalone component that must be newly introduced. It’s really just a storage and indexing implementation at the end of the offline pipeline from post 4. The basis for the decision should come from three things: how big the corpus is, what the queries look like, and what the team can maintain.
Post 7/15 of this series · Previous: Embedding selection: don’t just look at benchmark scores · Next: Hybrid retrieval: sparse, dense, and score fusion
First understand what ANN is sacrificing
Exact nearest neighbor computes the similarity between the query vector and every vector in the store, with complexity O(N·d). Approximate nearest neighbor (ANN) uses an index structure to replace most of those distance computations, at the cost of no longer guaranteeing that it finds the true nearest neighbor—so it can only be measured by recall. So every ANN approach has to deal with this triangle:
1 | 召回率(recall@K) |
The three quantities constrain each other pairwise; tuning is basically moving around within this triangle. Understanding how each index trades off is more useful than memorizing parameter names.
Flat / brute-force scan. Lossless, no index build cost, and completely sufficient from tens of thousands to hundreds of thousands of vectors. After normalization, one matrix multiplication computes cosine similarity—a matter of tens of milliseconds. The small-corpus scenario mentioned in post 4 (a few hundred chunks) doesn’t even need a database; just read it into memory at startup.
HNSW (hierarchical navigable small world graph). Builds vectors into a multi-layer graph, and queries greedily walk from the top-layer entry point down to the bottom layer. The key parameters are M (number of neighbors per node), efConstruction (candidate width during graph construction), and efSearch (candidate width during query). Increasing M makes the graph denser, uses more memory, and improves recall; efSearch is an online-adjustable knob—turn it up and it visits more nodes, with recall and latency rising together. Its advantage is fast queries and high recall; the cost is that the graph structure must reside in memory, construction is slow, and deletion and updates are awkward.
IVF (inverted file index). First clusters into nlist buckets, and at query time scans only the nearest nprobe buckets. Few parameters, low memory, fast construction, but the ceiling is determined by clustering quality, and centers must be retrained after the data distribution drifts. Going from nprobe = 1 to 10 changes recall and latency almost linearly—a very intuitive adjustment lever.
PQ (product quantization). Splits high-dimensional vectors into segments, quantizes each segment into a codebook ID, and approximates distance with compact codes. The main purpose is to compress storage so that tens of millions to hundreds of millions of vectors fit in memory; the cost is distance distortion and lower recall. A common combination is IVF-PQ for coarse ranking, then exact recomputation of candidates using the original vectors.
DiskANN / disk-based graph indexes. The graph lives on SSD, with only a small number of hub nodes kept in memory—trading IO for memory. Suitable for very large scale with limited budget, and very sensitive to disk random-read performance.
| Index | Recall | Latency | Memory | Suitable scale | Main risk |
|---|---|---|---|---|---|
| Flat | 100% | Linear with N | Low | Up to ~100K | Suddenly slows down as scale grows |
| HNSW | High | Very low | High | 1M–10M | Memory cost, updates and deletes |
| IVF / IVF-PQ | Medium–high | Low | Medium–low | 10M–100M | Distribution drift, quantization distortion |
| DiskANN-like | Medium–high | Medium | Low | 100M+ | Depends on SSD performance |
Don’t copy default parameter values—sweep them yourself. I usually fix an evaluation set, sweep a parameter grid, and plot the “recall@20 — P99 latency” curve, taking the knee rather than the maximum:
1 | grid = [(ef, recall_at_20(ef), p99_latency(ef)) |
A very practical lesson: many systems set efSearch very high to chase 99% ANN recall, but what really determines end-to-end quality is the five snippets finally sent into the model. The gain from raising ANN recall from 95% to 99% is often smaller than adding a reranking layer afterward. Recall depth and ranking precision need to share the budget together; post 9 will expand on this.
Filtering: the most fragile step
Post 5 said that acl must be pushed down to the recall stage. The problem is that combining filtering with ANN has two implementations, and they perform very differently.
Pre-filter first selects the candidate set by condition, then does ANN within the subset. When the subset is small, some implementations simply degrade to brute-force scan; when the subset is large, the index must support “skipping nodes that don’t satisfy the condition,” otherwise graph traversal gets bogged down by large numbers of invalid nodes.
Post-filter first takes top_k by ANN, then filters. It’s simple to implement, but after filtering there may be only two or three left, leaving thin context; the larger top_k is set, the more is wasted.
A more insidious problem is that recall drops when filter selectivity is high. HNSW’s graph is built on the full dataset, and the path from the entry point to the target node may pass through many filtered-out nodes; the graph gets cut to pieces and connectivity degrades. Some engines offer “separate indexes per partition” or “filter-aware graphs” to mitigate this.
So when I test, I always cover these groups: no filter, 50% remaining after filtering, 10% remaining, 1% remaining. Testing only unfiltered performance is as good as not testing. Also confirm that the filter field itself is indexed—when a scalar field has no index, the filtering step is a full table scan.
Four axes for selection
Scale: growth rate matters more
Up to ~100K, Flat plus an in-memory matrix is enough—don’t introduce a new component for it; at the million level, HNSW is mainstream; above ten million, start considering quantization, sharding, and disk indexes. But more important than current scale is growth rate. If it grows tenfold in half a year, validate the sharding plan now rather than migrating after memory fills up.
Query shape: determines selection more than QPS
Whether you need hybrid retrieval (BM25 and vectors together), multiple vectors, scalar filtering, grouping by doc_id and deduplicating to take the best snippet, or multi-tenant isolation. These items often determine the final choice more than “pure vector QPS.”
Operational boundary: who gets up at midnight to restart it
Does anyone on the team want to maintain a distributed system, and can they accept separate backup, monitoring, upgrades, and capacity planning? If the business data is already in Postgres, pgvector lets vectors, metadata, transactions, and permissions stay in the same database, and the operational cost may be an order of magnitude lower. The trade-off is that at very large scale, performance and indexing capability are inferior to dedicated engines.
Consistency and updates: are deletes really deletes?
When documents are frequently added and deleted, are deletions in the index hard deletes or soft deletes? Can the service continue during a rebuild? Can active_version be switched atomically for dual-index canary rollout (the approach in article 4)? These items are critical in content-oriented systems, yet they rarely appear in selection comparison tables.
Based on my own understanding, the common options can be roughly grouped as follows:
| Option | Form | Suitable for | Main limitations |
|---|---|---|---|
| In-memory matrix / FAISS library | Embedded | Small corpora, offline evaluation, experiments | No persistence or concurrency management; you have to wrap it yourself |
pgvector |
Postgres extension | Existing PG, up to millions of records, strong filtering and transactions | Large-scale ANN performance and memory |
| Elasticsearch / OpenSearch | Search engine plus vectors | Existing ES, hybrid sparse + dense retrieval | Relatively limited room for vector index tuning |
| Qdrant / Weaviate / Milvus | Dedicated vector database | Millions of records and above, multi-tenant, complex filtering | An extra system to operate |
| Managed cloud retrieval service | Managed | No desire to operate, fluctuating throughput | Cost, data compliance, vendor lock-in |
There is no “best” in the table, only trade-offs under constraints. The most cost-effective selection I ever made was not to adopt a vector database: an internal knowledge base had only a few hundred documents, vectors were stored in sqlite, loaded into a numpy matrix at startup, and cosine similarity was computed by brute force, producing results in tens of milliseconds, with a full rebuild taking a few minutes. What was saved was an entire set of deployment, backup, and version compatibility work. It would not be too late to migrate when the scale really reaches the hundreds of thousands.
Four sets of data that must be measured before launch
No matter which option is finally chosen, I keep these results on file as a baseline for future tuning:
- Recall@20 and P99 for pure ANN, using the same manually labeled evaluation set, not synthetic vectors;
- Recall and latency with filter conditions and selectivity at 50% / 10% / 1%;
- Writes and rebuilds: full build time, incremental write throughput, and space reclamation after deletion;
- Concurrency tail latency: P99 rather than average when QPS is pushed to the expected peak, and degradation behavior after query timeout.
The fourth set is the easiest to skip. A vector retrieval timeout must not cause the entire RAG request to fail. My degradation order is: lower efSearch and retry once, fall back to BM25 single-path results, and finally return “temporarily unable to retrieve” rather than letting the model answer out of thin air. This path must actually be exercised in load testing; otherwise, the first online timeout will be a hallucinated output.
Some pain points cannot be solved by switching vector databases
The value of dedicated vector databases is concentrated in scale: high-dimensional indexing, filter-aware ANN, horizontal scaling, multi-tenant isolation, and incremental updates. The cost is introducing a new stateful component, along with the backup, upgrade, capacity, and data synchronization that come with it. Embedded solutions are simple and controllable, but once the corpus or concurrency increases by an order of magnitude, all the missing capabilities must be filled in by yourself.
There is another judgment worth writing down: if your main pain point is “exact string cannot be found,” switching vector databases will not solve it; that is a problem of representation and retrieval channels. If the pain point is “the correct answer ranks seventh among the top ten recalled,” that is a ranking problem. Looking at the storage layer and the ranking layer separately can save a lot of unnecessary migration.
Suppose the index and vector database are both chosen; the pure vector channel will still fail on error codes, IDs, and version numbers. The next article will discuss how to add a sparse retrieval path and how exactly to merge the results of the two paths. Before that, answer a simpler question first: in your database, how many times do P99 latencies differ between queries with acl filtering and queries without filtering?
Comments