Skip to content

Exact KNN, HNSW and IVF; derive a candidate and storage budget

15 min reading

Compare exact search, HNSW and IVF using a declared candidate budget.

Page details

GenAI · Lesson 13 of 45 · 2 / 2.2

Sources · 15 min reading · 31 min with practice

Published · Last edited:

More
20px

Progress is saved in this browser when storage is available.

View guided paths and progress

Know first: Chunking: semantic, recursive and overlapping windows through one document. Optional help: GenAI foundations.

Optional background references

Hypothetical scenario. Northwind’s chosen chunks make the vector collection larger. Dev proposes approximate search to avoid scoring every vector. Maya wants to know whether a faster lookup still finds the passages her questions require.

Maya: “What would we compare the fast result with?”

Dev: “Exact search can give us reference neighbors for selected queries.”

Priya: “Keep that comparison inside the same permitted collection as the approximate search.”

You will distinguish exact KNN, HNSW graph navigation and IVF list probing, then derive candidate work and storage under stated assumptions. Evaluate candidate recall before asking a later ranker to repair missing evidence.

What does faster candidate search leave out?

An IVF index assigns vectors to coarse partitions and stores their identifiers in inverted lists. A query probes selected lists and compares vectors within them. Probe count trades candidate work against the chance of excluding a relevant vector. In contrast, HNSW navigates a proximity graph. Neither approximation removes the need for exact-search reference cases and permission-aware evaluation. The Faiss IndexIVF reference describes this inverted-list structure.

Hypothetical scenario. Assume 10,000 vectors distributed evenly across 100 lists. Each contains 10,000/100 = 100 vectors. Probing four lists compares approximately 4 × 100 = 400 candidate vectors instead of 10,000. Uneven lists and coarse-assignment work change this estimate. A relevant vector in an unprobed list cannot be recovered by reranking the 400 candidates. Measure recall on declared queries; candidate reduction is not evidence of unchanged answer quality.

Hypothetical scenario. Dev proposes faster search, but Priya needs to know which relevant passages disappear.

In short. Compare approximate results with an exact baseline. Measure recall under the permitted filter.

Speed needs a reference answer

Hypothetical scenario. A library has searchable vectors for its handbook passages. Exhaustive scoring gives useful results, but the team expects more documents and concurrent requests. It replaces the scan with a graph index. Queries become faster in a small trial, while a passage needed for an exception disappears from some results. Was the representation wrong, the graph search incomplete, or the source absent?

A vector index organizes vectors to support a search rule. Some approaches examine every eligible vector; approximate methods aim to avoid some work while accepting that they may miss neighbors that exhaustive scoring would return. To assess that trade-off, first define the reference result and the workload.

This chapter follows embeddings and chunking. You will derive a vector-payload budget, calculate approximate-neighbor recall, and distinguish an indexing algorithm from the database responsibilities needed to operate it.

Separate approximate search from the exact reference universe

Hypothetical scenario. Define a query and the currently eligible vector set before comparing exact KNN, HNSW and IVF. The exact result over that set is a reference for neighbor recall; it is not itself a relevance label.

Separate approximate search from the exact reference universe
ArtifactConcrete evidenceDecision boundary
Search universeACL/source versions, vector spaceEligible comparison set
Exact referencequery, metric, top candidatesNeighbor-recall baseline
ANN configgraph/list policy, search allowanceWork / coverage choice
Same query and metric: Eligible vector set → Exact reference / ANN.Same query and metric: Eligible vector set → Exact reference / ANN. Eligible vector set to Exact reference / ANN: same query and metric; Exact reference / ANN to Measured candidate coverage: compare before answer scoring.Eligible vector setExact reference /ANNMeasured candidatecoveragesame query and metriccompare before answer scoring
Same query and metric: Eligible vector set → Exact reference / ANN. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

HNSW traverses a graph of candidate relationships; IVF chooses coarse partitions and searches selected lists. Their tuning parameters trade work for candidate coverage under the chosen data and filter behavior. Post-filtering a small approximate set can miss eligible neighbors even when the unfiltered recall looks good. Keep encoder and distance identity fixed in the comparison, measure filtered recall and inspect skew and update behavior. A storage payload calculation excludes graph links, list metadata, replicas and runtime workspace unless separately counted.

An algorithm name does not establish a service limit

“The collection is large” is incomplete. Work depends on vector count, dimension, eligible scope, scoring rule, request rate, hardware, batching, and the target latency distribution. A scan can be a good baseline even if a later design needs acceleration. An approximate index can be a poor choice if its maintenance or memory cost exceeds the value of saved query work.

Nor does an exact nearest neighbor mean the correct answer passage. Exactness refers to the chosen vectors and score. If the representation ranks irrelevant material first, reproducing that ranking perfectly does not solve relevance. Keep approximation error separate from semantic retrieval error.

The HNSW paper describes a graph-based approximate nearest-neighbor method. Evaluate recall against the exact reference under the same corpus and score function; a faster candidate search does not establish that it always returns the exact highest-scoring set.

Declare the search universe and then choose a route

An exact top-k reference needs a fixed corpus revision, the same eligible documents, a scoring rule, a value of k, and a tie policy. Here, “eligible” includes the request's access and scope restrictions. A comparison against unrestricted global neighbors is not a valid reference for a restricted request.

Compare approximation with a shared exact reference The same query, eligible corpus revision, score, and tie rule feed two paths. An exhaustive path produces reference neighbors; an approximate path produces candidate neighbors. Compare their overlap separately from relevance and service latency. Same query + scopecorpus + scorek + tie policyExhaustive scoringreference top-kApproximate searchcandidate top-kCompareoverlap

A flat scan scores all eligible vectors and selects the best results. Approximate designs organize a route through the collection: a partitioning method can examine selected regions, while a graph method follows connections between vectors. Quantization can reduce representation size or scoring work while introducing another approximation. These techniques can be combined, but their effects should be evaluated separately where possible.

Malkov and Yashunin's HNSW paper describes a hierarchy of proximity graphs. Upper levels contain subsets of elements; a search navigates through that hierarchy before a broader search near the bottom. It is not an ordinary sorted index with a guarantee of exact nearest neighbors.

Graph connectivity and construction effort affect the built structure; query-time search effort affects how extensively it is explored. Implementations commonly expose controls such as M, efConstruction, and efSearch, but their supported ranges and exact behavior belong to the chosen implementation. More exploration can improve measured neighbor recovery at extra work; it does not establish a universal latency or recall guarantee.

Budget payload and neighbor recovery separately

Hypothetical scenario. Store N = 100,000 vectors, each with d = 128 coordinates, using four bytes per coordinate. The raw vector payload is N × d × 4 = 100,000 × 128 × 4 = 51,200,000 bytes. That is 51.2 decimal MB, or 51,200,000/1,048,576 = 48.828125 MiB.

This excludes identifiers, source text, access metadata, graph links, allocator overhead, and query buffers. Holding old and new vector payloads together during a representation migration requires 2 × 51.2 = 102.4 MB before those other items. The calculation is a floor for those two payloads, not a complete RAM or deployment recommendation.

For an exhaustive dot-product scan over all these vectors, each query uses N × d = 12,800,000 coordinate multiplications and N × (d − 1) = 12,700,000 additions under a straightforward arithmetic count. At a chosen demand of 20 queries per second, multiplication demand is 20 × 12,800,000 = 256,000,000 per second. This excludes query encoding, selection, filtering, and service overhead. It is not a measured throughput or latency prediction.

Now evaluate an approximate index using two queries, with k = 3 and at least three eligible vectors for each. Assume no score ties at the cutoff. Use the same exact reference and scoring rule for both paths.

QueryExact top 3Approximate top 3Recovered reference neighbors
Q1A, B, CA, B, D2 of 3
Q2E, F, GE, F, G3 of 3

Neighbor recall at 3 is 2/3 for Q1 and 3/3 for Q2. The mean is (2/3 + 1)/2 = 5/6, approximately 83.3%. Because k is equal, pooling the recovered neighbors gives the same 5/6. This is agreement with exact vector neighbors, not 83.3% relevance, answer support, or user satisfaction.

A different candidate that recovers all six reference neighbors would score 100% on these two queries, still without proving performance on unseen requests. Measure recall over representative cases alongside latency distributions, memory, build time, and update behavior. Declare what happens when fewer than k eligible records exist or the search returns fewer results; do not conceal that condition by changing denominators after the comparison.

In the wild: Vector Indexes (HNSW and Friends): Exact vs Approximate Search

Malkov and Yashunin's HNSW paper: HNSW builds a hierarchy of proximity graphs and uses approximate search.

Filters and updates change what a good result means

Filtering after a small global candidate search can leave too few permitted results. Increasing the initial candidate count may help, but does not prove that the best eligible neighbors were considered. Filter-aware search, preselected eligible subsets, or exhaustive scoring within a small allowed scope are different options with different costs.

Authorization must still hold at disclosure. The choice of search strategy cannot turn an unauthorized record into an acceptable candidate for downstream services or logs. A graph may internally need navigation information, but that is distinct from permission to expose source content.

Updates create another boundary: which corpus revision is searchable, when deletions become effective, and what a rebuild or recovery restores. A result from an older snapshot is not evidence that an index meets the current source's deletion or permission requirements. Record and test these semantics rather than inferring them from the algorithm's name.

A graph or vector-search library also does not automatically supply a complete database service. Durability, concurrency, backup, recovery, tenant isolation, monitoring, and access enforcement require explicit design. Choose the needed guarantees and verify the implementation that provides them.

A fast global shortlist can hide the allowed record

Hypothetical scenario. A request searches across a collection but may see only a small project. The service asks for three global neighbors and removes those outside the project. All three are excluded, so the user receives no result even though the project's own nearest passage is relevant.

The immediate diagnosis is not “the embedding failed.” The candidate route never included the eligible passage. Compare against an exact reference restricted to the project. Then evaluate a filter-aware route or an appropriately bounded search over that project's vectors.

A repair that returns something is insufficient. Inspect relevance, access enforcement, and worst-case work for different project sizes. Keep a regression where the global highest-scoring records are all forbidden, and another where the permitted set changes while cached results exist.

Three different meanings of quality

“Exact search is accurate.” It is exact with respect to a score and corpus. Relevance and supported answers need separate judgments.

“High ANN recall proves the retriever is useful.” An approximate index can faithfully recover an exact ranking that is poor for the task. Compare semantic retrieval quality as well.

“A graph guarantees logarithmic service latency.” An algorithmic scaling claim is not a service-level bound. Data distribution, search effort, filters, hardware, and concurrent work affect observed behavior.

“The payload calculation is the memory budget.” Additional index structures and operational overlap can dominate a deployment decision. Account for them with actual measurements or declared assumptions.

Earn approximation with a baseline

Use exhaustive scoring as a reference and consider it as the operating route when the eligible set and demand permit. It is inspectable and separates representation quality from approximation. You can evaluate an index candidate against it before committing to the operational cost of a more complex service.

Approximation is useful when measured resource or latency limits justify a trade-off and the remaining neighbor loss is acceptable for the task. Choose a configuration using representative queries, restricted scopes, update patterns, and recovery cases. Keep the exact reference available for bounded diagnosis even if it cannot serve the full live workload.

Do not select a product from an isolated recall number. Declare the requirements first: evidence quality, access boundaries, allowed staleness, demand, and recovery behavior. The index is one component of that complete system.

Limits of Vector Indexes (HNSW and Friends): Exact vs Approximate Search

Approximate-search recall depends on the corpus, score function and settings being evaluated. A benchmark result is not a complete serving guarantee. Admission, access checks, updates and recovery remain necessary even when a chosen index finds useful candidates quickly.

Test the search universe boundary

Unfiltered ANN recall is high but a tenant gets few results. What should be tested?

Reveal the design reasoning

The tenant-filtered universe and the actual filtering placement. Increase candidate work or choose a compatible filtered-search mechanism only after measuring eligible recall and resource cost.

Decision: Tune against a declared exact universe, then evaluate task relevance separately.

Check yourself: separate index errors from evidence errors

A test uses k = 4. An approximate result recovers three of the exact top four, and all four approximate hits are judged irrelevant. What does the neighbor recall tell you?

Neighbor recall is 3/4 = 75%. It measures recovery of the exact vector ranking. It does not contradict the relevance judgments: the representation's ranking can be poor even when approximation reproduces most of it. Investigate the evidence and representation separately.

What is the raw payload for 50,000 vectors of 256 four-byte coordinates? Is it enough to choose a machine?

50,000 × 256 × 4 = 51,200,000 bytes, or 51.2 MB. It is the same payload as the worked example because half the vectors have twice the dimension. It excludes index structures and operating overhead, so it is insufficient to choose a machine.

An index returns no permitted results after filtering ten global candidates. Can the application conclude that the permitted collection has no answer?

No. It has only shown that those ten candidates supplied no permitted result. Search the eligible scope with a defined reference or a tested filter-aware strategy. Distinguish “no evidence found by this route” from “the collection contains no supporting evidence.”

Northwind decision log

Compare approximate results with an exact baseline.
Measure recall under the permitted filter.
Choose index settings from a latency and recall budget.

Go deeper into search work and indexing

Check the mechanism in this lesson

Can a cross-encoder recover a relevant IVF vector from an unprobed list if it only receives the selected candidates?

Compare the explanation

No. The vector never entered its candidate set. Increase or change candidate generation under measured recall requirements before attributing the failure to reranking.

Carry the decision forward

Approximate search is one reason evidence may be absent. Page 14 compares lexical and dense candidate signals, then follows their deduplicated union through rank fusion and reranking.