AI Engineering · Concept Library · Free article
Vector Search
Vector search finds the stored vectors nearest to a query vector. Doing that exactly means comparing against every one, which is fine at thousands and a wall at millions, so production systems use an approximate index that visits a clever fraction instead. Why it gives up being exact, how HNSW and IVF actually work, and the tuning, compression, and filtering that decide whether it holds up under real traffic.
Comparing a query against every stored vector is O(N), fine at thousands, a wall at millions. So real systems use an approximate nearest-neighbor (ANN) index that gives up a sliver of accuracy for an enormous speed-up: it visits a clever fraction of the vectors instead of all of them. The dominant index is HNSW, a layered proximity graph you hop through greedily; IVF, which buckets vectors into clusters and only scans a few, is the other. Every knob trades along one surface, recall versus latency versus memory, and the practical work is tuning that trade, compressing vectors to fit in RAM, and filtering by metadata without silently starving your results.
The embeddings page ended on a quiet cliffhanger. Every help-center article for Wrenlet's support bot is now a point in meaning-space; to answer a customer, you embed their question and “find the nearest points.” It even told you how, in code: sort every document by similarity, take the top few. That works beautifully, right up until it doesn't.
At launch, Wrenlet's help center had a few hundred articles. The loop that scored all of them ran in under a millisecond; nobody thought about it. Two years later the index holds every article, every resolved support ticket, and every past chat, millions of chunks, and that same loop now takes the better part of a second on each question. The bot feels sluggish, the bill for the machine doing the scoring keeps climbing, and the fix isn't a faster loop. It's a fundamentally different way to search. That way is a vector index, and this page is how it works.
The honest, exact way, and why it hits a wall
Start with the search that's simply correct. Embed the question into a vector, then compare it against every stored vector one by one, keep a running list of the closest, and return the best k. This is called a flat or brute-force index, “flat” because there's no structure, just the raw vectors in a row. Its great virtue is that it's exact: it looks at everything, so it always returns the true nearest neighbors. Its ground truth is the yardstick every faster method is measured against later.
The problem is the arithmetic. Each comparison is a dot product across every dimension of the vector, a few hundred to a few thousand multiply-adds, and you do it once per stored vector. So the cost is “number of vectors × dimensions,” written O(N·d). Double the corpus and you double the work, with no ceiling. Watch what that does as Wrenlet grows:
The interactive version of this example is available when JavaScript loads.
The bargain: give up “exact,” gain “fast”
Here's the leap. The exact scan is slow because it insists on checking every candidate to be certain it found the single best. But retrieval doesn't need certainty, it needs the right passages in the top-k, and it can tolerate occasionally missing one of them. So we trade: accept a search that's approximate, it finds the true nearest neighbors almost always, not always, in exchange for looking at a tiny fraction of the vectors. This is approximate nearest-neighbor search, ANN, and it's what every vector database actually runs.
How good is “almost always”? You measure it with recall@k: of the true top-k neighbors (the ones a flat scan would return), what fraction did the approximate index actually surface? Recall of 0.95 at k=10 means that, on average, it found nine or ten of the true top ten. Production systems typically tune for somewhere around 0.90 to 0.99 recall, high enough that the missed neighbor rarely matters, fast enough to serve at scale.
How does HNSW work?
The dominant ANN index, the one under pgvector, Weaviate, Qdrant, Redis, Elasticsearch, and most others, is HNSW (Malkov & Yashunin, 2018), short for Hierarchical Navigable Small World. The name is a mouthful; the idea is simple. Instead of storing the vectors as a flat list, you wire each one to its nearest neighbors, forming a graph, a map where every vector knows a handful of the vectors closest to it. To find what's near a query, you don't scan the map; you walk it.
The walk is a game of getting warmer. You start at the graph's entry point, one designated vector on the sparse top layer, almost certainly nowhere near the query. You look at the small handful of vectors it's wired to and ask one question: which of these is closest to what I'm looking for? You jump to that one. Now you're a little nearer. From there you do the exact same thing, look at its neighbors, jump to the closest, then again, and again. Every jump lands you nearer the query, the way “warmer… warmer… hot” walks a child straight to a hidden toy. You stop the instant none of your current neighbors is any closer than where you're already standing: that's the signal you've arrived, right in the query's neighborhood. And you got there having looked at maybe a few dozen vectors along the path, never the millions sitting off in every other direction.
The hierarchical part is the speed trick. The graph is built in layers. The top layer is sparse, a few vectors with long-range links that let you cross the whole space in a couple of hops. Lower layers get denser, with shorter links for fine-grained homing. Search starts at the top for a coarse “which region?” jump, then drops layer by layer, zooming out to zoom in, until it settles on layer 0 where every vector lives. Walk it below, raise the search effort and watch the beam widen: more vectors visited, more of the true neighbors caught, but more hops to pay for.
The interactive version of this example is available when JavaScript loads.
Stepping through it separates the two halves. The descent is the coarse-to-fine part: long hops across a sparse top layer, then shorter ones as each lower layer densifies, so the walk arrives near the query before it has looked at most vectors. The beam is the accuracy part, and it is the one you tune. On this illustrative 26-vector graph a narrow beam settles early and returns a near-miss, leaving a true neighbour tucked in a pocket unvisited, while a wider one reaches it. Both still touch a fraction of the corpus, which is the entire bargain.
What do HNSW’s M, efConstruction and efSearch do?
HNSW's whole recall-vs-latency-vs-memory position is set by three parameters, and the classic mistake is confusing which are set once at build time and which you can turn per query. Two are baked into the graph when you build it; one you can change on every search.
| Knob | When it applies | Turn it up → |
|---|---|---|
| M, links per vector | Build time | Better recall and a sturdier graph, at higher memory (more links stored) and slower builds. The paper puts the useful range at 6 to 48, and pgvector, Qdrant and hnswlib all default to 16. |
| efConstruction, build search width | Build time | A higher-quality graph, so a higher recall ceiling, costs only build time, not query speed or memory. Typical 100 to 400. |
| efSearch, query search width | Query time | Higher recall per query, at higher latency. No memory or rebuild cost, your main live dial. Typical 40 to 200+. |
How does IVF work?
IVF takes a completely different route from HNSW: cluster the vectors into cells up front, then at query time scan only the few cells whose centers sit nearest the question. IVF (inverted file) first runs k-means over your vectors to carve the space into cells, think of it as pre-sorting every vector into one of, say, a few thousand buckets, each with a representative center point. At query time you don't scan all the buckets; you find the handful of cell centers nearest the query and scan only those cells' vectors. If each cell holds a thousandth of the corpus and you probe a few of them, you've skipped 99%+ of the work.
IVF's tuning is two numbers: nlist, how many cells you carve the space into, and nprobe, how many of them you scan per query. Turn nprobe up and you scan more cells, higher recall, more work, until at nprobe = nlist you're back to an exact scan. Its famous weakness is the edge-of-cell miss: a true neighbor that happens to sit just across a cell boundary, in a bucket you didn't probe, is invisible no matter how close it really is. Raising nprobe patches the leak by scanning neighboring cells too, at a latency cost.
HNSW or IVF: which should you use?
| Index | How it searches | Best when |
|---|---|---|
| Flat (brute force) | Scans every vector, exact, 100% recall. | Small corpus (≲ tens of thousands), or as the ground-truth oracle for measuring recall. |
| HNSW (graph) | Walks a layered neighbor graph greedily. | You want the best recall-per-latency and can afford the RAM; the default for most workloads. |
| IVF (clusters) | Scans only the nprobe cells nearest the query. | Huge corpora where memory matters and build speed helps; pairs with compression (below). |
One dial, one curve: recall bought with latency
HNSW's efSearch and IVF's nprobe are the same dial wearing two costumes: both say “look at more candidates.” Turn either up and recall rises while latency rises with it, never one without the other. There is no setting that gives you perfect recall at zero cost; there's only a curve, and your job is to pick the point on it where recall is high enough and latency is still inside budget. Move the dial and feel the curve:
The interactive version of this example is available when JavaScript loads.
How do you fit a billion vectors in memory?
A graph index like HNSW lives in RAM, and the vectors are the bulk of it. A million 768-dimensional vectors at full precision is around 3 GB of floats; a billion is thousands of gigabytes before you count the graph links. At that scale the memory bill, not the CPU, is what breaks you. The graph itself is the smaller half and worth being able to size: roughly d x 4 + M x 2 x 4 bytes a vector, so 10 million 768-dimensional vectors at M=16 is about 32 GB, of which the links are 1.3 GB. The paper puts the index overhead at 60 to 450 bytes an object depending on M. Past that you shrink each vector with quantization: store a lossy, compact version, search on that, and (optionally) re-check the top candidates against the full-precision vectors to recover accuracy.
| Method | What it does | Memory cut · recall |
|---|---|---|
| Scalar quantization | Each dimension from a 4-byte float to a 1-byte int. | ~4× smaller · nearly lossless with a rescore step. |
| Product quantization (PQ) | Split the vector into sub-vectors, replace each with a codebook ID. | ~10 to 200× smaller · a real recall hit alone; recovers with IVF-PQ + rescoring. |
| Binary quantization | Each dimension collapses to a single bit (its sign). | up to ~32× smaller · only for high-dim vectors (≳1024), recovered with oversample + rescore. |
Product quantization (Jégou et al. 2011) is the workhorse for billion-scale corpora, and it pairs naturally with IVF: IVF narrows the search to a few cells, and PQ makes every vector in them tiny to store and cheap to compare. That combination, IVF-PQ, is what makes the heading of this section true. Those three terabytes at 64 bytes a vector are about 64 GB, plus the IVF centroids: one large machine instead of a rack. The catch is recall: aggressive compression alone can gut it, which is why serious setups always rescore, search fast on the compressed vectors to get a shortlist, then re-rank that shortlist against the full-precision copies. Newer systems (Qdrant's binary quantization, for instance) report keeping recall around 0.98 with a few times oversampling plus rescoring, but only on high-dimensional vectors.
The filter that silently starves your results
Real retrieval is rarely “find the nearest chunk”, it's “find the nearest chunk this user is allowed to see,” or “from the current plan,” or “written after last month.” That metadata filter looks trivial and is the single hardest part of production vector search. The naive approach, post-filtering, is a trap: fetch the top-k by similarity first, then drop the ones that fail the filter. Ask for 10, and if 8 of the top 10 belong to a plan the user isn't on, you hand back 2, a half-empty result page and no obvious error. Watch it starve:
The interactive version of this example is available when JavaScript loads.
The other end is pre-filtering, cut the corpus to the allowed set first, then search only that. It guarantees you get up to k valid results, but for a graph index it's costly: removing most of the nodes tears holes in HNSW's carefully wired neighborhoods, so the walk stalls or recall collapses. It's fine when the filtered set is small, painful when it's most of the corpus.
Which vector database should you use?
You almost never write an ANN index by hand, you pick a system that ships one. The split that matters is a library you embed in your own service versus a database that runs the index for you versus your existing SQL database with a vector extension. A representative cut, with the index each leans on:
| System | Kind | Index & why you |
|---|---|---|
| pgvector | Postgres extension | HNSW + IVFFlat, inside the SQL DB you already run, so joins and WHERE clauses compose in SQL. They are not free on an approximate index: filtering happens after the scan unless you turn on iterative scans. Great to a few million or tens of millions. |
| FAISS | Library (in-process) | Every index type (Flat, IVF, HNSW, PQ, IVF-PQ). Maximum control; you own persistence and serving. |
| Weaviate / Qdrant / Milvus | Managed / server DBs | HNSW (Milvus offers many), with filter-aware search and quantization built in. You skip running the infra. |
| Pinecone | Managed, serverless | Not HNSW. Pinecone runs its own IVF and product-quantization family over object storage, and says it has never used HNSW, because an HNSW graph has to stay in RAM. You do not pick or tune the index at all. |
| Redis, Elasticsearch / OpenSearch | Existing engines + vectors | HNSW bolted onto a store you may already operate, handy for hybrid keyword + vector in one place. |
Measuring what you can’t see: is recall still good?
Approximate search has a quiet danger: nothing tells you when it's returning worse results. Latency looks fine, the API returns k rows, and yet recall may have drifted down as the corpus grew, as data shifted, or as deletes piled up. The only way to know is to measure recall directly, and the trick is that you don't need exact ground truth over the whole corpus, you need it over a sample.
The recall canary
- Take a sample of real queries, a few hundred is plenty, and for each, run an exact flat scan to get the true top-k. That's your ground truth.
- Run the same queries through your ANN index and compare: what fraction of each true top-k did it return? Average it, that's your live recall@k.
- Run it continuously. Recall silently degrading as the index grows or churns is the classic production failure; a scheduled recall check against a fresh exact sample catches it before users do.
And when you tune, judge the whole budget, not just recall. The canonical picture is the recall-versus-throughput curve (ANN-Benchmarks plots exactly this for every algorithm): as you raise efSearch or nprobe, recall climbs and queries-per-second fall. A configuration is only valid if it clears your recall floor and your p99 latency and fits in memory and builds in acceptable time. Report all four; a recall number with no latency beside it is half an answer.
Vector search in code
Stripped to essentials with pgvector, the whole thing is four moves: build the index, set the live dial, query with a filter, and keep a recall check honest.
The whole flow, step by step
- Build the index once.
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops), notevector_cosine_ops: the index's distance metric must match how the embedding model was trained, or every result is subtly wrong. - Set the query-time dial.
SET hnsw.ef_search = 100;(orSET ivfflat.probes = 10;for IVF), the live recall/latency knob, tuned per your budget, no rebuild. - Query top-k with the filter, and know what Postgres does with it.
SELECT id FROM chunks WHERE plan = $userPlan ORDER BY embedding <=> $queryVec LIMIT 10. The<=>is cosine distance. TheWHERE, though, is applied only after the index scan, which is the post-filter starve from earlier in this page: pgvector's own README warns that a condition matching 10% of rows with the defaulthnsw.ef_searchof 40 returns about 4 rows, not 10. Sethnsw.iterative_scan = strict_order(pgvector 0.8.0 and later) so it keeps scanning until it has enough, or build a partial index per tenant when the predicate is very selective. - Measure recall against exact. Periodically re-run a sample of queries with the index disabled (a flat scan) and compare the top-k, your recall canary, so a drift shows up as a number, not a complaint.
Where does vector search bite?
It bites where the approximation, the tuning, or a filter quietly stops doing what you assumed it was doing, and none of those announce themselves.
The ones that actually bite
- Forgetting it's approximate. ANN can miss a true neighbor and never flags it. If a use case truly needs exactness, you need a flat scan or a rescoring pass, the index alone won't promise it.
- Shipping the defaults. A too-low nprobe or efSearch gives quietly terrible recall; people conclude the whole approach is broken. Sweep the dial on a labeled set before trusting it.
- Post-filtering permissions. Filter after the top-k and a selective filter starves the result; do it as part of the search, and treat access control as a correctness requirement, not a nicety.
- Under-budgeting memory. HNSW is RAM-resident and the graph adds real bytes per vector on top of the raw floats; at high dimension and high N the memory bill dominates. Plan for quantization or a disk-based index.
- Ignoring update cost. Deleting from a graph index is awkward, most engines tombstone and defer, then rebuild when tombstones pile up. A fast-churning corpus fights HNSW; budget for periodic rebuilds.
- Metric mismatch. Indexing with L2 while the model wants cosine (or skipping normalization) silently tanks quality, and it gets blamed on the index, not the metric.
Habits that keep an index fast and honest
What senior teams wire in from the start
- Start simple, scale when forced. Flat until it's slow, then pgvector/HNSW; reach for IVF-PQ or a managed DB only when memory or scale demands it.
- Tune the query-time dial first. Sweep efSearch/nprobe against a labeled set and pick the point where recall clears your floor and p99 latency still fits, before ever rebuilding.
- Match the metric to the model. Set the index's distance function to what the embedding was trained for, and normalize if you're using dot product as cosine.
- Filter inside the search. Use the store's filter-aware ANN, never a naive post-filter; make permission filters mandatory and fail-closed.
- Run a continuous recall canary. Compare a query sample against an exact scan on a schedule, so recall drift surfaces as a metric, not a support ticket.
- Budget all four costs. Recall, latency (p99), memory, and build/update time are one budget, decide against the whole square, not recall alone.
Interview cheat-sheet: intern to principal
- Why not just compare the query against every vector?
- That's an exact flat scan, and it's O(N·d), linear in the number of vectors. It's perfect for small corpora, but at millions of vectors and real query rates it blows the latency budget, because cost grows without bound as the corpus grows. Approximate indexes make search sublinear by looking at a clever fraction of the vectors.
- What does “approximate” cost you, and how do you measure it?
- It can occasionally miss a true nearest neighbor, you trade a little accuracy for a lot of speed. You measure the loss with recall@k: run an exact flat scan on a sample of queries for ground truth, run the same queries through the index, and see what fraction of each true top-k it returned. Production targets are usually around 0.90 to 0.99.
- How does HNSW work, in plain terms?
- It wires each vector to its nearest neighbors as a graph and searches by walking it greedily, hop to whichever neighbor is closest to the query, repeat until none is closer. It's layered: sparse long-range links up top for coarse jumps, dense short links below for fine homing, so you zoom out then in and touch only a few dozen vectors.
- HNSW's efSearch vs efConstruction vs M, which do you change to raise recall live?
- efSearch, it's the query-time search width, so you turn it up per request to raise recall at the cost of latency, with no rebuild or extra memory. M (links per vector) and efConstruction (build search width) are baked in at build time; changing them means rebuilding the graph. So efSearch first, rebuild only if that's not enough.
- HNSW or IVF, how do you choose, and what is IVF’s failure mode?
- HNSW usually gives the best recall-per-latency and is the default when you can afford the RAM. IVF buckets vectors into k-means cells and scans only the nprobe nearest ones, cheaper memory and faster builds, and it pairs with PQ for billion-scale. IVF's weakness is the edge-of-cell miss: a true neighbor just across a cell boundary you didn't probe is invisible, patched by raising nprobe.
- Why is metadata filtering hard, and what breaks if you do it naively?
- Post-filtering, take the top-k, then drop rows failing the filter, can starve: a selective filter leaves you with far fewer than k results and no error. Pre-filtering guarantees k but tears up a graph index's connectivity. The real fix is a filter-aware index that skips non-matching vectors during the search; and permission filters must be treated as correctness, not a post-processing step.
- How do you fit a billion vectors in memory?
- Quantize them: scalar quantization (~4× smaller), or product quantization (PQ) which replaces sub-vectors with codebook IDs for far larger cuts. Pair PQ with IVF, IVF picks which cells to scan, PQ makes each vector tiny, and rescore the shortlist against full-precision vectors to recover the recall that compression costs. Or move to a disk-based index if RAM still won't hold it.
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.