<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Vector Search From First Principles - Medium]]></title>
        <description><![CDATA[Search systems explained from first principles — from vectors, similarity, and nearest-neighbor search to ANN algorithms, indexing, quantization, and the papers and engineering decisions behind production search systems. - Medium]]></description>
        <link>https://medium.com/vector-search-from-first-principles?source=rss----c3d8c12616d1---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Vector Search From First Principles - Medium</title>
            <link>https://medium.com/vector-search-from-first-principles?source=rss----c3d8c12616d1---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:13:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/vector-search-from-first-principles" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Deep Dive: Product Quantization — Distance Error, Bias, and Why Better Estimates Can Rank Worse]]></title>
            <link>https://medium.com/vector-search-from-first-principles/deep-dive-product-quantization-distance-error-bias-and-why-better-estimates-can-rank-worse-02fac9464761?source=rss----c3d8c12616d1---4</link>
            <guid isPermaLink="false">https://medium.com/p/02fac9464761</guid>
            <category><![CDATA[vector-search-engine]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[product-quantization]]></category>
            <dc:creator><![CDATA[Pranshu Shukla]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 15:31:02 GMT</pubDate>
            <atom:updated>2026-10-06T15:31:01.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMwjXWIPqxdY0cUH5MCvEg.png" /></figure><h3>Deep Dive: Product Quantization — Distance Error, Bias, and Why Better Estimates Can Rank Worse</h3><p>In our previous articles, we built Product Quantization from first principles and saw how it replaces full-precision vectors with compact centroid IDs, then uses Asymmetric Distance Computation to estimate query-to-vector distances efficiently. That explains how PQ makes large-scale search practical.</p><p>But once the original vector is replaced by its PQ approximation, the distance we compute is no longer exact. The more important question is: how does that error affect the ranking of nearby candidates?</p><p>A quantizer can produce small distance errors and still swap the order of two close neighbors. At the same time, a numerically less accurate estimator can sometimes preserve the ordering that matters for top-<em>k</em> search. This is the deeper issue explored by Jégou, Douze, and Schmid: how quantization error propagates into nearest-neighbor ranking.</p><p>To understand that, we need to separate three related but distinct ideas: distance error, bias, and ranking error.</p><h3>Reconstruction Error Is Not Distance Error</h3><p>What matters for search is not only how far the quantized vector <em>(q(y))</em> moves from the original vector<em> (y)</em>, but how that movement changes its distance from the query <em>(x).</em></p><p>We can first measure this movement using the reconstruction error — the distance between the original vector and its quantized approximation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3PwZPjxzjMhZrEDQFgFIsw.png" /></figure><p>During quantization, the objective is to keep this reconstruction error small on average across all vectors and their quantized approximations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qum3IQXs6RzvQo8p2Ulc9A.png" /></figure><p>But this is not the quantity nearest-neighbor search directly uses. During search, we compare the query<em> (x) </em>with the quantized approximation <em>(q(y)),</em> so we use</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8XakEEE5QKLMiVnCdVO3g.png" /></figure><p>This creates a second kind of error: <strong>how much did quantization change the distance from the query?</strong> To measure this directly, the paper introduces <strong>Mean Squared Distance Error (MSDE)</strong>, which measures the error in the distances used for search rather than the error in reconstructing the original vectors.</p><p>For a single vector <em>(y) </em>and query <em>(x)</em>, we define the distance error as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4swvHANVeKtZfSb1lITPA.png" /></figure><p>Then across (N) query-vector pairs, the Mean<strong> Squared </strong>Distance<strong> </strong>Error (MSDE) is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VwvOFnCrdWutBC03fFFFLg.png" /></figure><p>This measures the squared difference between the true query-to-vector distance and the distance estimated using the quantized vector.</p><p>The useful result from the paper is that these two errors are not independent: the distance-estimation error can be bounded using the reconstruction error.</p><h3>How Much Can Quantization Change a Query Distance?</h3><p>Now we can connect the two errors we just defined.</p><p>Consider three points:</p><ul><li><em>x</em> — the query vector</li><li><em>y</em><strong><em> </em></strong>— the original database vector</li><li><em>q(y) </em>— its quantized approximation</li></ul><p>These three points form a triangle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbmfzwLQi918cXbBnpEeWA.png" /></figure><p>By the reverse triangle inequality, the difference between these two query distances is bounded by how far quantization moved the database vector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GQ6AMFgINM0Zshsolge3Sg.png" /></figure><p>Squaring both sides gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYPxjR0oDb3dIk-tP2RS3Q.png" /></figure><p>This inequality holds for every query–vector pair. So for each i-th pair:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pt-Sw5dUzef8Nut8QBM_hg.png" /></figure><p>Now add this over all <strong>N</strong> pairs and divide by <strong>N</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jDlRsqBMba0FXHZH093grg.png" /></figure><p>The left-hand side is exactly the MSDE we defined earlier, while the right-hand side is the quantizer’s MSE. Therefore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nRFLrx1gWOffbtMmgSrAlg.png" /></figure><p>In other words, the mean squared error of ADC’s distance estimates is upper-bounded by the quantizer’s mean squared reconstruction error. This gives us a useful connection: <strong>if we make the quantized representation more faithful to the original vectors, we also put a tighter bound on the error of our distance estimates.</strong></p><p>But a bounded error does not mean the estimator is perfectly centered around the true distance.</p><h3>Why ADC Makes Vectors Look Closer Than They Really Are</h3><p>Remember that ADC does not compare the query <em>(x)</em> with the original database vector <em>(y)</em>. Product Quantization splits both vectors into <em>(m)</em> subspaces, and each database sub-vector is represented by its selected centroid. ADC therefore computes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qR4cusl7tzy9nlpKuFKhxg.png" /></figure><p>To understand where the bias in this estimate comes from, it is easier to first examine just <strong>one</strong> of those quantization cells.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eS-imErWek8kne4OQxfd-Q.png" /></figure><p>Suppose <em>(Y)</em> represents a database subvector known only to have been assigned to centroid <em>(cᵢ).</em></p><p>Suppose the sub-vector <em>(Y)</em> is assigned to centroid <em>(cᵢ). </em>Everything that follows applies independently to each PQ subspace; we will combine the <em>(m)</em> subspaces again afterward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ww5zDxRqPbsgOCWgw8C0Mg.png" /></figure><p>The first part, <em>(cᵢ)</em>, is the centroid ADC uses. The second part, <em>(Y − cᵢ)</em>, is the information lost during quantization: how far the actual vector lies from its centroid.</p><p>The true squared distance from the query is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*saAUTehVm8O5Jw4dtyzsTA.png" /></figure><p>Substituting the expression above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3GcODE_BXBrPtJWia3Lu1A.png" /></figure><p>Here, <em>(x − cᵢ)</em> represents the direction and distance from the centroid <em>(cᵢ)</em> to the query <em>(x)</em>. In contrast, <em>(cᵢ − Y)</em> represents the direction and distance from the actual database vector <strong>Y</strong> back toward the centroid.</p><p>Expanding it gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9r3zAo-ri_NAVpplHcaWnA.png" /></figure><p>The cross term <em>(2⟨x − cᵢ, cᵢ − Y⟩)</em><strong> </strong>captures how the vector’s offset from its centroid is aligned relative to the query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-J5g-hbdzgEXmN2CYn9Tkg.png" /></figure><p>Its sign would then depend in this fashion:</p><ul><li><strong>Positive</strong> when <em>(x − cᵢ)</em> and <em>(cᵢ − Y)</em> point roughly in the same direction.</li><li><strong>Negative</strong> when they point roughly in opposite directions.</li><li><strong>Zero</strong> when they are perpendicular.</li></ul><p>Now average over all vectors assigned to <em>(cᵢ).</em> Because the centroid <em>(cᵢ) </em>is the mean of the vectors assigned to its cell, the residuals (<em>Y −cᵢ) </em>have zero mean:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z9lldQJDnv0OpZ9j6Kim9A.png" /></figure><p>The cross term therefore disappears when we take the expectation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Z5Xh8OHMlAcXLEEVefecg.png" /></figure><p>What remains is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-2YFhTJt84UaZWBjP15Ag.png" /></figure><p>The first term is exactly what ADC computes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ne_oP1kNLbo-GvGWUDOOQA.png" /></figure><p>The second term is the <strong>average quantization error inside that cell</strong>. The paper denotes it by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2nCwXqAOkLBeHMbFyFkFWw.png" /></figure><p>So:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5INJHFr711i3V1XvxYd8Lw.png" /></figure><p>This exposes exactly what ADC leaves out. In each subspace, ADC keeps only the query-to-centroid distance. The expected true squared distance also contains the average residual energy of vectors represented by that centroid.</p><p>So, on average, ADC’s squared-distance estimate is too small.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bpkNmMOk8eZ-vgvX_0o6Mg.png" /><figcaption>Recreated from Jégou, Douze, and Schmid, <em>Product Quantization for Nearest Neighbor Search</em>. The original experiment compares true and estimated distances for a SIFT query over 1,000 vectors using 64-bit PQ codes, showing systematic distance underestimation for ADC and a stronger bias for SDC.</figcaption></figure><p>The paper shows the same effect empirically, they observe both SDC and ADC tend to underestimate the true distances, although the bias is stronger for SDC.</p><p>This naturally suggests a correction: if we can estimate <strong>ξ(q, cᵢ)</strong> for each centroid, why not simply add it back?</p><h3>Can We Add the Missing Distance Back?</h3><p>Now that we know why ADC tends to make vectors look closer than they really are, the fix is to add back the distance lost during quantization.</p><p>During training, we estimate the average squared reconstruction error associated with every centroid in each sub-quantizer. For sub-quantizer <em>(j)</em>,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5KbYuRom_xGHkAXmXpNSQ.png" /></figure><p>Here, <em>(qⱼ(y⁽ʲ⁾) )</em> is the centroid selected for the j-th subvector, and <em>(ξⱼ(y))</em> is the average squared reconstruction error of vectors that map to that centroid.</p><p>Because this value depends only on the centroid ID, it can be learned during training and stored alongside the sub-codebook in another lookup table.</p><p>Furthermore, the important part is that this average distortion depends only on the database vector’s PQ code. It does not depend on the query (<em>x)</em>, so all of these correction values can be precomputed.</p><p>So it would be reasonable to expect nearest-neighbor search to improve as well. <strong>Surprisingly, it does not.</strong></p><h3>Why a Better Distance Estimator Can Be a Worse Search Function</h3><p>The authors observe that the correction term removes most of ADC’s systematic bias. The average error shifts from about<strong><em> −</em></strong><em>0.044</em> with the original estimator to approximately<em> 0.002</em> after correction, bringing the estimated distances much closer to the true distances on average.</p><p>At the same time, the error distribution becomes slightly wider: the variance increases from <em>0.00146</em> to <em>0.00155</em>. In other words, the corrected estimator is <strong>far less biased, but slightly more variable</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QvhQQh2GnyHHsGtgcDNhMA.png" /></figure><p>That distinction matters because nearest-neighbor search ultimately depends on preserving the correct ordering of candidates, not just on making the average distance estimate numerically closer to the truth.</p><p>A small example makes the distinction clear. Suppose two candidates have true distances:</p><pre>A = 0.80<br>B = 0.82</pre><p>Now imagine a <strong>biased </strong>estimator would give:</p><pre>A = 0.74<br>B = 0.76</pre><p>Both distances are underestimated, but the ordering is still correct. So nearest-neighbor search still chooses the right vector.</p><p>Now imagine a better-calibrated but noisier estimator gives:</p><pre>A = 0.83<br>B = 0.79</pre><p>Across many vectors, its errors might average close to zero. But for this pair it has reversed the ordering and nearest-neighbor search now returns the wrong candidate.</p><p>This is exactly what the authors observe experimentally: although the correction removes most of the bias, it produces worse nearest-neighbor search results on average.</p><p>Based on this result, the authors retain ordinary ADC for nearest-neighbor search and note that the corrected estimator is useful when the distance values themselves matter.</p><h3>What Actually Matters: Preserving the Ranking</h3><p>Product Quantization is often described as a compression technique, but its real challenge is not simply reconstructing vectors accurately. The compressed representation is useful only if the distances computed from it preserve the ordering that nearest-neighbor search depends on.</p><p>The original PQ analysis shows that reconstruction error places a useful bound on ADC distance error, and that the usual ADC estimator is systematically biased toward making vectors appear closer than they really are. Adding the centroid-specific correction term removes most of that bias and makes the distance estimate much better calibrated on average.</p><p>But that improvement comes with a subtle trade-off: the corrected estimator also introduces slightly more variance. That means an estimator can become <strong>numerically more accurate on average without becoming better at ordering nearby candidates</strong>.</p><p>This is the key takeaway:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kLizfQy6tM_ZhLqwYeKoiA.png" /></figure><p>For ANN systems, that distinction is fundamental. The objective is not to reproduce every exact distance; it is to preserve enough of the relative ordering that the true nearest neighbors survive the approximation. Product Quantization therefore leaves us with an important lesson: the best distance estimator is not necessarily the best search function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02fac9464761" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vector-search-from-first-principles/deep-dive-product-quantization-distance-error-bias-and-why-better-estimates-can-rank-worse-02fac9464761">Deep Dive: Product Quantization — Distance Error, Bias, and Why Better Estimates Can Rank Worse</a> was originally published in <a href="https://medium.com/vector-search-from-first-principles">Vector Search From First Principles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector Search From First Principles: Product Quantization — Compressing Vectors Without Losing…]]></title>
            <link>https://medium.com/vector-search-from-first-principles/vector-search-from-first-principles-product-quantization-compressing-vectors-without-losing-bb1a42479712?source=rss----c3d8c12616d1---4</link>
            <guid isPermaLink="false">https://medium.com/p/bb1a42479712</guid>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[product-quantization]]></category>
            <category><![CDATA[hnsw]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[knn]]></category>
            <dc:creator><![CDATA[Pranshu Shukla]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 15:31:01 GMT</pubDate>
            <atom:updated>2026-10-04T15:31:01.638Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sRmmCjpkdluguEmXz9a4pw.png" /></figure><h3>Vector Search From First Principles: Product Quantization — Compressing Vectors Without Losing Searchability</h3><p>So far, we have mostly treated HNSW as if every vector’s original values were readily available whenever a distance needed to be computed. At small scale, that is a reasonable model. At large scale, however, storing and repeatedly reading full-precision vectors becomes expensive.</p><p>Most embeddings are stored as fp32, where each coordinate uses 4 bytes. A 128-dimensional vector therefore requires <strong>512 bytes</strong>. One million vectors need about <strong>512 MB</strong>, while one billion require roughly <strong>512 GB</strong> just for the vector values, before accounting for the HNSW graph, metadata, document identifiers, or other index structures.</p><p>There is also a query-time cost. Every candidate HNSW evaluates requires reading the vector and computing its distance to the query. So search cost depends not only on <strong>how many nodes HNSW visits</strong>, but also on <strong>how much data must be moved and processed for each visit</strong>.</p><p>Until now, the question was: <strong><em>How can we avoid visiting every vector?</em></strong><br>Now we need to ask: <strong><em>Can we make each vector much smaller while preserving enough information to search it effectively?</em></strong></p><p>That is the problem quantization tries to solve.</p><h3>Reducing Vectors using Vector Quantization</h3><p>We have now established two problems with storing full-precision vectors: (1) they consume a large amount of memory, and (2) every distance computation requires reading those floating-point values again.</p><p>A natural way to reduce both costs is to stop storing every vector exactly and instead approximate it using a nearby <strong>centroid</strong>. Rather than keeping the full vector for every database point, we learn a shared set of representative vectors. Each centroid represents a region of the vector space and stands in for the vectors assigned to it.</p><p>If a database vector <em>(y)</em> is represented by centroid <em>(c)</em> , then we hope that, for a query <em>(q)</em>,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVZw5WOj2Lz2iDv6Uerh7Q.png" /></figure><p>n other words, instead of computing the query’s distance to the original vector, we compute its distance to the centroid that represents it.</p><p>We first learn a collection of centroids, called a <strong>codebook</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsQY0jqYA9xD_63eopTaTA.png" /></figure><p>For each database vector <em>(y)</em>, we then choose the nearest centroid:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NjyYJOusv0apoMS-OrbdsA.png" /></figure><p>Hence, if <em>(y) </em>is closest to a centroid <em>(c)</em>, we approximate its value to be equal to <em>(c).</em></p><p>The important part is that the centroid itself does not need to be stored separately for every vector. The codebook is stored once and shared across the entire dataset, while each vector stores only the ID of its assigned centroid. This immediately reduces storage and also allows approximate distance computations to operate on the centroid representation instead of repeatedly reading the original full-precision vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LoBVV_uv4r6P8xdZJKDiPA.png" /></figure><p>The trade-off is <strong>quantization error</strong>: the centroid is only an approximation of the original vector. The usefulness of the representation therefore depends on how closely each centroid matches the vectors assigned to it.</p><p>This is the basic idea behind <strong>vector quantization</strong>.</p><p>It works well when many nearby vectors can share the same representative without introducing too much error. But if we want to preserve increasingly fine differences between vectors, each centroid must represent a smaller region of the space. That requires many more centroids, and in high dimensions the number of centroids needed to obtain a very accurate representation grows extremely quickly.</p><p>That scaling problem is what motivates <strong>Product Quantization</strong>.</p><h3>Why a Single Codebook Stops Scaling</h3><p>The finer we want our approximation to be, the more centroids we need.</p><p>With only a small number of centroids, each centroid has to represent a relatively large region of the vector space. As we add more centroids, those regions become smaller, so each vector can usually be represented by a centroid that lies closer to it.</p><p>The number of bits we need to store the centroid ID depends on the size of the codebook . For example, if our codebook contains <strong>256 (2⁸) centroids</strong>, then we need <strong>8 bits</strong> to identify any one of them. For example to represent 243rd centroid, it will be represented as <strong>11110011.</strong></p><p>That bit pattern simply tells us which centroid in the codebook represents the vector. As we increase the number of centroids, we need more bits to store the centroid ID. So the number of bits required per vector grows with the number of centroids we want to distinguish:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1qmBUDps7M4FC5SomrnT5A.png" /></figure><p>As a thought experiment, suppose we wanted an ordinary vector quantizer to use the full expressive capacity of a 64-bit code. A 64-bit code can distinguish up to 2<strong>⁶⁴ different centroid IDs</strong>, so in an ordinary vector quantizer each vector could, in principle, choose from as many as 2<strong>⁶⁴ centroids</strong>. That is still extremely compact compared with the original representation: our 128-dimensional fp32 vector needs <strong>512 bytes</strong>, while a 64-bit code needs only <strong>8 bytes</strong>.</p><p>However, there are multiple problems with such a representation:</p><ol><li>To learn a k-means quantizer with 2⁶⁴ centroids, we would need an enormous training set. There would be no way to meaningfully learn that many representative regions from any realistic amount of data.</li><li>For 128 dimension data, the codebook with 2⁶⁴ centroids would need to store: 2⁶⁴ × 128 floating-point values. <strong>That is about 9.4 Trillion GB just to store the centroids.</strong></li><li>Assignment would also become infeasible. When a new vector needs to be quantized, we must determine which centroid represents it. With an ordinary flat codebook containing an astronomical number of centroids, even finding the nearest centroid becomes a search problem of its own.</li></ol><p>Hence at that scale, ordinary vector quantization is simply not practical.</p><p>This is the limitation highlighted by Jégou, Douze, and Schmid in <a href="https://ieeexplore.ieee.org/document/5432202"><strong>“Product Quantization for Nearest Neighbor Search” (IEEE TPAMI, 2011)</strong></a>: if we try to make an ordinary vector quantizer expressive enough to use a very large code space, <strong>codebook storage, training, and vector-to-centroid assignment all become impractical</strong>.</p><p>What we really want, then, is the expressive power of a huge codebook without having to explicitly learn, store, or search through that huge set of full-dimensional centroids.</p><p>Product Quantization achieves this by changing how the codebook itself is constructed.</p><h3>Reducing Vectors using Product Quantization</h3><p>The key idea behind Product Quantization is to <strong>stop treating the entire vector as a single object that must map to one full-dimensional centroid</strong>.</p><p>Instead, Product Quantization splits the vector into several smaller <strong>sub-vectors</strong> and represents each part independently. Each subvector is quantized using its own codebook, so the final representation becomes a combination of several smaller centroid choices rather than a single centroid in the full 128-dimensional space.</p><p>The benefit is that this gives us a much more expressive representation for the same storage budget. Rather than needing an enormous full-dimensional codebook to capture many possible vector shapes, Product Quantization can combine centroid choices from multiple smaller codebooks. This lets it represent far more possible approximations while keeping each individual codebook small enough to learn and search efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOdFJ_IPMDV-Ev4c7ZYfyA.png" /></figure><p>Suppose for example, we have a 128 dimension vector to product quantize. The 128-dimensional vector is split into eight sub-vectors of 16 dimensions each:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tfX2c4seDOPzEuaPAenjhg.png" /></figure><p>Each subvector has its own codebook containing 256 centroids.</p><p>So PQ might map them as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L7a5F2ve_mG79zrRS7Ds5Q.png" /></figure><p>The complete vector is therefore represented by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ox295_v0Aabdzd7fyXOP8w.png" /></figure><p>If each sub-codebook contains <strong>256 = 2⁸</strong> centroids, each centroid ID needs 8 bits &amp; with eight sub-vectors only <strong>8 centroid IDs × 8 bits = 64 bits </strong>is required for the representation.</p><p>So we still end up with a 64-bit representation of the original 128-dimensional vector, but those 64 bits are now distributed across eight small quantization problems instead of being used to select one centroid from an impossibly large full-dimensional codebook.</p><p>That decomposition is what makes PQ practical — but it also introduces its main approximation trade-off.</p><p>By splitting the vector, we are assuming that each sub-vector can be quantized independently. PQ introduces two related sources of approximation:</p><p>(1) First, each subvector is replaced by a centroid, introducing ordinary quantization error.</p><p>(2) Second, splitting the dimensions means correlations across different subspaces cannot be modeled by a single centroid.</p><p>That brings us to the main question: <strong>what information do we lose by breaking one high-dimensional vector into independent pieces?</strong></p><h3>What Do We Lose When We Split the Vector?</h3><p>Because PQ splits the original vector into non-overlapping coordinate blocks, the reconstruction error of the full vector can be decomposed into the reconstruction errors of those individual blocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVbRPXHzWqtM4xU6MMNCfw.png" /></figure><p>Here, <strong>MSE (mean squared error)</strong> measures how far the quantized reconstruction is from the original vector: we take the difference between the original and reconstructed coordinates, square those differences, and average them. Since each coordinate belongs to exactly one subvector, the total reconstruction error is simply the sum of the errors introduced by each independently quantized block.</p><p>The paper describes two key parameters. <em>m</em> is the number of sub-vectors, or equivalently the number of subquantizers, while <em>k*</em> is the number of centroids available within each subquantizer.</p><p>For a fixed total code length, increasing <em>(m)</em> leaves fewer bits available to each subquantizer, which means each sub-codebook can contain fewer centroids. Fewer, richer subquantizers can therefore model each block more precisely, although they are more expensive to train and evaluate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3tzCIYeUJe6FmM0Ndeg_Xw.png" /><figcaption>Recreated illustration based on Jégou, Douze, and Schmid, “Product Quantization for Nearest Neighbor Search” (IEEE TPAMI, 2011). For a fixed code length, using fewer subquantizers with larger codebooks generally yields lower reconstruction error, at the cost of more expensive training and evaluation.</figcaption></figure><p>The commonly used configuration in the paper, <em>m = 8, k* = 256</em>, is therefore a practical balance: the vector is split into 8 sub-vectors, each subvector chooses from 256 centroids, and each centroid ID requires 8 bits. The final code therefore uses <em>8 × 8 bits = 64 bits = 8 bytes</em>, while keeping each individual sub-codebook small enough to train, store, and search efficiently.</p><h3>How Should the Dimensions Be Grouped?</h3><p>Once we decide to split a vector into <strong>m</strong> subvectors, another design choice appears: <strong>which dimensions should go together?</strong></p><p>The simplest approach is to preserve the original ordering and divide the vector into contiguous blocks.</p><p>For a 128-dimensional vector with <strong>m = 8</strong>:</p><pre>dimensions   1–16  → subvector 1<br>dimensions  17–32  → subvector 2<br>...<br>dimensions 113–128 → subvector 8</pre><p>This is convenient, but it is not necessarily optimal.</p><p>The reason is that PQ quantizes each subvector independently. If two dimensions are strongly related but end up in different subvectors, that relationship cannot be modeled jointly by the same subquantizer.</p><p>So ideally, dimensions that vary together should remain in the same subspace.</p><p>The paper discusses three approaches:</p><ul><li><strong>Natural</strong> — keep the original coordinate order.</li><li><strong>Random</strong> — randomly reorder dimensions before grouping them.</li><li><strong>Structured</strong> — group dimensions that are known to be related by the construction of the descriptor.</li></ul><p>With <em>k* = 256</em>, the grouping strategy changes ADC recall@100 substantially:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5QoFuoP-3ihlbeD1n6vYQ.png" /><figcaption>Source: Results reported in Jégou, Douze, and Schmid, “Product Quantization for Nearest Neighbor Search,” IEEE TPAMI, 2011. Table recreated for illustration.</figcaption></figure><p>These experiments show that the way dimensions are assigned to subspaces can materially affect PQ quality when the original dimensions contain meaningful structure or correlations. In such cases, keeping related dimensions within the same subspace can preserve information that would otherwise be lost when those dimensions are quantized independently.</p><p>At this point, we have solved the compression problem. The next step is figuring out how to search directly using those compressed codes.</p><h3>Distance Computation</h3><p>Once the database is compressed, there are two possibilities: compress the query too, or leave the query untouched:</p><h4>1. Symmetric Distance Computation (SDC)</h4><p>In Symmetric Distance Computation (SDC), the query vector<em> (x)</em> is quantized as well. The distance between the query and a database vector is then approximated by computing the distance between their quantized representations, rather than between the original query vector and the quantized database vector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n6-bKSkf9wanUB5AKPa03A.png" /></figure><p>Here:</p><p><strong><em>x</em> </strong>= the query vector, <strong><em>y</em></strong> = the database vector<br><strong><em>q(x)</em></strong> = quantized query, <strong><em>q(y)</em></strong> = quantized database vector</p><p>This is called <strong>symmetric</strong> distance computation because the distance is computed between two quantized representations.</p><h4>Asymmetric Distance Computation</h4><p>In <strong>Asymmetric Distance Computation (ADC)</strong>, we keep the query vector <strong>x</strong> in full precision. we compare <em>x</em> with quantized vector <em>q(y) </em>and estimate the distance as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9D5xuIr_mVICePEGIofsg.png" /></figure><p>This is called <strong>asymmetric</strong> distance computation because only the database vector is quantized.</p><p>That small change matters. The query is only one vector, while the database may contain millions or billions of vectors. There is little benefit in compressing the query if doing so introduces another source of approximation error. ADC introduces quantization error on only one side of the comparison, while SDC introduces it on both.</p><p>The paper’s experiments confirm this. ADC consistently gives better search accuracy than SDC at similar computational cost. For that reason, the paper recommends using ADC whenever there is no specific need to store the query itself in compressed form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PUkNtfNyRNaAUMn95TSTGw.png" /><figcaption>Recreated from the trends reported in Jégou, Douze, and Schmid, “Product Quantization for Nearest Neighbor Search” (IEEE TPAMI, 2011). ADC achieves higher recall than SDC at comparable code lengths because the query remains unquantized, avoiding an additional source of approximation error.</figcaption></figure><h3>Searching Without Reconstructing the Vector</h3><p>After Product Quantization, each database vector is no longer stored as its original coordinates. Instead, it is represented by a short list of centroid IDs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Ko3rhaT78etarjq-hBr7A.png" /></figure><p>Each ID tells us which centroid was selected for that particular sub-vector.</p><p>One way to search would be to reverse the compression process every time we compare a database vector with a query:</p><ol><li>Read the <em>m</em> centroid IDs.</li><li>Fetch the corresponding centroid from each sub-codebook.</li><li>Concatenate those centroids to reconstruct the approximate vector <strong>q(y)</strong>.</li><li>Compute the usual Euclidean distance between the query <strong>x</strong> and <strong>q(y)</strong>.</li></ol><p>That would work, but reconstructing an approximate D-dimensional vector for every candidate would give back much of the computation we were trying to remove.</p><p>PQ avoids reconstruction entirely.</p><p>Recall that with Product Quantization, each database vector is split into <em>(m)</em><strong> </strong>sub-vectors, and each subvector is represented by the ID of its nearest centroid in the corresponding sub-codebook.</p><p>A few encoded database vectors might therefore look like:</p><pre>[23, 34, 55, ...]<br>[23, 67, 52, ...]<br>[81, 34, 19, ...]</pre><p>These numbers are no longer vector coordinates; each one is a <strong>centroid ID</strong>.</p><p>Because every sub-codebook contains only a limited set of centroids, many database vectors will reuse the same centroid in a given subspace. In the example above, the first two vectors both use <em>centroid 23</em> for their first subvector.</p><p>Now consider ADC. To score the first vector, we need the distance between the first query subvector x⁽¹⁾ and centroid c₂₃:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tXtEBgdekI1geZBq5wQ4ag.png" /></figure><p>When we move to the second database vector, we need exactly the same quantity again because its first subvector is also represented by the same c₂₃</p><p>Repeating this calculation for every database vector would create a large amount of redundant work. Across millions or billions of vectors, the same query-subvector-to-centroid distances would be recomputed again and again.</p><p>ADC avoids this by computing every possible query-subvector-to-centroid distance once, when the query arrives, and reusing those values while scoring all database vectors.</p><h4>Step 1: Split the query</h4><p>The query is divided into the same <strong>m</strong> subvectors used by PQ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cakhoy-OhycPzS1i0WgJHg.png" /></figure><h4>Step 2: Compare each query subvector with every centroid in its sub-codebook</h4><p>For each subspace<em> j, </em>we calculate the squared distance from the query subvector <em>x⁽ʲ⁾</em> to every centroid in that sub-codebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axJyDzyi6vlRsztXTfQx9A.png" /></figure><p>This gives us one lookup table for each subspace.</p><h4>Step 3: Score database vectors using only lookups</h4><p>Now suppose a database vector has the PQ code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uzl2T2gAitOWOtbR4hm_Sg.png" /></figure><p>Instead of performing Euclidean-distance calculations against the centroids, we simply retrieve the distances that were already computed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5wXY9N3Bvn4eW0D8gEpCg.png" /></figure><p>That is the key optimization — Each individual lookup is constant-time, so scoring a PQ code requires <em>(O(m))</em> work: <em>(m)</em> table lookups and <em>(m-1) </em>additions, rather than a D-dimensional floating-point distance computation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RW0vC06TmGdO_4HmQOT3yQ.png" /></figure><p>The more database vectors reuse the same sub-centroids, the more valuable this becomes: the expensive query-to-centroid distances are calculated once, then reused across the entire search.</p><p>At this point, we have made the compressed representation both <strong>small</strong> and <strong>cheap to search</strong>.</p><h3>Where Product Quantization Leaves Us</h3><p>We started with a simple problem: full-precision vectors are expensive to store, and repeatedly loading hundreds of floating-point coordinates for every distance computation makes large-scale search expensive as well. Product Quantization changes that representation. Instead of storing the original vector, it stores a short sequence of centroid IDs learned across smaller subspaces.</p><p>At query time, the query itself can remain in full precision. With Asymmetric Distance Computation, we compute its distance to every centroid in each sub-codebook once, build a set of lookup tables, and then score each compressed database vector using only table lookups and additions. A distance computation that originally required loading and comparing an entire (D)-dimensional vector can therefore operate directly on a compact PQ code.</p><p>In a PQ-based search system, the resulting pipeline is straightforward: store compact PQ codes for the database, keep the query in full precision, build query-specific lookup tables, and use those tables to cheaply score compressed vectors. If greater final accuracy is needed, the strongest approximate candidates can then be reranked using higher-precision representations.</p><p>Product Quantization therefore gives us something more useful than compression alone: <strong>a representation designed to remain searchable even after the original vectors have been compressed.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb1a42479712" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vector-search-from-first-principles/vector-search-from-first-principles-product-quantization-compressing-vectors-without-losing-bb1a42479712">Vector Search From First Principles: Product Quantization — Compressing Vectors Without Losing…</a> was originally published in <a href="https://medium.com/vector-search-from-first-principles">Vector Search From First Principles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive: DiskANN — Taking Graph-Based ANN Beyond Memory]]></title>
            <link>https://medium.com/vector-search-from-first-principles/deep-dive-diskann-taking-graph-based-ann-beyond-memory-2f0b641255b2?source=rss----c3d8c12616d1---4</link>
            <guid isPermaLink="false">https://medium.com/p/2f0b641255b2</guid>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[diskann]]></category>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[hnsw]]></category>
            <dc:creator><![CDATA[Pranshu Shukla]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 15:31:02 GMT</pubDate>
            <atom:updated>2026-10-02T15:31:01.874Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPdz6bS8x-oIYiATEP0e8Q.png" /></figure><h3>Deep Dive: DiskANN — Taking Graph-Based ANN Beyond Memory</h3><p>In the previous articles, we saw why graph-based ANN works so well: methods such as NSW and HNSW turn nearest-neighbor search into a navigation problem rather than an exhaustive scan.</p><p>But that efficiency comes with an important systems assumption: <strong>the graph and the vectors are available in memory.</strong></p><p>At millions of vectors, that may be manageable. At hundreds of millions or billions, it becomes much harder. The graph itself consumes substantial memory, the vectors consume even more, and keeping the entire search structure resident in RAM quickly becomes one of the dominant costs of the system.</p><p>One option is to distribute the graph across many machines, but that has its own challenges around infrastructure cost, query fan-out, result aggregation, and operational complexity as the dataset grows.</p><p>DiskANN asks a different question: <strong><em>Can we move the graph out of main memory, store it on disk, and still keep ANN search fast?</em></strong></p><p>For this to work, the storage medium matters. Traditional hard drives are poorly suited to graph traversal because random reads are expensive, whereas SSDs offer much lower random-access latency and can sustain many small reads. This makes it practical for DiskANN to keep the graph on <strong>SSD rather than in RAM</strong>. But that also changes what makes a good ANN graph: once traversal depends on storage access, every unnecessary hop can become another random I/O and directly add to query latency.</p><p>This is the problem explored in the 2019 NeurIPS paper <a href="https://dl.acm.org/doi/abs/10.5555/3454287.3455520"><strong>“DiskANN: Fast Accurate Billion-point Nearest Neighbor Search on a Single Node”</strong></a> by Subramanya et al.</p><p>Their solution is not simply to move an existing graph index onto SSD, but to redesign the system around storage constraints — building a graph that converges in fewer hops, keeping compact vector representations in memory, issuing disk reads in parallel, caching frequently visited nodes, and recovering full-precision accuracy without paying for a separate round of disk reads</p><h3>HNSW’s Memory Bottleneck</h3><p>The difficulty appears as the index grows. HNSW is designed around fast access to both the graph structure and the vectors used to score nodes during traversal. When these structures remain in RAM, visiting another node is relatively cheap, so the search can afford to explore a reasonably large candidate set.</p><p>Modern embedding models also make this memory pressure much more significant. BGE-large-en-v1.5 uses 1024 dimensions, Amazon Titan Text Embeddings V2 uses 1024 by default, Cohere Embed v4.0 defaults to 1536, and OpenAI’s text-embedding-3-large uses 3072 dimensions by default. These are representative of the high-dimensional embeddings now common in production RAG, semantic search, and recommendation systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-PKEVSxTN6c6FdFjoy7QwQ.png" /><figcaption><strong>Figure: </strong>Representative embedding dimensions across widely used production models. Modern embedding systems commonly operate at 768–3072 dimensions, making vector storage and in-memory ANN indexes increasingly expensive at large scale.</figcaption></figure><p>So even the paper’s example of one billion 128-dimensional vectors is relatively modest compared with many embeddings used today. At float32, those billion 128-dimensional vectors alone require roughly ≈ 512 GB (And that is before storing a single graph edge!)</p><p>To address this, there are two common approaches —</p><ol><li>The first is aggressive compression — Systems such as FAISS use structures like inverted indices together with techniques such as Product Quantization to reduce the memory footprint.</li><li>The second is sharding — Split the dataset across multiple machines, keep an in-memory graph on each machine, search every shard, and combine the results.</li></ol><p>Both approaches work, but each introduces a trade-off. If compressed vectors are also used for the final ranking, quantization error can reduce recall; sharding, meanwhile, increases the number of machines required as the dataset grows.</p><p>DiskANN explores another direction: <em>Keep the high-quality graph-based search, but move the large graph and vectors onto SSD.</em></p><p>That immediately raises a simpler question: if SSDs provide much more capacity at a lower cost, <strong>why not just take the graph we already have, store it on SSD, and search it exactly the same way?</strong></p><h3>Why Not Just Put the Graph on an SSD?</h3><p>At first, the obvious solution seems simple: <strong>put the graph and vectors on SSD and run the same graph traversal we previously ran in memory.</strong></p><p>The problem is that a graph designed for RAM does not automatically become an efficient graph for SSD.</p><p>Suppose the search begins at an entry point. We read that node from disk and obtain its neighbors. To decide which neighbor is most promising, however, we also need to score those candidates against the query.</p><p>But their vectors live on disk too.</p><p>This means graph traversal can quickly turn into a sequence of random I/O operations: read a node, inspect its neighbors, fetch candidate vectors, score them, choose which candidates to explore next, and repeat.</p><p>That is where the naive design breaks down.</p><p>The DiskANN paper notes that simply moving an in-memory ANN index onto SSD can require <strong>hundreds of disk reads for a single query</strong>. Even if a commodity SSD can sustain roughly <strong>300,000 random reads per second</strong>, an individual random read still costs hundreds of microseconds. A long chain of dependent reads therefore makes it difficult to keep nearest-neighbor search within a few milliseconds.</p><p>There are really <strong>two kinds of information</strong> the search needs during this process:</p><ol><li>The <strong>graph neighborhood</strong> of an expanded node, which tells us where the search can move next.</li><li>The <strong>vector representation</strong> of a candidate, which lets us estimate how promising that candidate is.</li></ol><p>DiskANN therefore needs a way to keep enough information in memory to make search decisions, while leaving the much larger graph and full-precision vectors on SSD.</p><p>But even after reducing how often candidate vectors must be fetched, another problem remains: <strong>every additional graph hop can still require another SSD access.</strong></p><p>This gives DiskANN two separate problems to solve:</p><ol><li><strong>How can we score candidates without reading every full-precision vector from SSD?</strong></li><li><strong>How can we construct the graph so that reaching the nearest neighbors requires fewer SSD accesses?</strong></li></ol><p>The first leads to keeping compressed vector representations in memory. The second leads to <strong>Vamana</strong>.</p><p>To understand why Vamana helps, we first need to look at the graph property it is trying to improve.</p><h3>From Neighborhood Graphs to Vamana</h3><p>As we saw earlier, HNSW and NSG use neighbor-selection heuristics with an idea closely related to the Sparse Neighborhood Graph (SNG) property: candidates are examined from closest to farthest, and a candidate is kept only if the neighbors already selected do not provide an equally good or better route toward it.</p><p>But DiskANN points out an important limitation: <strong>being navigable does not mean being fast to navigate.</strong></p><p>An SNG guarantees that there is always a neighbor that moves us closer to the destination, but it places no strong bound on how many such moves may be required. For example, points arranged along a line can form a valid SNG by connecting primarily to their immediate neighbors. Search will eventually reach the target, but moving across the dataset may require a long sequence of hops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2L5K-hoyZGh4BSe1V9iWg.png" /><figcaption><strong>Figure:</strong> A sparse neighborhood graph can remain navigable while still requiring many small steps. In a line-like arrangement, search keeps moving closer to the target, but may need a long sequence of hops to get there.</figcaption></figure><p>For an in-memory graph, those extra hops cost CPU and distance computations. For an SSD-resident graph, they can translate directly into additional storage accesses.</p><p><strong>Vamana therefore asks for something stronger than navigability: can we construct the graph so that each useful step makes substantially more progress toward the target?</strong></p><p>That is what leads to its <strong>RobustPrune</strong> heuristic.</p><h3>RobustPrune: What If Every Hop Made More Progress?</h3><p>The problem with the SNG was that it only asked for <strong>some progress</strong> toward the target. Vamana strengthens this idea through a pruning procedure called <strong>RobustPrune</strong>.</p><blockquote>An edge is pruned when an already-selected neighbor provides a sufficiently good indirect route to the same candidate.</blockquote><p>RobustPrune introduces a parameter α ≥ 1 that determines how much better that indirect route must be before the direct edge is removed. As α increases, this condition becomes harder to satisfy, so more useful long-range edges remain in the graph.</p><p>If α = 1, RobustPrune behaves like the SNG rule: as soon as an already-selected neighbor provides a better route to a candidate, Vamana removes the direct edge from the current node to that candidate.</p><p>As α increases, Vamana becomes more conservative about pruning. An already-selected neighbor must now provide a <strong>substantially better route</strong> to a candidate before the direct edge is removed.</p><p>Suppose a candidate p&#39; is 10 units away from p.</p><ul><li>With α = 1, an already-selected neighbor p* only needs to be closer than 10 units to p&#39; for the direct edge to be pruned.</li><li>With α = 2, p* must be within 5 units of p&#39; before that pruning condition is satisfied.</li></ul><p>Increasing α therefore raises the bar for pruning. More direct edges survive, including useful longer-range connections that can help the search make larger jumps through the graph.</p><p>Formally, p&#39; is removed only when:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6msit8CVoELnwfaBIpB3tQ.png" /></figure><p>So a larger α allows more edges to survive pruning, including longer-range connections that can let search skip several intermediate nodes.</p><p>That is precisely the trade-off Vamana wants for SSD search: <strong>spend a little more on graph connectivity to save expensive graph hops later.</strong></p><h3>How Vamana Builds the Graph</h3><p>Vamana does not know the right long-range connections upfront. It begins with a <strong>random graph</strong>, where each point is connected to a small number of other random points, and then repeatedly improves those connections based on what greedy search discovers while traversing the graph.</p><h4>Phase 1: Start with a Random Graph</h4><p>Vamana begins with a <strong>directed graph</strong>, giving every point <em>(R)</em> randomly chosen outgoing neighbors — nodes that the search can move to directly from that point.</p><p>This is different from HNSW, which starts with no graph and builds its structure incrementally as points are inserted.</p><p>The purpose of this phase is simply to give the algorithm a connected structure to improve. Vamana starts with a complete set of vertices already present and then progressively rewires that graph into a useful ANN structure.</p><p>Vamana also chooses the medoid of the dataset — the data point whose aggregate distance to the other points is smallest — and uses it as the fixed starting point for graph search.</p><h4>Phase 2: Search for Each Point Using the Current Graph</h4><p>Vamana then processes the dataset in a <strong>random order</strong>, taking one point p at a time.</p><p>For each p, it runs <em>GreedySearch</em> from the dataset medoid s, using p itself as the target. This shows which parts of the current graph are actually useful for reaching p.</p><p>Vamana records the nodes visited along the way. These visited nodes form a natural candidate set for p&#39;s outgoing edges: they are the points the current graph already considered relevant while trying to navigate toward p.</p><p>Vamana then applies <em>RobustPrune</em> to this candidate set to decide which of those connections should actually be kept.</p><h4>Phase 3: Replace p&#39;s Random Neighbors Using RobustPrune</h4><p>Vamana now applies <strong><em>RobustPrune</em></strong> to p. Its candidate pool contains the nodes visited during the search <strong>together with </strong><strong>p’s existing outgoing neighbors</strong>.</p><p><strong><em>RobustPrune</em></strong> then selects at most R outgoing edges from this combined pool, removing connections that are redundant through another selected neighbor. The initial random edges are therefore not blindly discarded: they compete with the newly discovered candidates, and only the useful connections survive.</p><p>This is the self-improving part of Vamana: the current graph is used to discover p, and the nodes encountered during that search are then used to improve p&#39;s own connections.</p><p>At this point, however, the update is still <strong>one-way</strong>. If p now points to x, there is no guarantee that x points back to p. Vamana handles that in the next phase by adding <strong>backward edges</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xO_Ty76hB0-Iny0GaFCfpA.png" /><figcaption><strong>Figure:</strong> Vamana builds its graph by starting from random directed connections, using greedy search to discover useful candidate neighbors, pruning them with RobustPrune, adding reverse edges, and repeating this process across all points. A second pass with (<em>alpha &gt; 1)</em> preserves more useful long-range edges, helping reduce the number of hops needed during search.</figcaption></figure><h4>Phase 4: Add Backward Edges</h4><p>Once p has chosen its outgoing neighbors, Vamana adds a <strong>backward edge</strong> from each selected neighbor back to p. So if p points to x, Vamana also tries to add the reverse connection x → p.</p><p>This matters because Vamana’s graph is directed: p → x does not automatically imply x → p. Adding the reverse edge improves connectivity around p and makes it easier for future searches to reach it from nearby parts of the graph.</p><p>There is one complication. Adding x → p may push x beyond the maximum out-degree R. When that happens, Vamana runs <strong>RobustPrune</strong> on x again, trimming its outgoing neighbors back to at most R.</p><h4>Phase 5: Repeat for Every Point</h4><p>Vamana processes the dataset in a random order and repeats the same cycle:</p><p><strong>search for the point → collect visited nodes → prune its neighbors → add backward edges → repair degree violations.</strong></p><p>With each iteration, the graph becomes better suited for the same <em>GreedySearch</em> procedure that will eventually be used at query time.</p><h4>Phase 6: Run a Second Pass with α &gt; 1</h4><p>Vamana runs this graph-refinement process <strong>twice</strong>.</p><p>The first pass uses α = 1. This aggressively removes redundant edges and produces a sparse, navigable graph.</p><p>The second pass repeats the same process using the configured α &gt; 1. Because RobustPrune now requires a much better indirect route before removing an edge, more useful long-range connections are retained.</p><p>These longer-range edges give the search opportunities to make larger jumps through the graph, reducing the number of hops required to reach the target region — and, once the graph is stored on SSD, reducing the number of storage accesses required during search.</p><h3>But How Do You Build Vamana for a Billion Points?</h3><p>During construction, Vamana repeatedly searches through the current graph, evaluates candidate neighbors, and rewires edges. At billion-point scale, keeping the entire dataset in memory while doing this is no longer practical.</p><p>DiskANN therefore builds the graph in smaller pieces.</p><h4>Divide and Conquer: Partitioning the Dataset</h4><p>DiskANN partitions the dataset using <strong>k-means clustering</strong>. K-means identifies k representative points, called <strong>centroids</strong>, and groups vectors around the centroids they are closest to.</p><p>Building each partition independently introduces a problem: two nearby vectors may fall on opposite sides of a cluster boundary, causing an important connection between them to be missed.</p><p>To avoid this, DiskANN makes the partitions <strong>overlap</strong>. Instead of assigning each vector only to its nearest centroid, it assigns the vector to its ℓ nearest centroids—typically ℓ = 2.</p><p>Vectors near a boundary can therefore appear in multiple partitions, allowing useful connections across neighboring regions to be discovered during construction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ByRYZGerK9qXAD5OcJ9gA.png" /><figcaption><strong>Figure:</strong> DiskANN makes billion-scale graph construction feasible by first partitioning the dataset into overlapping regions, building a Vamana graph within each partition, and then merging the discovered edges into a single global graph.</figcaption></figure><h4>Stitching the Graph Back Together</h4><p>DiskANN builds a Vamana graph independently for each partition and then combines the results by taking the <strong>union of their edges</strong>.</p><p>If a point appears in multiple partitions, it may acquire different outgoing edges in each one. All of those discovered connections are brought together in the merged graph.</p><p>The partitioning is therefore only a <strong>construction strategy</strong>. After the partial graphs are merged, DiskANN produces a <strong>single global Vamana graph</strong>, rather than a collection of separate indices that must be searched independently.</p><h3>What Lives in RAM and What Lives on SSD?</h3><p>We have now solved the problem of <strong>building</strong> the graph without fitting the entire dataset in memory.</p><p>But search creates a different problem: once a graph expansion reveals many new candidate nodes, how do we decide which of them are worth exploring without reading every full-precision vector from SSD?</p><h4>PQ in RAM: Decide Which Candidates Are Worth Exploring</h4><p>When DiskANN expands a node, it may discover dozens of new candidate neighbors. To decide which of those candidates are closest to the query, the search needs some representation of their vectors.</p><p>Fetching every candidate’s full-precision vector from SSD would defeat the purpose of moving the index out of memory: a single graph expansion could trigger many additional random reads.</p><p>DiskANN avoids this by keeping a <strong>Product Quantization (PQ)</strong> representation of every vector in RAM.</p><p>These PQ codes are much smaller than the original vectors, but still allow DiskANN to estimate each candidate’s distance to the query. Newly discovered candidates can therefore be scored and ranked entirely in memory.</p><p>This means DiskANN can discover many candidates, evaluate all of them using PQ, and spend SSD reads only on the small number that look promising enough to explore further.</p><h4>SSD: Expand Only the Promising Nodes</h4><p>Once DiskANN decides that a candidate is worth exploring, it must <strong>expand</strong> that node to discover its outgoing neighbors.</p><p>Those graph neighborhoods live on SSD, so expansion still requires a disk read. DiskANN stores the graph together with the original full-precision vectors, while the PQ representations used for candidate scoring remain in RAM.</p><p>The division of responsibility is therefore:</p><ul><li><strong>RAM </strong>→ score many candidates cheaply using PQ</li><li><strong>SSD </strong>→ fetch graph neighborhoods only for candidates selected for expansion</li></ul><p>This prevents DiskANN from spending an SSD read on every candidate merely to decide where to search next.</p><p>The full-precision vector stored beside each neighborhood will become important later, when we look at how DiskANN recovers the accuracy lost through PQ.</p><h3>Beam Search: Reduce Sequential SSD Round Trips</h3><p>With candidate distances available in memory, DiskANN knows which graph nodes look promising.</p><p>The remaining problem is actually fetching their neighborhoods.</p><p>With ordinary greedy search, we might choose the single best candidate, fetch its neighborhood from SSD, inspect what we discovered, choose the next candidate, and then issue another read.</p><p>That creates exactly the dependency chain we were trying to avoid:</p><p><strong>read → wait → decide → read → wait → decide</strong></p><p>DiskANN replaces this with a small <strong>beam</strong>. Instead of expanding only the single closest unvisited candidate, it takes the W most promising candidates and requests their neighborhoods together.</p><p>This matches the way SSDs are designed to work. Unlike a single dependent chain of reads, several independent random reads can be issued at the same time and serviced concurrently. DiskANN therefore uses the beam width W to turn graph expansion from a mostly sequential process into a small batch of parallel SSD requests.</p><p>The important point is that these parallel reads are not free. DiskANN may actually perform more I/O than a strictly sequential search, because some of those four neighborhoods may turn out not to have been necessary. But the reads overlap in time, so the query spends less time waiting for one read to finish before it can issue the next.</p><p>There is therefore a trade-off in choosing W.</p><ul><li>If W is too small, DiskANN leaves too much I/O sequential.</li><li>If W is too large, it may fetch many neighborhoods that were never needed, wasting bandwidth and increasing pressure on the SSD.</li></ul><p>The paper explores relatively small beam widths such as W = 2, 4, 8 to balance these effects.</p><p>So the two ideas work together:</p><p><strong>Vamana reduces how many hops the search needs. Beam Search gets more graph expansion out of each round of SSD waiting.</strong></p><h3>Caching the Beginning of the Search</h3><p>There is one more obvious source of repeated I/O.</p><p>Vamana searches begin from the same starting point, and many queries therefore traverse some of the same vertices near the beginning of the graph.</p><p>DiskANN can simply keep those frequently visited vertices in RAM.</p><p>If the query distribution is known, the system can cache nodes that are commonly accessed. But the paper also proposes a simpler strategy: cache all vertices within roughly C = 3–4 graph hops of the starting point.</p><p>That allows the early portion of many searches to happen entirely in memory before the traversal reaches the parts of the graph that need SSD access.</p><p>The cache cannot grow indefinitely — the number of reachable nodes grows quickly with every additional hop — but a small cached region removes some of the most repetitive disk reads.</p><h3>Full-Precision Reranking Without Another I/O Phase</h3><p>Earlier, we saw that DiskANN uses <strong>PQ in RAM to score the many candidates it discovers</strong>, allowing it to decide which few nodes are promising enough to fetch from SSD.</p><p>But PQ is lossy. Those approximate distances are useful for navigating the graph, but they may not preserve the exact ordering of the nearest neighbors.</p><p>Fortunately, DiskANN already performs an SSD read whenever it chooses to <strong>expand</strong> one of those promising nodes. It takes advantage of that read by storing the node’s <strong>full-precision vector alongside its graph neighborhood</strong> on disk.</p><p>So the two stages are different:</p><ul><li><strong>Candidate discovered →</strong> score it approximately using its PQ code in RAM.</li><li><strong>Candidate selected for expansion →</strong> fetch its neighborhood from SSD, and receive its fp32 vector in the same read.</li></ul><p>The paper points out why this layout is effective. SSD reads occur in aligned blocks, so reading only a small portion of a block is not necessarily cheaper than reading the whole block.</p><p>In the paper’s 128-dimensional setup, the graph neighborhood and full-precision vector fit within the same 4 KB disk sector, so retrieving the exact vector requires no additional disk read. With much larger modern embeddings, the exact physical layout may require more data to be read, but the underlying idea remains the same: co-locate full-precision coordinates with graph data so reranking can reuse I/O already performed during traversal.</p><p>As BeamSearch progresses, DiskANN temporarily keeps the full-precision vectors of the nodes whose neighborhoods it has fetched. By the end of the traversal, it therefore already has exact vectors for the promising portion of the graph it actually explored.</p><p>Those vectors can then be used to <strong>re-rank the final candidates using exact distances</strong>, correcting errors introduced by PQ.</p><p>The important point is that DiskANN does <strong>not</strong> fetch the fp32 vector of every candidate PQ evaluates. It obtains exact vectors only for nodes it was already going to read from SSD for graph expansion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i_meAwqk5wBhrzlGm-3PGg.png" /><figcaption><strong>Figure:</strong> During search, DiskANN first expands the current node to discover many candidate IDs, then uses PQ codes kept in RAM to estimate their distances and choose only a promising subset. Only those selected nodes are fetched from SSD — bringing back both their neighborhoods and full-precision vectors — after which the exact vectors are used to re-rank the final candidates into the top-<em>k</em> results.</figcaption></figure><h3>Did the Design Actually Work?</h3><h4>Did Vamana Reduce the Number of Hops?</h4><p>The reason for introducing Vamana was straightforward: <strong>if graph hops translate into rounds of SSD reads, then reaching the target in fewer hops directly reduces query latency.</strong></p><p>The experiments show that Vamana does exactly that.</p><p><em>At a target </em><strong><em>98% 5-recall@5</em></strong><em>, Vamana requires substantially fewer hops than HNSW and NSG at higher graph degrees. More importantly, increasing the maximum number of neighbors each node can keep continues to reduce Vamana’s hop count, while HNSW and NSG largely plateau. The extra degree only helps if those additional edges create useful shortcuts; with </em><em>α &gt; 1, Vamana is better able to use that additional capacity to preserve long-range connections.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPmxxHXNaWAp82jHdZoD6A.png" /><figcaption><strong>Figure:</strong> Average graph hops required to achieve 98% 5-recall@5 on SIFT1M as the maximum number of neighbors per node increases. HNSW and NSG largely plateau, while Vamana continues to reduce the number of hops by making better use of the additional graph degree. Values are approximately digitized and redrawn from Figure 2(c) of the DiskANN paper.</figcaption></figure><p>This is the behavior α &gt; 1 was designed to enable. By retaining useful long-range edges, Vamana can make larger jumps through the graph and make better use of the additional degree available to each node.</p><h4>Does Partitioned Construction Hurt the Graph?</h4><p>DiskANN also needs to show that building Vamana in overlapping pieces does not destroy those properties.</p><p>On SIFT1B, the paper compares two billion-point indices:</p><ul><li>a <strong>one-shot Vamana graph</strong> built over the entire dataset, and</li><li>a <strong>merged graph</strong> built from 40 overlapping k-means partitions, with every point assigned to its 2 closest partitions.</li></ul><p>The merged graph does require more traversal than the one-shot graph, but the cost is relatively small: at a fixed recall, the paper reports no more than about 20% additional latency. In return, the billion-point index could be constructed while keeping memory usage below 64 GB, compared with roughly 1.1 TB peak memory for the one-shot build.</p><p>That is the important trade-off: a modest loss in search efficiency makes billion-point graph construction practical on a much smaller machine.</p><h4>Putting the Whole System Together</h4><p>Finally, the paper evaluates the complete SSD-based DiskANN system.</p><p>On SIFT1B, DiskANN achieves <strong>more than 95% 1-recall@1 in under 3.5 ms</strong> while using the same memory footprint as the 32-byte compressed baseline.</p><p>The headline result in the paper’s abstract is even broader: on its 16-core, 64 GB workstation, DiskANN serves <strong>more than 5,000 queries per second with under 3 ms mean latency at 95%+ 1-recall@1</strong>.</p><p>Those numbers are not the result of Vamana alone. They come from the pieces working together.</p><h3><em>What DiskANN Changed</em></h3><p>DiskANN’s main contribution is not simply moving a graph onto SSD. It recognizes that once the index leaves RAM, the optimization target itself changes. Distance computations still matter, but now random I/O, sequential round trips, and physical data layout become part of the search algorithm.</p><p>Vamana reduces the number of hops. PQ lets the search evaluate many candidates without reading them from disk. BeamSearch overlaps the SSD accesses that remain. Caching removes repeated reads near the entry point, while full-precision vectors recovered during traversal repair the ranking error introduced by PQ.</p><p>The result is an important shift in how we think about graph-based ANN: the best graph is not determined only by geometry. It also depends on the memory hierarchy on which that graph will be searched.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f0b641255b2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vector-search-from-first-principles/deep-dive-diskann-taking-graph-based-ann-beyond-memory-2f0b641255b2">Deep Dive: DiskANN — Taking Graph-Based ANN Beyond Memory</a> was originally published in <a href="https://medium.com/vector-search-from-first-principles">Vector Search From First Principles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive: Does HNSW Really Need the Hierarchy?]]></title>
            <link>https://medium.com/vector-search-from-first-principles/deep-dive-does-hnsw-really-need-the-hierarchy-b7f374ffd90b?source=rss----c3d8c12616d1---4</link>
            <guid isPermaLink="false">https://medium.com/p/b7f374ffd90b</guid>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[knn-algorithm]]></category>
            <category><![CDATA[hnsw]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[knn]]></category>
            <dc:creator><![CDATA[Pranshu Shukla]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 15:31:02 GMT</pubDate>
            <atom:updated>2026-09-30T15:31:02.016Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cQTOfbp7-4zzMIRBpC1Uw.png" /></figure><p>In the previous articles, we saw how HNSW uses sparse upper layers to reach a promising region before searching the full graph at Layer 0. The hierarchy seems central to its design. But how much does it actually help when searching high-dimensional embeddings?</p><p>Several studies have tested that question. <a href="https://arxiv.org/abs/1904.02077">Lin and Zhao (2019)</a> found that the hierarchy’s speedup was most apparent on low-dimensional synthetic data and largely disappeared at higher dimensions.<a href="https://doi.org/10.52202/068431-2789"> Coleman et al. (2022)</a> observed that searching HNSW’s base graph alone could perform comparably to searching the full hierarchy. At billion-vector scale, <a href="https://arxiv.org/abs/2305.04359">Dobson et al. (2023)</a> found that shallower or flat graph indexes could also be competitive, though those comparisons involve other differences between the indexes.</p><p>These results motivate <a href="https://doi.org/10.1007/978-3-032-21324-2_3">Munyampirwa et al.’s <em>Down with the Hierarchy: The “H” in HNSW Stands for “Hubs”</em></a>. The paper goes beyond asking whether the upper layers help. It asks <strong>what makes the base graph navigable enough to search without them</strong>.</p><h3>What Changes in High Dimensions?</h3><p>In the earlier articles, we treated HNSW’s upper layers as an explicit routing system: they move the search quickly across the graph, while Layer 0 handles local exploration. The question here is whether high-dimensional data can create an alternative routing system inside Layer 0 itself.</p><p>In some high-dimensional spaces, the nearest-neighbor structure becomes highly uneven. A small number of vectors appear in the nearest-neighbor lists of disproportionately many others — a phenomenon known as <strong>hubness</strong>.</p><p>The paper’s proposal is that these hubs may be more than popular neighbors. If they are also well connected and frequently visited during search, Layer 0 could be developing its own routing structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6S6U70dqUJwA6qZ0LyY9Cg.png" /><figcaption><em>The Hub Highway Hypothesis: highly connected hubs (orange) form routes through the base graph, potentially reducing the need for HNSW’s upper layers. Conceptual illustration.</em></figcaption></figure><p>A query could reach one of these highly connected hubs, travel through a network of other hubs, and leave that network only after reaching the region that requires deeper local exploration.</p><p>This is exactly what puts the hierarchy into question.<strong> </strong>The upper layers come with additional links and memory overhead, and the original HNSW work also noted that hierarchical search can reduce throughput in distributed settings compared with a flat NSW graph. If the base graph develops an efficient hub-based routing structure — as it does on several of the high-dimensional datasets studied in the paper — then the upper layers may be duplicating work that Layer 0 is already doing.</p><p>This is the idea Munyampirwa et al. eventually formalize as the <strong>Hub Highway Hypothesis</strong>.</p><h3>Testing Whether the Hierarchy Still Matters</h3><p>Before explaining <em>why</em> the hierarchy may be unnecessary, the authors first establish that removing it does not meaningfully hurt search performance.</p><h4>How the Authors Isolate the Hierarchy</h4><p>They use <a href="https://github.com/nmslib/hnswlib">hnswlib</a> as the baseline HNSW implementation. Rather than building two completely different graph indexes and comparing them, they first construct a normal hierarchical HNSW index with the library and<strong> then extract only the bottom layer and search that flat graph </strong>using their own library, <a href="https://github.com/BlaiseMuhirwa/flatnav">FlatNav</a>, which reimplements HNSW’s greedy search over a flat NSW graph.</p><p>This setup removes graph construction as a major confounding factor: both searches operate over the same Layer-0 graph. It does not eliminate every implementation difference, because HNSW and FlatNav use different search code, but it isolates the presence or absence of the upper layers far better than comparing unrelated graph indexes.</p><p>They compare the two systems across the standard ANN Benchmarks and the larger BigANN Benchmarks, including four datasets containing 100 million vectors. Performance is evaluated using recall against both p50 latency, representing the median query, and p99 latency, representing tail performance.</p><p>One possible concern remains: even if the upper layers are unnecessary during search, perhaps they still help construct a better Layer-0 graph.</p><p>The authors test this separately in the appendix. They build FlatNav graphs from scratch, without constructing a hierarchy, and obtain essentially the same search results.</p><h4>What Happens When the Hierarchy Is Removed</h4><p>On the four <strong>100-million-vector BigANN datasets</strong>, the recall-latency curves for HNSW and FlatNav were nearly on top of each other at both <strong>p50 and p99 latency</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a2NBlB8Ckbtikvqs.png" /><figcaption><em>Median query latency versus recall across four 100-million-vector datasets. HNSW and FlatNav show nearly overlapping curves, with no consistent advantage from the hierarchy. </em>Reproduced from Munyampirwa, Lakshman, and Coleman, <a href="https://arxiv.org/abs/2412.01940v3"><em>Down with the Hierarchy: The “H” in HNSW Stands for “Hubs”</em></a>, Figure 2, under <a href="https://creativecommons.org/licenses/by/4.0/?utm_source=chatgpt.com">CC BY 4.0</a>.</figcaption></figure><p>The same pattern appears on the smaller ANN Benchmark datasets. In other words, removing all of HNSW’s upper layers does not produce a consistent search-performance penalty — even at 100 million vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H1e8UbutOLYE4A-w.png" /><figcaption><em>Tail query latency versus recall on the same datasets. Removing the upper layers produces no consistent latency penalty in these experiments. </em>Reproduced from Munyampirwa, Lakshman, and Coleman, <a href="https://arxiv.org/abs/2412.01940v3"><em>Down with the Hierarchy: The “H” in HNSW Stands for “Hubs”</em></a>, Figure 3, under <a href="https://creativecommons.org/licenses/by/4.0/?utm_source=chatgpt.com">CC BY 4.0</a>.</figcaption></figure><p>The memory numbers move in the opposite direction. During index construction, the paper reports:</p><ul><li><strong>BigANN:</strong> 183 GB → 113 GB, about <strong>38% lower peak memory</strong></li><li><strong>Yandex DEEP:</strong> 100 GB → 60.7 GB, about <strong>39% lower</strong></li><li><strong>Microsoft SpaceV:</strong> 104 GB → 85.5 GB, about <strong>18% lower</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yzJcWtQqXiutiXaVvhhjdA.png" /><figcaption>Peak memory during index construction across three 100-million-vector datasets. FlatNav used approximately 18–39% less memory than hnswlib; implementation differences also contribute to these savings. Recreated from Table 6 of <a href="https://arxiv.org/abs/2412.01940v3">Munyampirwa et al.</a>, <a href="https://creativecommons.org/licenses/by/4.0/?utm_source=chatgpt.com">CC BY 4.0</a></figcaption></figure><p>Even at 100 million vectors, increasing the collection size does not restore a consistent search advantage for the hierarchy. The experiments instead point towards the geometry of the data — particularly dimensionality and distance measure — as the more important factor</p><p>.The authors reproduce earlier low-dimensional experiments and find that the hierarchy does help when dimensionality is small, particularly below roughly 32 dimensions. But on the higher-dimensional datasets representative of modern vector search, that advantage largely disappears.</p><p>The memory comparison comes with an important caveat: hnswlib and FlatNav are different implementations, so the reported savings cannot be attributed entirely to removing the hierarchy. These numbers should therefore be read as an implementation-level comparison rather than a precise measurement of the hierarchy’s memory cost.</p><p>That leads to the more interesting half of the paper. If the upper layers are no longer doing the routing, what is?</p><h3>Hubness: When Some Vectors Become Everyone’s Neighbor</h3><p>To understand what might take over the routing role, we need to examine how often each vector appears as someone else’s neighbor.</p><p>Choose a value <em>(k)</em>, representing the number of nearest neighbors assigned to every vector. If <em>(k=10)</em>, each vector contributes a list containing its ten closest neighbors. We can then reverse the question: <strong>how many of those lists contain a particular vector <em>(x)</em>?</strong></p><p>The paper denotes this count by <em>(N(x))</em>, known as the vector’s <strong><em>k-</em>occurrence</strong>. Although every vector selects exactly ten neighbors, a particular vector may itself be selected by far more — or far fewer — than ten others.</p><p>Across the dataset, these counts form the <strong>k-occurrence distribution</strong>. When that distribution develops a long right tail, a small number of vectors appear in far more neighbor lists than the rest. These unusually frequent neighbors are called <strong>hubs</strong>, and the tendency for them to emerge is called <strong>hubness</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NRedeIv2ZWTcPIPLa9EEjA.png" /><figcaption><em>Neighbor occurrences for 5,000 Gaussian vectors with k = 10. Counts cluster around ten in 3 dimensions, while a long tail emerges in 100 dimensions. Horizontal axis ranges differ; vertical axes are logarithmic. Inspired by </em><a href="https://www.jmlr.org/papers/v11/radovanovic10a.html"><em>Radovanović, Nanopoulos, and Ivanović’s Hubs in Space (2010)</em></a><em>; not reproduced from the paper’s data.</em></figcaption></figure><h3>Why Does High Dimensionality Produce Hubs?</h3><p>One part of the explanation is <strong>distance concentration</strong>: as dimensionality increases, many points can end up at similar distances from a query.</p><p>A constructed example makes this easier to see. Suppose the query is <strong><em>x(0,0)</em></strong>, and the two candidate vectors are <strong><em>a(1,0)</em></strong> and<strong> <em>b(8,6)</em></strong>. Their Euclidean distances from the query are <strong>(1)</strong> and <strong>(10)</strong>, respectively. The distinction is clear: <strong><em>(b)</em></strong> is ten times farther from the query than <strong><em>(a).</em></strong></p><p>Now append <strong>100</strong> additional coordinates to every vector. Set each new coordinate to <strong><em>(0)</em></strong> for the query and to <strong><em>(3)</em></strong> for both candidates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TSFSMlegGBODAMbaBPRqBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GP5m8SPeB9lstK0_0HZtYA.png" /></figure><p>Every added coordinate contributes <strong>((3–0)² = 9) </strong>to each squared distance, so the 100 coordinates add up to (900).</p><p>The new distances become:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZlzMxCCCV1NRWXlOVnHTDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SQ88-G1CC2KZQMEnGdg1FA.png" /></figure><p>Candidate <strong><em>(a)</em></strong> remains closer, so the ordering has not changed. The contrast, however, has collapsed. In two dimensions, <strong><em>(b)</em></strong> was ten times farther and the distance gap was <strong><em>(9)</em></strong>. After adding the extra coordinates, <strong><em>(b) </em></strong>is only about <strong>5.3% farther</strong>, and the gap has fallen to approximately <strong>1.61</strong>.</p><p>The repeated coordinates in this example are deliberately constructed to make that loss of contrast easy to see. Real datasets do not have this exact structure. However, a related effect occurs in many high-dimensional distributions: typical distances grow as more dimensions contribute, while the variation among those distances grows more slowly. Consequently, distances become increasingly similar relative to their overall magnitude.</p><p>Distance concentration narrows the differences among candidates, while the structure of the data determines which vectors repeatedly emerge as neighbors and become hubs.</p><p>The existence of hubs alone, however, does not explain why HNSW’s hierarchy becomes unnecessary. For that, the hubs must also be connected in a way that helps search move through the graph — and they must actually be used for that purpose.</p><h3>From Hubs to a Highway</h3><p>Hubness gives the paper a candidate set of routing nodes, but frequent occurrence alone is not enough. For these nodes to replace HNSW’s hierarchy, two additional properties must hold: the hubs must connect to one another, and queries must actually use that connected structure during search.</p><p>This leads to the paper’s <strong>Hub Highway Hypothesis</strong>:</p><blockquote>In high-dimensional metric spaces, k-NN proximity graphs can form a highway-like routing structure in which a small subset of nodes is highly connected and heavily traversed, especially during the early stages of search.</blockquote><p>Most nodes belong primarily to local neighborhoods but some nodes connect unusually well across the graph.</p><p>A query enters the graph, reaches these highly connected nodes, travels through them to the appropriate region, and then leaves the highway to perform more detailed local exploration.</p><p>That is strikingly similar to the job performed by HNSW’s hierarchy. The rest of the paper therefore tries to establish three things:</p><ol><li>Some graph nodes really are visited far more frequently than others.</li><li>Those frequently visited nodes are connected to one another.</li><li>Queries actually use them early in search before moving into local neighborhoods.</li></ol><p>Together, these three properties would show that the hubs form more than a collection of popular nodes: they function as a routing network inside the base graph. Munyampirwa et al. test each property separately, beginning with the distribution of search traffic.</p><h3>Evidence 1: Search Traffic Is Not Evenly Distributed</h3><p>The first part of the Hub Highway Hypothesis is that <strong>some nodes should be used by search far more often than others</strong>.</p><p>To test this, the authors run a fixed set of queries through the graph and record how many times each node is visited. They call the resulting counts the <strong>node-access distribution</strong>: for every node, it measures how many query traversals pass through it.</p><p>If navigation were distributed relatively evenly, most nodes would receive similar amounts of traffic. A highway would look very different: most nodes would be visited only occasionally, while a small subset would be used repeatedly across many queries.</p><p>That is what the authors observe.</p><p>For datasets using <strong>ℓ2 distance</strong>, the node-access distribution becomes increasingly <strong>right-skewed as dimensionality rises</strong>. Most nodes receive relatively little traffic, while the tail extends towards a small number of nodes with exceptionally high access counts.</p><p>The angular-distance results provide an important contrast. Their distributions change far less as dimensionality increases and do not develop the same pronounced right tail. This suggests that dimensionality alone does not determine how strongly search traffic concentrates; the geometry induced by the distance measure also matters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gfaVUbkdsfYuBKGj3vIrsA.png" /><figcaption><strong>Node-access distributions under angular and Euclidean distance.</strong> For Euclidean (l2) datasets, increasing dimensionality produces a longer right tail: most nodes receive relatively little search traffic, while a small subset is visited disproportionately often. The effect is much less pronounced under angular distance. Reformatted from Figure 7 of Munyampirwa et al., <em>Down with the Hierarchy: The ‘H’ in HNSW Stands for “Hubs”</em>, reproduced under CC BY 4.0.</figcaption></figure><p>The figure therefore supports two related observations: search traffic is concentrated on a subset of Layer-0 nodes, and that concentration strengthens much more sharply with dimensionality under <strong>l2 </strong>distance.</p><p>This supports the first part of the highway hypothesis: some nodes carry a disproportionate amount of search traffic.</p><h3>Evidence 2: Hubs Connect to Other Hubs</h3><p>Frequently visited nodes alone do not make a highway.</p><p>Imagine several busy intersections scattered across a country. Each may handle a great deal of traffic, but unless those intersections are connected to one another, they do not form a transportation backbone.</p><p>The authors therefore ask whether the high-traffic nodes identified in the previous experiment are also <strong>preferentially connected to each other</strong>.</p><p>They first label nodes as hubs using the node-access distribution. Under one definition, hubs are the <strong>top 5% most frequently visited nodes</strong>; under a stricter definition, they are the <strong>top 1%</strong>. For each hub, the authors inspect its one-hop outgoing neighbors and count how many are also hubs. They then repeat the measurement for a randomly selected group of non-hub nodes.</p><p>To quantify the difference, the authors report Cohen’s <strong><em>d</em></strong>. It measures the difference between the average number of hub neighbors for hubs and non-hubs, expressed relative to the variation within those two groups. A value near zero indicates little separation; a larger positive value means that hubs have substantially more hub neighbors than ordinary nodes do. Because the value is measured in standard-deviation units, <strong><em>d=0.8</em></strong> does <strong>not</strong> mean that hubs are 80% more connected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fj_Dj02xZ_C7WxdmDvXA4A.png" /><figcaption><strong><em>Connectivity among high-traffic nodes.</em></strong><em> The chart shows the reported effect size for the difference between hubs and non-hubs in the number of adjacent hub nodes. Across the five real benchmark datasets, the effect becomes stronger when the hub definition is narrowed from the top 5% of accessed nodes to the top 1%. This indicates that the most frequently visited nodes are especially likely to connect to one another. Adapted from Tables 2 and 3 of Munyampirwa et al., </em>Down with the Hierarchy: The ‘H’ in HNSW Stands for “Hubs”<em>, reproduced under CC BY 4.0.</em></figcaption></figure><p>Using the top-5% definition, hubs generally have more hub neighbors than non-hubs, although the evidence is not equally strong across every dataset. When the definition is narrowed to the top 1%, the pattern becomes much clearer: the authors’ statistical tests find preferential hub-to-hub connectivity in all but one dataset, and the reported effect sizes become substantially larger.</p><p>In other words, the busiest nodes are not scattered independently throughout the graph. <strong>The strongest hubs preferentially connect to other strong hubs.</strong></p><p>Together, these nodes form a disproportionately interconnected subgraph — something much closer to a <strong>highway network</strong> than a collection of isolated popular nodes.</p><h3>Evidence 3: Queries Actually Use the Highway</h3><p>There is still one missing piece.</p><p>We now know that some nodes are visited far more often than others, and that the strongest hubs are unusually well connected to one another. But that does not yet show that search actually <strong>uses this hub network as a routing layer</strong>.</p><p>To test this, the authors record the order in which nodes are visited during <strong>beam search</strong>, the Layer-0 search procedure used by HNSW. Rather than following a single path, beam search keeps a set of promising candidate nodes, repeatedly expands the one closest to the query, and adds better neighbors back into the candidate set. The search continues until no remaining candidate can improve the current results.</p><p>Because different queries require different numbers of search steps, the authors normalize each traversal by its total length. They then divide that normalized sequence into stages and measure the fraction of visited nodes classified as hubs at each stage.</p><p>Across GIST, GloVe, Microsoft SpaceV, and Yandex DEEP, hub utilization is highest near the beginning of the traversal. Queries spend the first portion of the search moving heavily through hub nodes; as they approach the target region, the hub fraction falls and ordinary nodes increasingly dominate the traversal.</p><p>The strength of this pattern also follows the hubness of the dataset. GIST, the highest-dimensional (<strong>l2</strong>) dataset in this experiment, shows especially high highway utilization. GloVe, which uses angular distance and exhibits weaker hubness, spends a smaller fraction of its traversal on hubs.</p><p><strong>Hub utilization over normalized search progress.</strong> Queries visit hubs most heavily during the early stages of search and increasingly move through non-hub nodes as they approach the final neighborhood. Reproduced from Figure 8 of Munyampirwa et al., <em>Down with the Hierarchy: The “H” in HNSW Stands for “Hubs”</em>, under CC BY 4.0.</p><p>The three experiments now fit together. Search traffic is concentrated on a small set of nodes; the strongest of those nodes connect preferentially to one another; and queries use that connected subgraph early, before transitioning into local exploration. Together, those properties make the hub network behave like a routing layer inside Layer 0.</p><h3>So, Does HNSW Really Need the Hierarchy?</h3><p>The paper’s answer is more nuanced than a simple yes or no: <strong>the hierarchy is useful when the base graph lacks an effective routing structure, but it becomes redundant when that structure emerges naturally.</strong></p><p>In the low-dimensional synthetic settings examined by the authors, the (k)-occurrence distribution is relatively uniform. Fewer vectors become nearest neighbors of a disproportionately large number of other vectors, so the base graph develops fewer strong hubs. Without those hubs — and the dense connections among them — Layer 0 does not naturally provide a fast route between distant regions.</p><p>Here, the hierarchy performs a valuable role. Its sparse upper layers provide an explicit routing structure, allowing the search to cross large portions of the graph before descending into Layer 0 for detailed exploration.</p><p>In many of the high-dimensional (l2) datasets studied in the paper, however, the graph begins to construct its own alternative. A small number of nodes receive a disproportionate amount of search traffic, the strongest of those nodes preferentially connect to one another, and queries visit them early before moving into their final local neighborhoods.</p><p>The contrast can therefore be summarized as:</p><ul><li><strong>Weak natural hub structure:</strong> the hierarchy supplies the routing backbone that the base graph lacks.</li><li><strong>Strong natural hub structure:</strong> a hub highway emerges inside Layer 0, reducing the value of the upper layers.</li></ul><p>Dimensionality is an important part of this story, but it is not the only factor. The difference between Euclidean and angular distance shows that the distance measure and data distribution also influence whether strong hubs emerge. The boundary near 32 dimensions should therefore be understood as an observation from particular experiments, not as a universal threshold beyond which hierarchy suddenly becomes unnecessary.</p><p>What Munyampirwa et al. ultimately challenge is not the usefulness of hierarchical routing itself, but the assumption that it must always be built explicitly. On many modern high-dimensional embedding workloads, the base graph appears capable of organizing its own routing network — without the additional links, memory, and traversal required by HNSW’s upper layers.</p><p>When Layer 0 lacks a natural routing backbone, the “H” still needs to stand for Hierarchy. But when the base graph develops a connected network of heavily traversed nodes, the same routing role can be performed by Hubs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7f374ffd90b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vector-search-from-first-principles/deep-dive-does-hnsw-really-need-the-hierarchy-b7f374ffd90b">Deep Dive: Does HNSW Really Need the Hierarchy?</a> was originally published in <a href="https://medium.com/vector-search-from-first-principles">Vector Search From First Principles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector Search From First Principles: What Determines HNSW Recall?]]></title>
            <link>https://medium.com/vector-search-from-first-principles/vector-search-from-first-principles-what-determines-hnsw-recall-dafc71528a49?source=rss----c3d8c12616d1---4</link>
            <guid isPermaLink="false">https://medium.com/p/dafc71528a49</guid>
            <category><![CDATA[knn-algorithm]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[hnsw]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[knn]]></category>
            <dc:creator><![CDATA[Pranshu Shukla]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 15:31:02 GMT</pubDate>
            <atom:updated>2026-09-28T15:31:02.098Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jsgal5aRY5jICxNcjM1InA.png" /></figure><p>In the previous articles, we worked our way from exact nearest-neighbor search to graph-based ANN, first seeing how NSW made greedy search practical and then how HNSW added hierarchy to make that navigation more efficient.</p><p>But understanding how HNSW searches a graph leaves an important question unanswered:</p><p>What determines whether the true nearest neighbors are actually found?</p><p>HNSW recall is shaped long before a query begins searching the graph.</p><p>It depends on three things working together:</p><ul><li><strong>the structure of the data</strong> — how difficult the vector space is to navigate,</li><li><strong>the graph HNSW constructs</strong> — which connections and routes are preserved,</li><li><strong>the search itself</strong> — how much of that graph is explored for a query.</li></ul><p>In this article, we will trace recall through each of these stages and see how efSearch, efConstruction, M, neighbor-selection heuristics, intrinsic dimensionality, Local Intrinsic Dimensionality (LID), and even insertion order influence the final result.</p><p>The goal is not to produce another HNSW parameter-tuning guide.</p><p>It is to understand <strong>where recall is gained or lost inside the algorithm</strong>, and why the same HNSW configuration can behave very differently across datasets.</p><h3>When Does HNSW Get the Answer Wrong?</h3><p>For a query, we need some way to measure how closely HNSW’s approximate results match the true nearest neighbors. This measure is called <strong>recall</strong>.</p><p>You will often see it written as <strong>Recall@k</strong>, where k is the number of nearest neighbors we ask the search to return. <strong>Recall@10</strong>, for example, measures what proportion of the true 10 nearest neighbors appear in the 10 results returned by HNSW.</p><p>More specifically, it is represented as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VV5PVJLFly8DqA3FaDyG6Q.png" /></figure><p>Once the dataset has determined how difficult the problem is, HNSW can lose recall in two operational stages: while building the graph and while searching it.</p><h4>1. The graph has a good route, but search misses it</h4><p>The graph may contain connections that lead toward the true nearest neighbors, but the query does not explore far enough to discover them.</p><p>Searching more aggressively gives HNSW more opportunities to follow those routes. This is primarily where <strong>search-time exploration</strong>, and therefore efSearch, matters.</p><h4>2. The graph itself makes the neighbor difficult to reach</h4><p>The problem can also begin much earlier, during construction.</p><p>Useful connections may never have been created, or they may have been removed during neighbor selection and pruning. The true neighbor can still be part of the graph, but reaching it may now require a much less direct route.</p><p>This is where efConstruction, M, neighbor selection, insertion order, and the structure of the dataset become important.</p><p>We will start at query time with efSearch, then work backward through graph construction and finally to the structure of the dataset itself.</p><h3>The Search Effort (efSearch)</h3><p>During the bottom-layer search, HNSW maintains a set of promising candidates as it explores the graph. efSearch controls how broadly that search is allowed to explore by keeping more promising alternatives under consideration.</p><ul><li>With a small value, HNSW behaves more aggressively: It finds a promising region and concentrates the search there.</li><li>With a larger value, it keeps more alternatives alive.</li></ul><p>A larger efSearch allows the search to explore more possible paths before deciding which candidates to discard. This increases the chance of reaching the true nearest neighbors, so recall generally improves as efSearch increases.</p><p>The trade-off is additional query work: more nodes are explored which means more distances are<strong> </strong>computed and<strong> latency increases.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqba7USRAtvT3Hph6-lbtw.png" /><figcaption><strong>Figure: Recall–latency trade-off as </strong><strong>efSearch increases.</strong> Results from the FAISS HNSW-Flat benchmark on the SIFT1M dataset. Increasing efSearch improves Recall@1 by exploring more of the graph, but also increases query latency; the recall gains gradually diminish as search effort grows. Benchmark results: <a href="https://github.com/facebookresearch/faiss/wiki/Indexing-1M-vectors?utm_source=chatgpt.com">FAISS — Indexing 1M vectors</a>. SIFT1M is a 1-million-vector, 128-dimensional nearest-neighbor benchmark dataset</figcaption></figure><p>The graph makes the trade-off behind efSearch clear. Increasing efSearch gives HNSW more opportunities to recover missed neighbors, so recall improves quickly at first.</p><p>But the gains begin to flatten as recall approaches its ceiling: moving from efSearch = 16 to 64 produces a large improvement, while increasing it further to 128 or 256 yields only small additional gains.</p><h3>The Construction Effort (efConstruction)</h3><p>HNSW itself is built using approximate nearest-neighbor search. When a new vector is inserted, HNSW does not compare that vector with every previously inserted point, instead it searches the graph that already exists. The nodes discovered during that search become candidates for connections to the new vector.</p><p>efConstruction controls how broadly HNSW searches while deciding which existing nodes should become neighbors of the newly inserted point.</p><p>So the trade-off is:</p><ul><li><strong>A higher </strong><strong>efConstruction</strong> keeps more candidates during this construction-time search. This gives HNSW a better chance of discovering good neighbors and generally produces a higher-quality graph, but increases indexing time.</li><li><strong>A lower </strong><strong>efConstruction</strong> searches a smaller set of candidates. Construction becomes faster, but useful neighbors are more likely to be missed. If those connections are never created, the final graph may be harder to navigate and achieve lower recall.</li></ul><p>Unlike efSearch, this cost is paid while the index is being built rather than on every query. But once construction is complete, every query inherits the graph that was created. A better-connected graph can therefore achieve higher recall with the same efSearch, because the search has better routes available without needing to explore more aggressively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nd8MwZivmngRaqKg8sJCsw.png" /><figcaption><strong>Figure: Effect of </strong><strong>efConstruction on HNSW recall at different search budgets.</strong> On the SIFT1M benchmark with M = 32, increasing efConstruction improves Recall@100 across efSearch = 32, 64, and 96. The effect is easiest to see when query-time exploration is limited: at efSearch = 32, recall rises from 0.753 to 0.787 as efConstruction increases from 80 to 160. At higher efSearch, the same graph-quality improvement is still present, but more aggressive search partially compensates for weaker construction. <strong>Source:</strong> Apache Doris HNSW evaluation on SIFT1M — <a href="https://doris.apache.org/docs/4.x/table-design/index/vector-index/hnsw/">HNSW benchmark results</a>.</figcaption></figure><p>The original HNSW paper recommends setting efConstruction high enough that the construction-time approximate nearest-neighbor search achieves recall close to one, noting that approximately 0.95 is sufficient for most use cases.</p><p>But discovering good candidate neighbors is only the first part of graph construction. Even if HNSW finds many good candidates, it cannot keep connections to all of them without making the graph increasingly dense and expensive to search.</p><p>It therefore still has to decide <strong>how many of those connections each node is allowed to keep</strong>.</p><p>That is where M comes in.</p><h3>The Connection Budget (M)</h3><p>Each node has a limited connection budget, controlled primarily by M.</p><p>A higher M allows a node to keep more connections. For example, if a node can keep only four neighbors, it has fewer possible paths available during search than if it can keep sixteen.</p><p>More connections generally improve recall because the graph has more alternative routes. If one path leads the search in the wrong direction, another connection may still lead toward the correct neighborhood.</p><p>The trade-off is that a larger M also means:</p><ul><li>more memory to store the graph,</li><li>more neighbors to inspect when a node is visited,</li><li>and potentially more distance computations during search.</li></ul><p>So increasing M can improve connectivity and recall, but at the cost of memory and query work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owVB6omPu4p_yYcNL3zpJA.png" /><figcaption><strong>Figure: Effect of </strong><strong>M on HNSW recall at different search budgets.</strong> On the SIFT1M benchmark, increasing M (the maximum number of neighbors retained per node) improves Recall@100 across all tested efSearch values. The benefit is strongest when search effort is limited: at efSearch = 32, recall rises from 0.753 to 0.903 as M increases from 32 to 64. At higher efSearch, recall is already stronger, but larger M still improves navigability by preserving more routes through the graph. This illustrates the trade-off behind M: a denser graph generally improves recall, but also requires more memory and can increase query work because more neighbors may need to be inspected during search. <strong>Source:</strong> Apache Doris HNSW evaluation on SIFT1M — <a href="https://doris.apache.org/docs/4.x/table-design/index/vector-index/hnsw/?utm_source=chatgpt.com">HNSW benchmark results</a></figcaption></figure><p>There is one additional detail: M is not necessarily the final maximum degree of every node.</p><p>The original HNSW algorithm uses Mmax for upper layers and a separate Mmax0 for Layer 0. The paper found Layer 0 especially important for high-recall search and observed that setting Mmax0 to roughly 2 × M worked well in its experiments.</p><p>But the number of connections is only one part of graph quality.</p><h3>Not All Connections Are Equally Useful</h3><p>After efConstruction discovers candidate neighbors, HNSW still has to decide <strong>which of them to keep</strong>.</p><p>Simply choosing the M closest candidates can create redundant connections when several of them lie in the same local region. HNSW therefore uses a <strong>neighbor-selection heuristic</strong> that favors more diverse connections. A slightly farther candidate may be retained if it provides access to a different part of the graph, while a closer one may be pruned if another selected neighbor already covers the same region.</p><p>This becomes particularly important for clustered data, where connecting only to nearby points can make movement between clusters difficult.</p><p>The heuristic also provides two additional options:</p><ul><li>extendCandidates expands the candidate pool by considering neighbors of already discovered candidates. The original paper found this particularly useful for highly clustered data.</li><li>keepPrunedConnections can add back some rejected candidates when too few neighbors survive the diversity heuristic.</li></ul><p>So M controls <strong>how many connections can be kept</strong>, while neighbor selection determines <strong>which connections make the graph navigable</strong>.</p><p>And because the usefulness of those connections depends on the geometry of the dataset, the same HNSW parameters can behave very differently across different kinds of data.</p><h3>The Dataset Itself Can Make HNSW Hard</h3><p>So far, we have treated recall as something controlled by the graph and the amount of work HNSW performs. But there is another factor that neither M, efConstruction, nor efSearch directly controls: <strong>the geometry of the dataset itself.</strong></p><blockquote>Some vector spaces are simply easier for HNSW to navigate than others, even when the index uses exactly the same parameters.</blockquote><p>Consider two datasets that both contain 768-dimensional vectors. Their <strong>ambient dimensionality</strong> is identical: every vector is represented using 768 coordinates.</p><p>That does not mean, however, that both datasets are equally complex.</p><p>One dataset might effectively vary along only a few dozen independent directions, while another might make meaningful use of hundreds. This underlying complexity is captured by <strong>intrinsic dimensionality — </strong>roughly, the number of independent directions needed to describe the structure of the data.</p><p>As intrinsic dimensionality increases, nearest-neighbor relationships become harder for a sparse graph like HNSW to represent.</p><p>Imagine first that the data effectively varies in only two or three directions. Nearby points tend to be arranged along those same few directions, so a node needs only a small number of well-chosen connections to provide useful routes through its neighborhood.</p><p>Now suppose the data varies meaningfully along hundreds of independent directions. A node can have relevant nearby points distributed across many more directions in the space. With a fixed connection budget such as M = 16, HNSW can preserve only a small subset of those possible routes.</p><p>This makes the graph more dependent on exactly which edges were selected. If the route needed for a particular query was not preserved, the search may have to take a longer indirect path — or may never reach that neighborhood within its efSearch budget.</p><p>Elliott and Clark explored this directly in <strong>“The Impacts of Data, Ordering, and Intrinsic Dimensionality on Recall in Hierarchical Navigable Small Worlds.”</strong> They generated synthetic datasets using increasing numbers of orthonormal basis vectors, allowing them to gradually increase the intrinsic dimensionality while controlling the rest of the dataset.</p><p>As the number of independent directions increased, recall declined for both HNSWLib and FAISS, with their experiments showing a substantial drop as the synthetic data approached full rank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uepVl2UWaL7THsZkXi0l1Q.png" /><figcaption><strong>Effect of intrinsic dimensionality on HNSW recall.</strong> Elliott and Clark generated 1024-dimensional synthetic vectors using increasing numbers of orthonormal basis vectors. With M = 16, efConstruction = 128, and efSearch = 40 held fixed, Recall@10 decreases for both HNSWLib and FAISS as the number of independent basis directions increases. <strong>Source:</strong> Elliott &amp; Clark, <em>The Impacts of Data, Ordering, and Intrinsic Dimensionality on Recall in Hierarchical Navigable Small Worlds</em>.</figcaption></figure><p>So intrinsic dimensionality helps explain why one dataset can be harder than another. But even within a single dataset, that difficulty does not have to be uniform.</p><h3>Local Intrinsic Dimensionality: Some Queries Are Harder Than Others</h3><p>LID asks how complex the neighborhood around a particular point is. Intuitively, LID roughly measures how quickly the number of nearby points grows as we expand outward from that point. A region behaving like a simple low-dimensional surface has low LID; a region where neighbors spread across many independent directions has higher LID.</p><ul><li><strong>A low-LID region</strong> has a relatively simple local structure. Nearby vectors tend to have more overlap in their neighborhoods, making it easier for HNSW to move toward the correct results.</li><li><strong>A high-LID region </strong>is more complex. There are more possible directions in which nearby vectors can differ, and the overlap between their nearest-neighbor lists can be lower.</li></ul><p>The practical consequence is that <strong>queries against different parts of the same HNSW index can have very different recall</strong>, even when they use exactly the same efSearch.</p><p>This also means that an index can report excellent average recall while hiding a much harder subset of queries. Queries landing in low-LID regions may be recovered easily, while those landing in high-LID regions may require substantially more exploration.</p><p>Elliott and Clark observed this relationship in their analysis of HNSW, noting that higher LID leads to worse recall for the same search parameters, or requires more search work to reach the same recall.</p><p>So recall is not only a property of the index as a whole. It can also depend on <strong>where in the vector space the query lands</strong>.</p><h3>Why the Hierarchy Helps Less as LID Increases</h3><p>This is where HNSW runs into an old enemy of nearest-neighbor search: the <strong>curse of dimensionality</strong>. You can think of LID as a local version of the curse: the entire dataset does not need to be difficult for a particular neighborhood to behave like a high-dimensional space.</p><p>In low-dimensional spaces, “nearby” is usually quite informative. Neighborhoods are compact, nearby points tend to share neighbors, and a few well-chosen edges can guide the search effectively.</p><p>As dimensionality increases, distances can become less discriminative, neighborhoods spread across more meaningful directions, and more points can appear similarly plausible as the next step.</p><p>So the hierarchy is still useful, but it solves a smaller fraction of the overall problem. Prior work by Lin and Zhao, also discussed by Elliott and Clark, found that the hierarchical component provides less benefit as the dimensionality of the data increases, with a diversified flat graph becoming increasingly competitive. arXiv</p><p>In other words, <strong>the hierarchy can get you to the neighborhood, but high LID can still make the neighborhood itself difficult to search.</strong></p><h3>Insertion Order Also Changes Recall</h3><p>HNSW is built incrementally.</p><p>When a vector is inserted, it searches only the graph that exists at that point in time. The neighbors it discovers, and the connections it creates, therefore depend on which vectors were inserted before it.</p><p>This means that inserting the same set of vectors in a different order can produce a different graph.</p><p>Elliott and Clark tested this by sorting vectors according to their Local Intrinsic Dimensionality before insertion.</p><p>They compared graphs built using:</p><ul><li>ascending LID order,</li><li>descending LID order,</li><li>and random insertion order.</li></ul><p>They found that <strong>descending-LID insertion generally produced better recall than ascending-LID insertion</strong>, especially at lower efSearch values. In their reported averages, HNSWLib improved by around 2.6 percentage points and FAISS by around 6.2 percentage points at efSearch = 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zGZTaJ7EHHT5VIQtuZHx_A.png" /></figure><p>Their hypothesis is that inserting high-LID vectors earlier creates a broader initial structure in the graph. Lower-LID vectors, which tend to form tighter and simpler neighborhoods, are then added later around that structure.</p><p>With ascending-LID insertion, tightly connected local regions form early, while the harder high-LID points are added later and have to connect into an already established graph.</p><p>The important takeaway is not that every HNSW index should simply be sorted by LID before construction. It is that HNSW recall can depend on the history of how the graph was built, not only on the final set of vectors and parameter values.</p><h3>Putting the Factors Together</h3><p>We can now think about HNSW recall as the result of <strong>three stages working together</strong>:</p><h4>1. The Data Determines the Difficulty</h4><p>Before HNSW builds anything, the dataset already determines how difficult the nearest-neighbor problem will be.</p><p>Intrinsic dimensionality, Local Intrinsic Dimensionality (LID), clustering, and neighborhood structure all influence how easily nearby vectors can be connected and navigated.</p><p>A simple neighborhood may be represented well with relatively few edges. A complex, high-dimensional neighborhood may require much more from the graph and the search.</p><h4>2. Construction Determines the Graph HNSW Has to Work With</h4><p>HNSW then tries to capture that structure in a sparse graph.</p><p>efConstruction controls how thoroughly it searches for candidate neighbors, M controls how many connections can be retained, the neighbor-selection heuristic determines <strong>which</strong> connections survive, and insertion order influences how the graph develops over time.</p><p>Together, these choices determine how navigable the final graph is.</p><h4>3. efSearch Determines How Thoroughly That Graph Is Explored</h4><p>At query time, efSearch controls how much effort HNSW spends navigating the graph it was given.</p><p>Increasing efSearch can uncover routes that a smaller search would miss, but it cannot improve the graph itself. If construction produced poor or indirect connections, query-time search may need substantially more work to compensate.</p><p><em>These stages can also compensate for one another to a degree. A denser or better-constructed graph may achieve a target recall with less query-time exploration, while a more difficult dataset may require a larger </em><em>M, more construction effort, a higher </em><em>efSearch, or some combination of all three.</em></p><p>This is why there is no universally correct HNSW configuration. efSearch, efConstruction, and M do not determine recall in isolation; they operate on a graph whose quality depends on both how it was constructed and the geometry of the vectors it represents.</p><p>Tuning HNSW is therefore less about finding the “best” value for each parameter and more about deciding how much graph quality, memory, construction work, and query work are needed for the structure of a particular dataset.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dafc71528a49" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vector-search-from-first-principles/vector-search-from-first-principles-what-determines-hnsw-recall-dafc71528a49">Vector Search From First Principles: What Determines HNSW Recall?</a> was originally published in <a href="https://medium.com/vector-search-from-first-principles">Vector Search From First Principles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive: HNSW — Why Adding Hierarchy Changed Graph Search]]></title>
            <link>https://medium.com/vector-search-from-first-principles/deep-dive-hnsw-why-adding-hierarchy-changed-graph-search-50f6dd6de61b?source=rss----c3d8c12616d1---4</link>
            <guid isPermaLink="false">https://medium.com/p/50f6dd6de61b</guid>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[hnsw]]></category>
            <dc:creator><![CDATA[Pranshu Shukla]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 15:31:01 GMT</pubDate>
            <atom:updated>2026-09-26T15:31:01.669Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Ny8E6G-sFhXe4gNeMhZdA.png" /></figure><h3>Deep Dive: HNSW — Why Adding Hierarchy Changed Graph Search</h3><p>In the previous articles in this series, we started from the foundations of vector search: what it means for two vectors to be <em>near</em> each other, why exact nearest-neighbor search becomes increasingly expensive as datasets grow, and how <strong>Navigable Small World (NSW) graphs</strong> turned nearest-neighbor search into a graph-navigation problem.</p><p>NSW gave us an important idea: instead of comparing a query against every vector, build a graph and move through it toward increasingly closer neighbors.</p><p>But NSW still had a problem.</p><p>As the graph grew, search had to navigate a single, increasingly dense network. Finding the right region could require many local hops, and the graph had no explicit structure for making large jumps across the vector space before switching to finer-grained exploration.</p><p>That is the problem HNSW set out to solve.</p><p>This article is a deep dive into <strong>“Efficient and Robust Approximate Nearest Neighbor Search Using Hierarchical Navigable Small World Graphs” by Yu. A. Malkov and D. A. Yashunin</strong> — the paper that introduced <strong>Hierarchical Navigable Small World graphs (HNSW)</strong>.</p><p>Rather than stopping at the familiar description of HNSW as a <em>multi-layer graph</em>, we will work through the reasoning behind its design: why hierarchy was introduced, how it changes navigation compared with NSW, how search and insertion interact, why neighbor selection matters, and how parameters such as M, efConstruction, efSearch, and mL shape the graph that ultimately emerges.</p><p>The goal is to understand HNSW not as a black-box ANN algorithm, but as a carefully engineered evolution of the Navigable Small World graph we built up in the previous article.</p><h3>Recap: What Was Wrong With NSW?</h3><p>Navigable Small World graphs already showed something important: a graph built mostly from local connections can still become efficiently searchable if it contains enough long-range shortcuts.</p><p>But NSW had a structural weakness with scale:</p><p>When a query starts far from its nearest neighbors, <strong>long-range edges</strong> are valuable because they quickly move the search across the graph. Once the search reaches the right region, <strong>short-range edges</strong> become more useful for refining the result.</p><p>The HNSW authors describe this behavior as moving through different distance scales. Conceptually, the search needs two phases:</p><ol><li><strong>Zoom out:</strong> reach nodes whose connections span sufficiently large distances.</li><li><strong>Zoom in:</strong> use progressively shorter connections to approach the query.</li></ol><p>NSW does not explicitly separate these distance scales. Instead, they emerge naturally as the graph grows: older nodes tend to accumulate more connections and become high-degree <strong>hubs</strong>, often containing both long- and short-range edges.</p><p>Starting from such hubs improves navigation because they provide access to multiple regions of the graph. But there is a cost: searching through a hub also means evaluating many of its connections.</p><p>The HNSW paper characterizes NSW search cost roughly as:</p><pre>&quot;number of greedy hops&quot; × &quot;average degree of nodes visited&quot; </pre><p>The number of hops grows approximately logarithmically with graph size, while the degree of important hub nodes can grow as well. The result is a search cost that can become <strong>polylogarithmic rather than cleanly logarithmic.</strong></p><p>So the key question becomes:</p><blockquote><em>Can we preserve NSW’s useful long-range shortcuts without mixing every distance scale inside the same high-degree nodes?</em></blockquote><p>HNSW does exactly that.</p><p>It separates connections of different scales into different layers, turning NSW’s implicit hierarchy into an explicit one.</p><h3>The Core HNSW Idea</h3><p>The central idea behind HNSW is simple: <em>do not mix connections that operate at very different distance scales in the same graph. Separate them into layers.</em></p><p>In NSW, long-range shortcuts, medium-range links, and local connections all coexist in one network. Search has to discover the appropriate scale indirectly by moving through nodes with different degrees. HNSW makes those scales explicit.</p><h4>Separating the graph by distance scale</h4><p>HNSW constructs a hierarchy of proximity graphs — the upper layers contain only a small fraction of the vectors and therefore tend to provide long-range connections across the dataset. As we move downward, progressively more vectors appear and the connections become increasingly local.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rANRxAfQTK2lNg-UZiapFw.png" /><figcaption>Figure: HNSW separates navigation by distance scale. Upper layers contain fewer nodes and longer-range connections for coarse movement across the graph, while lower layers become progressively denser and more local, with Layer 0 providing the finest-grained search.</figcaption></figure><h4>Search becomes an explicit zoom-in process</h4><p>Once the graph is organized into layers, search no longer has to discover the right distance scale implicitly. HNSW can start with the sparse, long-range structure at the top and progressively move into denser, more local neighborhoods as it gets closer to the query.</p><p>Search then proceeds as follows:</p><ol><li>Search begins at the highest layer.</li><li>Because relatively few nodes exist there, its connections tend to span larger distances.</li><li>The algorithm greedily moves toward the query until none of the current node’s neighbors is closer.</li><li>That local minimum becomes the entry point to the next layer.</li><li>The process repeats until Layer 0 is reached.</li></ol><p>This is the explicit zoom-in phase that NSW could only achieve indirectly through hubs.</p><h4>Why should this be cheaper than NSW?</h4><p>Recall the issue with NSW:</p><p>As the network grows, useful hubs can accumulate more and more connections. Although each newly inserted node initially selects only a limited number of neighbors, NSW does not impose a fixed upper bound on the degree of existing nodes. Because connections are bidirectional, older and frequently selected nodes can continue receiving new edges as more vectors are inserted.</p><p>As a result, the degree of important hubs can grow with the size of the graph. A search reaching one of these hubs may therefore have to evaluate an increasing number of edges spanning many different distance scales.</p><p>HNSW instead separates those scales across layers.</p><p>At a particular layer, the search evaluates connections relevant to roughly that scale of navigation. More importantly, HNSW also imposes a fixed maximum number of connections per element within each layer, rather than allowing navigation hubs to accumulate an ever-growing adjacency list.</p><p>Together, bounded degree and explicit scale separation are the basis for the paper’s argument that HNSW can achieve approximately logarithmic search scaling, rather than the polylogarithmic behavior associated with NSW’s growing hubs.</p><p>This immediately raises two questions:</p><ol><li>How does HNSW decide which nodes belong to which layers?</li><li>If connections are bidirectional, how does HNSW keep an older node’s degree bounded when new nodes continue connecting to it?</li></ol><p>The first question explains how the hierarchy is created. The second leads us to HNSW’s neighbor-selection and pruning mechanisms.</p><h3>Setting Up the Hierarchy</h3><p>The hierarchy in HNSW is created probabilistically rather than semantically. A vector is not promoted to an upper layer because it is special, central, or particularly well connected. Instead, every newly inserted vector is randomly assigned a maximum level l.</p><p>If a node receives level l, it appears in every layer from 0 through l. This means that every vector exists in Layer 0, while only a progressively smaller fraction of vectors appear in the layers above it.</p><h4>Higher layers become rarer — and therefore more global</h4><p>The maximum level is sampled from an exponentially decaying distribution, so the probability of a node reaching higher layers decreases exponentially.</p><p>More precisely, HNSW samples the maximum level using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVD_BvAK4h-FMlw_IGxE4A.png" /></figure><p>where U is a random value uniformly sampled between 0 and 1.</p><p>The -ln(U) term produces an exponentially distributed value, while mL controls how quickly the hierarchy becomes sparse. A larger mL allows more nodes to reach higher layers; a smaller mL makes the population fall off more aggressively.</p><p>The paper uses the following value for mL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YuszyQeILkv_fwzd-q2mFA.png" /></figure><p>This links the density of the hierarchy to the graph’s connectivity parameter M. With this choice, the probability that a node reaches at least level l becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63LSrVUM1PLbFgltWKvs5Q.png" /></figure><p>So if M = 16, approximately:</p><pre>Layer 0 → all nodes<br>Layer 1 → 1 / 16<br>Layer 2 → 1 / 256<br>Layer 3 → 1 / 4096</pre><p>For one million vectors, that would mean roughly <strong>62,500 nodes at Layer 1, 3,900 at Layer 2, and only about 244 at Layer 3</strong>.</p><p>This is how random level assignment naturally produces the increasingly sparse hierarchy HNSW needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gu5fWqhi5Ik1q1wWmNjwfQ.png" /><figcaption>Figure: HNSW assigns node levels using an exponentially decaying distribution, so every vector appears in Layer 0, while the probability of reaching progressively higher layers drops rapidly. This naturally creates sparse upper layers for coarse navigation and dense lower layers for local search.</figcaption></figure><p>As a result, each successive layer contains fewer nodes.</p><p>This sparsity is what creates different distance scales. HNSW does not explicitly mark an edge as <em>long-range</em> or <em>short-range</em>. Instead, when fewer nodes are available in an upper layer, the connections between them naturally span larger regions of the vector space. Lower layers contain more nodes, allowing connections to become progressively more local.</p><p>The hierarchy therefore emerges naturally:</p><ul><li><strong>upper layers:</strong> sparse, long-range navigation</li><li><strong>lower layers:</strong> dense, increasingly local navigation</li><li><strong>Layer 0:</strong> all vectors and the finest-grained neighborhood structure</li></ul><h4>Moving randomness from insertion order into the hierarchy</h4><p>This also addresses an important weakness of NSW.</p><p>In NSW, useful long-range connections partly emerged from the <strong>random order in which nodes were inserted</strong>. Earlier nodes had more opportunities to accumulate connections and become hubs, so insertion order could influence the resulting navigation structure.</p><p>HNSW makes this mechanism more explicit. Each new vector independently receives a random level, determining whether it participates in the sparse upper layers.</p><p>The coarse-to-fine structure therefore does not have to emerge indirectly from a favorable insertion order. It is continuously maintained through <strong>random level assignment as the index grows</strong>.</p><h3>How HNSW Builds the Graph</h3><p>Like NSW, HNSW is built incrementally. It is easiest to understand the insertion process in five phases:</p><h4>Phase 1: Navigate down to the level where the new node belongs</h4><p>Suppose the current graph extends up to <strong>Layer 4</strong>, while the new vector q was randomly assigned maximum level <strong>2</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*2DbOHGxgMC-Ll6db_lDAGw.png" /><figcaption><strong>Phase 1 of HNSW insertion:</strong> the new vector X does not create edges immediately. Search first navigates greedily through the existing upper layer and uses the closest node found as the entry point to the highest layer where X will actually be inserted.</figcaption></figure><p>The search starts from the designated entry point at the highest layer. In the layers above q&#39;s assigned maximum level, no connections are created for q; those layers are used only for navigation.</p><p>At each of these layers, HNSW performs a simple greedy search:</p><ol><li>Start from the current entry point.</li><li>Examine all of its neighbors and compute their distances to q.</li><li>Move to the <strong>single closest neighbor,</strong> but only if it is closer to q than the current node.</li><li>Repeat until none of the current node’s neighbors is closer to q.</li></ol><p>So although multiple neighbors are evaluated at each step, the search follows only one best path forward through these upper layers. The goal here is not to discover many neighbors. It is simply to reach the right region of the graph cheaply.</p><h4>Phase 2: Search more broadly and create connections</h4><p>Once the algorithm reaches a layer that q actually belongs to—in our example, Layer 2—the behavior changes. Now HNSW must do more than navigate. It needs to find a set of good candidates that q can potentially connect to in that layer.</p><p>The search therefore stops behaving like a single-path greedy walk and begins keeping multiple promising candidates alive at the same time. This search width is controlled by a parameter called ef.</p><p>You can think of ef as controlling <strong>how broad the search is allowed to become</strong>. More precisely, HNSW maintains a dynamic list of up to ef of the best elements discovered so far; increasing ef allows more competing routes through the graph to remain viable during the search.</p><p>A small ef makes the search narrow and cheap. A larger ef allows the algorithm to explore more alternatives before deciding which nodes are closest to q.</p><p>During graph construction, HNSW uses a specific value for this parameter called efConstruction. A larger efConstruction means HNSW explores more of the existing graph before selecting neighbors for q. This generally gives it a better approximation of q&#39;s true neighborhood, but increases indexing cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*OI3vSf73V0gSpXgWiJG7nA.png" /><figcaption><strong>Phase 2 of HNSW insertion:</strong> once the search reaches the highest layer where X belongs, HNSW performs a broader local search to collect candidate neighbors, with efConstruction controlling how widely that neighborhood is explored.</figcaption></figure><p>The candidates discovered by this broader search are then passed to HNSW’s <strong>neighbor-selection heuristic</strong>, which decides which of them should actually become edges.</p><h4>Phase 3: Choosing which candidates become connections</h4><p>HNSW does not connect q to every candidate it discovers. Instead, M controls how many neighbors the newly inserted node tries to select at each layer.</p><p>This is different from Mmax and Mmax0, which we will encounter shortly: those parameters limit how many connections an existing node is allowed to retain after reciprocal links are added.</p><p>The simplest strategy would therefore be: <strong><em>sort the candidates by distance to </em></strong><strong><em>q, select the closest </em></strong><strong><em>M, and connect them to </em></strong><strong><em>q.</em></strong> But the authors deliberately avoid doing only that.</p><p>Why? Because the nearest candidates may all lie in the same direction or local cluster. Connecting to all of them gives q several very similar routes, while potentially missing a slightly farther candidate that provides access to a different region of the graph.</p><p>Think of q as New York City. If New York could create only a few connections, choosing only the geographically closest places—Newark, Jersey City, Hoboken—would give several routes into almost the same local region. A slightly farther connection to Philadelphia or Boston may be more valuable because it opens a genuinely different direction through the network. HNSW applies the same intuition: it prefers neighbors that are not only close to q, but also diverse enough to provide distinct routes through the graph.</p><blockquote>HNSW uses a <strong>diversity-aware neighbor-selection heuristic</strong>.</blockquote><p>The neighbor-selection process works as follows:</p><ol><li>Candidates are considered from nearest to farthest relative to q.</li><li>A candidate e is selected only if its distance to q is smaller than its distance to every neighbor already selected.</li></ol><p>For example, suppose:</p><pre>d(e, q)  = 4<br>d(e, A)  = 7<br>d(e, B)  = 6</pre><p>Then e is accepted because it is closer to q than to either of the already selected neighbors.</p><p>But if:</p><pre>d(e, q) = 4<br>d(e, A) = 2</pre><p>then e is rejected. Since e lies much closer to A than to q, adding a direct edge from q to e may provide little additional value—the graph can potentially reach that region through A instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XzYe6jvRyPXRmuLVe-Q_Sg.png" /><figcaption>Figure: HNSW’s neighbor-selection heuristic favors directional diversity. Candidate e_reject is discarded because it lies close to an already selected neighbor and adds little new coverage around q, while candidate e_accept is retained because it points in a different region of the space and improves the navigability of the graph.</figcaption></figure><p>In other words, HNSW is not simply choosing the nearest candidates. It is also trying to preserve diverse directions of connectivity, avoiding edges that are likely to be redundant with neighbors already selected.</p><h4>Two additional knobs in the neighbor-selection heuristic</h4><p>The paper adds two optional controls to this process.</p><p>extendCandidates expands the candidate pool before applying the heuristic. Instead of considering only the nodes returned directly by the search, HNSW can also examine the neighbors of those candidates and add previously unseen ones to the pool.</p><p>The paper keeps this disabled by default and notes that it is mainly useful for highly clustered data, where the original search results may not expose enough alternatives across cluster boundaries.</p><p>The second option, keepPrunedConnections, deals with the opposite problem. The diversity rule can sometimes reject so many redundant candidates that fewer than M neighbors are selected. When this option is enabled, HNSW revisits the rejected candidates—starting with the closest—and uses them to fill the remaining connection slots.</p><h4>Phase 4: Adding reciprocal links and pruning the graph</h4><p>Once q has selected its neighbors, HNSW creates the connections bidirectionally.</p><p>This immediately brings back the problem we saw in NSW: <em>what stops an older node from accumulating more and more connections as new vectors keep choosing it?</em></p><p>HNSW handles this explicitly.</p><p>Each upper layer has an explicit maximum degree, referred to in the paper as Mmax. If adding a reciprocal connection causes an existing node to exceed this limit, HNSW takes the node&#39;s enlarged neighborhood, runs the neighbor-selection heuristic again, and prunes the neighborhood back to Mmax.</p><p>Layer 0 follows the same process but uses its own limit, Mmax0.</p><p>Older nodes can therefore continue receiving connections from newly inserted vectors, but their degree cannot grow without bound. And because pruning uses the same diversity-aware heuristic rather than simply retaining the nearest nodes, HNSW tries to preserve connections that are useful for <strong>navigation</strong>, not just those that are geometrically closest.</p><h4>Phase 5: Repeat until Layer 0</h4><p>After q has been connected and any overflowing reciprocal links have been pruned at its highest participating layer, HNSW moves down one level and repeats the same process. This continues layer by layer until Layer 0 is reached.</p><p>There is one subtle difference from the earlier greedy descent. Once the broader efConstruction search has begun, HNSW does not necessarily collapse the search back to a single entry point between layers. The candidate set W found at one layer is passed down as the set of entry points for the next layer.</p><p>Layer 0 is special because every vector in the index exists there. It is therefore the densest graph and captures the finest local structure of the dataset. The upper layers primarily guide HNSW toward a promising region; the final and most detailed neighbor search is then performed at Layer 0.</p><p>Layer 0 has its own degree limit, Mmax0, separate from the Mmax used in the upper layers. This allows HNSW to keep the coarse navigation layers relatively sparse while giving the bottom layer a larger connection budget for fine-grained search.</p><p>The paper’s experiments suggest Mmax0 = 2 × M as a good operating point. Setting Mmax0 = M produced a strong performance penalty at high recall, while increasing it beyond 2M added memory and traversal cost without a corresponding improvement.</p><h3>A note on the entry points</h3><p>HNSW maintains a designated entry-point node at the highest layer.</p><p>This is different from NSW, where search quality could improve by choosing a high-degree hub or by performing multiple searches from different starting nodes. In HNSW, the hierarchy is designed so that search can begin from one designated node and progressively descend toward the query.</p><p>HNSW therefore has one <strong>global entry point</strong> at its highest populated layer, but the starting point used as the search descends depends on the operation.</p><p>During normal query search — and during the initial greedy phase of insertion — the closest node found in one upper layer becomes the entry point to the layer below.</p><p>During the broader construction phase, however, HNSW can pass the entire candidate set W found at one layer down as the entry-point set for the next.</p><p>The designated top-level entry point itself remains unchanged unless a newly inserted vector is assigned a level higher than the current maximum layer. In that case, the new vector becomes the new global entry point for future searches and insertions.</p><h3>How HNSW Search Actually Works</h3><p>Once the graph has been constructed, querying HNSW follows the same coarse-to-fine idea we saw during insertion.</p><p>Given a query vector q, the goal is to find its approximate k nearest neighbors without exploring the entire graph.</p><p>Search happens in two stages:</p><h4>Phase 1: Greedily descend through the upper layers</h4><p>Search begins from the designated entry point at the highest existing layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ousy82fyxN9K1gFvFXSmvA.png" /><figcaption><strong>Greedy navigation through HNSW’s upper layers:</strong> search starts at the sparsest layer, moves greedily toward the query, and uses the closest node found as the entry point to the next, denser layer.</figcaption></figure><p>At each upper layer, HNSW performs the same greedy navigation we saw during construction:</p><ol><li>Compare the current node with its neighbors.</li><li>Move to the neighbor that is closer to q.</li><li>Continue as long as the distance improves.</li><li>When no neighbor is closer, stop at that local minimum.</li><li>Use that node as the entry point for the layer below.</li></ol><p>Importantly, although all neighbors of the current node may be evaluated, the upper-layer search follows only the <strong>single best route forward</strong>.</p><h4>Phase 2: Broaden the search at Layer 0</h4><p>Once HNSW reaches Layer 0, simple greedy search is no longer enough.</p><p>A greedy walk could stop at a local minimum even though better vectors exist nearby through another route. HNSW therefore keeps multiple promising candidates alive simultaneously.</p><p>The width of this search is controlled by ef—commonly exposed at query time as efSearch. Typically, efSearch must be at least as large as the requested k.</p><p>The original paper calls this query-time parameter simply ef; many modern implementations expose the same concept as efSearch. I will use efSearch here to distinguish it from efConstruction.</p><h3>What actually happens inside the Layer 0 search?</h3><p>At Layer 0, HNSW is no longer doing the single-path greedy search used in the upper layers. It now explores multiple promising paths at once.</p><p>To do this, it keeps track of two things:</p><ul><li>C — where should I explore next?<br> This contains promising nodes whose neighbors have not yet been fully explored. HNSW always expands the closest one first.</li><li>W — what are the best nodes I have found so far?<br> This keeps up to efSearch of the closest nodes discovered during the search. It is a working set, not yet the final top-k result.</li></ul><p>HNSW also maintains a <strong>visited set</strong> alongside these two collections. Its role is simpler: once a node has been encountered, it prevents the same node from being evaluated again through another graph edge.</p><p>The Layer 0 entry point is initially added to C, W, and the <strong>visited set</strong>.</p><p>The visited set has a simpler role: once a node has been encountered, it prevents HNSW from evaluating the same node again through another graph edge.</p><p>HNSW then repeats the following process:</p><ol><li>Take the closest unexplored node from C.</li><li>Look at each of its neighbors that has not already been visited.</li><li>Compute that neighbor’s distance to the query q.</li><li>If W still has room, keep the neighbor.</li><li>If W is full, keep the neighbor only if it is closer than the farthest node currently in W.</li><li>A kept neighbor is added to C so that its own neighborhood can potentially be explored, and to W because it is currently among the best candidates found.</li><li>If W grows beyond efSearch, remove its farthest node.</li></ol><p>So C drives exploration, while W keeps track of the best candidates discovered so far.</p><h4>When does HNSW know it can stop?</h4><p>This is the key part.</p><p>At any point, suppose:</p><ul><li>c is the closest node still waiting to be explored in C</li><li>f is the farthest node among the current efSearch best candidates in W</li></ul><p>Now compare them:</p><pre>distance(c, q) &gt; distance(f, q)</pre><p>If this is true, then even the best unexplored node is already worse than the worst node we currently consider worth keeping.</p><p>HNSW therefore stops expanding the graph. The search also ends naturally if there are no candidates left in C.</p><p>Importantly, this does <strong>not</strong> prove that no better vector exists somewhere else in the graph. It only tells HNSW that none of the currently discovered paths look promising enough to continue exploring. This is where the approximate nature of the search appears.</p><p>A larger efSearch keeps more alternatives alive and makes premature termination less likely, generally improving recall at the cost of additional graph exploration and distance computations.</p><p>When the search terminates, W contains up to efSearch of the best candidates discovered. HNSW returns the closest k among them.</p><h3>Conclusion</h3><p>HNSW can be understood as a structured refinement of NSW rather than a completely different idea. NSW already showed that nearest-neighbor search could emerge from graph navigation, but HNSW made that navigation far more deliberate.</p><p>Its hierarchy separates different distance scales: sparse upper layers support coarse movement across the space, while denser lower layers provide increasingly local refinement. Random level assignment maintains this hierarchy statistically as the index grows, while bounded degree prevents older nodes from growing into uncontrolled hubs.</p><p>The graph itself is also shaped for navigation rather than simple geometric closeness. During insertion, HNSW searches for candidate neighbors, applies a diversity-aware selection heuristic, creates reciprocal links, and prunes neighborhoods that exceed their allowed degree. This preserves multiple useful directions through the graph instead of keeping only the nearest connections.</p><p>Search follows the same coarse-to-fine structure. The upper layers use greedy descent to quickly locate a promising region, while Layer 0 switches to a broader search controlled by efSearch, allowing multiple paths to compete before the final top-k neighbors are returned.</p><p>What makes HNSW effective is therefore not any single mechanism, but how these pieces work together: <strong>hierarchy controls scale, randomized level assignment creates sparsity, neighbor selection preserves navigability, degree limits control graph growth, and </strong><strong>efConstruction and </strong><strong>efSearch expose the trade-off between quality and work.</strong></p><p>Seen this way, HNSW is less a “multi-layer graph” and more a carefully engineered way of organizing and navigating proximity information across multiple scales.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50f6dd6de61b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vector-search-from-first-principles/deep-dive-hnsw-why-adding-hierarchy-changed-graph-search-50f6dd6de61b">Deep Dive: HNSW — Why Adding Hierarchy Changed Graph Search</a> was originally published in <a href="https://medium.com/vector-search-from-first-principles">Vector Search From First Principles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector Search From First Principles: From NSW to HNSW]]></title>
            <link>https://medium.com/vector-search-from-first-principles/vector-search-from-first-principles-from-nsw-to-hnsw-d06bbb51c704?source=rss----c3d8c12616d1---4</link>
            <guid isPermaLink="false">https://medium.com/p/d06bbb51c704</guid>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[hnsw]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Pranshu Shukla]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 15:31:02 GMT</pubDate>
            <atom:updated>2026-09-24T15:31:02.492Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQTstK7YuYZivP752DuVAw.png" /></figure><p>In the <a href="https://medium.com/vector-search-from-first-principles/vector-search-from-first-principles-navigable-small-world-graphs-b64d362c981d">previous article</a>, we saw how <strong>Navigable Small World (NSW)</strong> graphs turn nearest-neighbor search into a navigation problem.</p><p>Their key insight is the combination of <strong>short-range links</strong>, which help search locally, and <strong>long-range links</strong>, which act as shortcuts across the vector space.</p><p>But NSW has a scaling problem.</p><p>As new vectors are inserted, they connect to existing nodes, and those connections are often reciprocal. Over time, frequently selected nodes can accumulate increasingly large neighborhoods. A node that once had 8 connections might eventually have dozens more.</p><p>Simply allowing the graph to accumulate more and more edges is therefore not a scalable solution. We want to preserve the useful shortcuts that make NSW navigable without allowing the cost of exploring the graph to grow with it.</p><p>In this article, we will tackle this scaling problem through one of the most popular and widely used algorithms in modern vector search: <strong>Hierarchical Navigable Small World graphs — HNSW</strong>.</p><h3>The problem is easier if we separate scales</h3><p>Consider how we navigate from one place to another in the real world — <strong>Navigation becomes progressively more local as we get closer to the destination.</strong></p><p>Suppose we want to travel from <strong>New York to a specific address in London</strong>.</p><p>We might navigate in stages:</p><ol><li><strong>New York → London Heathrow</strong> by flight</li><li><strong>Heathrow → central London</strong> by airport shuttle or train</li><li><strong>Central London → the destination neighborhood</strong> by bus</li><li><strong>Bus stop → the exact address</strong> by walking</li></ol><p>Once you reach London, those global connections are no longer useful. You switch to a denser regional network — The closer we get, the <strong>smaller and more precise our movements become</strong>.</p><p>HNSW applies the same idea to vector search: use sparse upper layers for large movements across the vector space, then descend into progressively denser layers as the search gets closer to the query.</p><p>But how do we actually build a graph that gives us these different scales of movement?</p><p>The answer is to let the same vectors participate in <strong>different layers of the graph</strong>.</p><h3>A High Level Gist of the the Hierarchy at Play</h3><p>Instead of constructing a single NSW graph, HNSW organizes vectors across multiple graph layers.</p><p>At the bottom, <strong>Layer 0 contains every vector</strong>. A smaller subset of those vectors also appears in Layer 1. An even smaller subset appears in Layer 2, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MdTH16igL4zprN4fg2nq-A.png" /><figcaption><strong>HNSW hierarchy in action:</strong> sparse upper layers enable large jumps across the vector space, while progressively denser lower layers refine the search until it reaches the nearest candidate at Layer 0.</figcaption></figure><p>In the sparse upper layers, the remaining vectors are typically farther apart, so connections between them can carry the search across large portions of the vector space — much like moving between major airports.</p><p>As the search descends, more vectors become available and the graph becomes denser. The search can therefore make progressively smaller and more precise movements.</p><p>But this hierarchy does not exist automatically. To get sparse upper layers and a dense bottom layer, HNSW needs a rule for deciding <strong>how high each vector is allowed to appear in the graph</strong>.</p><h3>How are the layers built?</h3><p>When a new vector is inserted, HNSW must decide whether it will exist only in Layer 0, also appear in Layer 1, or perhaps be promoted even higher.</p><p>The interesting part is that this decision is <strong>not based on the vector’s location, importance, or how well connected it is</strong>. Instead, HNSW assigns each vector a maximum layer probabilistically.</p><p>Just like NSW, HNSW builds the graph <strong>one vector at a time</strong>. The key difference is that before each vector is inserted,<strong> HNSW randomly assigns it a maximum layer. The vector is then included in that layer and every layer below it.</strong></p><p><strong>This means every vector is present in Layer 0</strong>, while only a subset of vectors also appear in the upper layers.</p><p><strong>The level assignment is random, but the probability of reaching higher layers decreases exponentially.</strong> As a result, most vectors remain only in the lower layers, progressively fewer appear as we move upward, and only a very small number reach the highest layers.</p><p>As a result, the hierarchy becomes naturally sparser as we move upward:</p><pre>Layer 3    very few vectors<br>Layer 2    fewer vectors<br>Layer 1    more vectors<br>Layer 0    every vector</pre><p>Because of this, the hierarchy naturally becomes sparser toward the top, without requiring a separate algorithm to choose special cluster centers, landmarks, or representative vectors.</p><h3>Searching through the hierarchy</h3><p>Now that we know how vectors are distributed across the layers, we can see how HNSW uses that hierarchy during search.</p><h4>Step 1: Navigate greedily through the upper layers</h4><p>The search begins from an <strong>entry point in the highest layer</strong>.</p><p>Because the upper layers contain relatively few vectors, their connections span larger portions of the vector space. This allows HNSW to move quickly toward the region where the query is likely to lie without immediately searching the dense graph below.</p><p>From the entry point, HNSW compares the query with the current node’s neighbors and moves to a neighbor if it is closer to the query.</p><p>It continues doing this until <strong>none of the neighboring nodes in that layer provides a better move</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ousy82fyxN9K1gFvFXSmvA.png" /><figcaption><strong>Greedy navigation through HNSW’s upper layers:</strong> search starts at the sparsest layer, moves greedily toward the query, and uses the closest node found as the entry point to the next, denser layer.</figcaption></figure><p>At that point, the search does not stop. Instead, it <strong>drops down one layer</strong>, using the best node found in the previous layer as the entry point for the next one.</p><p>This is similar to the New York-to-London example: once we reach London, we no longer need the flight network. We switch to a more detailed transportation network and continue from where the previous stage left us.</p><h4>Step 2: Search more broadly at the bottom-most layer</h4><p>When the search finally reaches <strong>Layer 0, the bottom-most layer</strong>, the behavior changes.</p><p>In the upper layers, HNSW performs greedy navigation, effectively following the single best direction it can find before descending.</p><p>At Layer 0, however, HNSW performs a <strong>broader search</strong>. Instead of keeping only one promising node, it can retain and explore multiple candidates around the query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9njZGrCDAdWagGj1-Yt1Q.png" /><figcaption><strong>Broader search at Layer 0:</strong> after the upper layers bring the search near the query, HNSW explores multiple promising candidates in the dense bottom layer, with efSearch controlling how broadly that local neighborhood is explored.</figcaption></figure><p>The amount of exploration at this bottom-most layer is controlled by a parameter efSearch.</p><p>A larger efSearch allows HNSW to explore more candidates before returning the nearest neighbors, which generally improves recall but requires more distance calculations.</p><p>So far, we have looked at the hierarchy from the perspective of <strong>searching an already-built graph</strong>. But HNSW uses almost the same navigation machinery while constructing the graph itself.</p><p>When a new vector arrives, the hierarchy first helps us find the region where that vector belongs. Only after reaching that region do we decide which existing vectors it should connect to.</p><h3>Inserting a new vector</h3><p>When HNSW adds a new vector, it does not compare it against every existing vector. Instead, it uses the hierarchy to first reach the right region of the graph, and only then begins creating connections.</p><p>Suppose the graph currently extends up to <strong>Layer 3</strong>, while the new vector X has been randomly assigned a maximum level of <strong>Layer 2</strong>.</p><p>This means X will eventually be inserted into Layers <strong>2, 1, and 0</strong>, but not Layer 3. The search therefore first has to navigate from the graph’s current top layer down to the highest layer where X can actually participate.</p><h4>Phase 1: Navigate down to the highest layer where X belongs</h4><p>HNSW begins from the current entry point in the highest layer.</p><p>At <strong>Layer 3</strong>, X does not belong to the layer, so no edges are created yet. This layer is used only for <strong>greedy navigation</strong>: HNSW moves from node to node as long as it finds a neighbor that is closer to X.</p><p>Once no better move is available, the algorithm descends one level and continues from the best node it just found.</p><p>In this example, that brings us to <strong>Layer 2</strong> — the highest layer assigned to X.</p><p>So the role of the layers <strong>above </strong><strong>X&#39;s maximum level</strong> is simply to guide insertion toward the right region of the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2DbOHGxgMC-Ll6db_lDAGw.png" /><figcaption><strong>Phase 1 of HNSW insertion:</strong> the new vector X does not create edges immediately. Search first navigates greedily through the existing upper layer and uses the closest node found as the entry point to the highest layer where X will actually be inserted.</figcaption></figure><h4>Phase 2: Search for candidate neighbors</h4><p>Once HNSW reaches <strong>Layer 2</strong>, insertion actually begins.</p><p>At this point, it performs a <strong>broader local search</strong> around X to find promising nearby nodes that could become its neighbors. Unlike the greedy navigation used in the layers above, this search keeps <strong>multiple candidates</strong> rather than following only one path.</p><p>The size of this search is controlled by another parameter efConstruction.</p><p>A larger efConstruction allows HNSW to explore more of the graph before deciding where X should connect. This usually improves graph quality, because it gives the algorithm a better candidate set, but it also makes index construction more expensive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OI3vSf73V0gSpXgWiJG7nA.png" /><figcaption><strong>Phase 2 of HNSW insertion:</strong> once the search reaches the highest layer where X belongs, HNSW performs a broader local search to collect candidate neighbors, with efConstruction controlling how widely that neighborhood is explored.</figcaption></figure><h4>Phase 3: Create connections and move to next layer</h4><p>After finding candidate neighbors at a layer, HNSW does not connect X to all of them.</p><p>Instead, it selects up to M neighbors and creates connections between those nodes and X.</p><p>These connections are bidirectional. That means if X connects to an existing node A, then A also adds a connection back to X.</p><p>Once the connections for that layer have been created, HNSW moves down to the <strong>next layer</strong>.</p><p>This process repeats until HNSW reaches <strong>Layer 0</strong>, where every vector in the graph exists. The bottom layer is treated slightly differently: nodes are allowed to retain <strong>more connections than in the upper layers</strong>. In the original HNSW formulation, the maximum degree is controlled by Mmax0 at Layer 0 and Mmax in the upper layers, with Mmax0 typically set larger.</p><p>Note — This is separate from efConstruction, which controls how many candidates are explored while searching for those neighbors.</p><p>The reason is that <strong>Layer 0 performs the final, detailed nearest-neighbor search</strong>. Giving nodes more local connections at this layer provides more alternative paths between nearby vectors, improving connectivity and recall where the most thorough part of the search happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-VHx6Jc8DgpWPN3tpVH9yg.png" /><figcaption><strong>Phase 3 of HNSW insertion:</strong> after candidate neighbors are found, the new vector X connects to a selected subset, then repeats the process at each lower layer. Layer 0 permits a larger maximum degree (Mmax0) to preserve richer local connectivity for the final search stage.</figcaption></figure><p>Giving Layer 0 more connectivity helps the final search, but HNSW still cannot allow neighborhoods to grow without limit. The graph only remains efficient if each node keeps a <strong>small, carefully chosen set of connections</strong>.</p><p>That creates the next problem: when a new vector finds many promising candidates during construction, <strong>which ones should actually become edges, and which ones should be discarded?</strong></p><h3>Keeping the graph sparse: neighbor selection and pruning</h3><p>The sparse connectivity at each layer is what keeps HNSW efficient, but bidirectional connections create a problem as the graph grows.</p><p>Because connections are <strong>bidirectional</strong>, every time a new vector chooses an existing node as a neighbor, that existing node also gains another edge. Over many insertions, some popular nodes could therefore accumulate more and more connections.</p><p>If HNSW allowed that to continue indefinitely, those nodes would become expensive to explore and the graph would gradually lose the sparsity that makes search efficient.</p><p>HNSW therefore needs an additional mechanism to limit each node’s degree while preserving the connections that are most useful for navigation.</p><p>The simplest solution would be to keep the M closest neighbors and prune everything farther away.</p><p>But HNSW deliberately does something more careful than that.</p><h4>Why not just keep the closest neighbors?</h4><p>Suppose a node X is allowed to keep only M connections, but HNSW has found many possible neighbors.</p><p>The obvious solution would be to sort them by distance from X and simply keep the closest M.</p><p>Those neighbors may all be individually good choices, but together they can be <strong>redundant</strong>: several of them may lie in roughly the same direction or region of the vector space.</p><p>Think back to the <strong>New York → London</strong> example. Assume you have crossed from New York to Europe and are now navigating <strong>Layer 2 — the European travel network</strong>.</p><p>If an airport keeps connections only to its geographically closest cities, reaching London might look like:</p><p><strong>Airport → nearby city A → nearby city B → nearby city C → … → London</strong></p><p>Every individual connection makes sense locally, but the network may require many small hops because the airport has no connection that takes us substantially farther across Europe.</p><p>Now suppose one of those redundant local connections is replaced with a slightly longer one:</p><p><strong>Airport → farther European hub → London region</strong></p><p>That connection may be longer, but it gives the graph something the collection of nearby connections did not: <strong>a route into a different part of the region</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vChZRD5SkfL_hsG1FjVg9w.png" /><figcaption><strong>Why HNSW prefers diverse neighbors:</strong> keeping only the closest connections can concentrate all edges in one region, while retaining a slightly farther but complementary neighbor can open a new route through the graph and reduce the number of hops needed to reach distant regions.</figcaption></figure><p>The same principle applies to X. The best neighborhood is therefore not necessarily the M closest vectors. It is a set of neighbors that remains reasonably close to X while also providing <strong>different directions through the graph</strong>.</p><h4>Solution — Keep a diverse set of neighbors</h4><p>HNSW therefore does not select neighbors purely by their distance from X. Its neighbor-selection heuristic also considers whether a candidate provides a useful connection beyond those already selected.</p><p>Instead of selecting neighbors purely by their distance from X, HNSW uses a heuristic that also considers <strong>how similar the candidate connections are to each other:</strong></p><ol><li>It starts by considering candidates from closest to farthest and selects the closest candidate first.</li><li>After selecting the closest candidate, HNSW evaluates each remaining candidate against the neighbors it has already kept.</li><li>If a candidate is very close to one of those selected neighbors, then keeping a direct edge from X to that candidate may add little new value.</li><li>But if the candidate lies in a different direction or region, the edge may be worth keeping and we do not discard.</li></ol><p>Returning to our European travel network, this is the difference between giving an airport four routes to neighboring cities and giving it a smaller set of routes that includes both nearby cities <strong>and useful connections farther across Europe</strong>.</p><p>The goal is not to deliberately choose long edges. It is to avoid spending the limited edge budget on several connections that provide essentially the same route.</p><p>But this selection problem does not happen only for the new vector. Because HNSW creates bidirectional connections, adding X can also push one of its existing neighbors beyond its allowed degree.</p><p>In that case, HNSW must apply the same principle again: keep a bounded, useful set of connections and prune the rest.</p><h4>Pruning when a node has too many connections</h4><p>Suppose a newly inserted vector X chooses an existing node A as one of its neighbors. A must now add a connection back to X.</p><p>But A may already be at its connection limit.</p><p>HNSW therefore takes the enlarged set of possible neighbors for A and runs the neighbor-selection heuristic again. It keeps the most useful set of connections and removes the rest.</p><p>This allows HNSW to achieve two things at the same time:</p><ol><li><strong>Bound the number of connections</strong> so that individual nodes do not become increasingly expensive to explore.</li><li><strong>Preserve diverse connections</strong> so that pruning does not remove the longer, useful routes that make the graph navigable.</li></ol><p>And this directly addresses one of the scaling problems we saw with NSW: rather than allowing old nodes to accumulate an ever-growing number of connections, HNSW keeps their neighborhoods bounded while deliberately choosing which connections are worth preserving.</p><h3>Where Do a Billion Vectors Live?</h3><p>HNSW gives us an efficient way to navigate a large vector collection, but it creates a new systems problem: <strong>the graph and the vector representations used during search need to stay memory-resident to keep traversal fast.</strong></p><p>At billion-vector scale, that becomes expensive very quickly. A 768-dimensional vector alone takes about <strong>3 KB</strong>, so one billion vectors would require roughly <strong>3 TB of RAM just for the vectors</strong>, before accounting for HNSW edges and other index structures.</p><p>So after solving navigation, the next question becomes:</p><p><strong>How do we reduce the memory footprint enough to keep billion-scale vector search practical without destroying search quality?</strong></p><p>That is where <strong>vector quantization</strong> enters the picture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d06bbb51c704" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vector-search-from-first-principles/vector-search-from-first-principles-from-nsw-to-hnsw-d06bbb51c704">Vector Search From First Principles: From NSW to HNSW</a> was originally published in <a href="https://medium.com/vector-search-from-first-principles">Vector Search From First Principles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive: How Navigable Small World Graphs Made Greedy ANN Search Work]]></title>
            <link>https://medium.com/vector-search-from-first-principles/deep-dive-how-navigable-small-world-graphs-made-greedy-ann-search-work-da34e6949c02?source=rss----c3d8c12616d1---4</link>
            <guid isPermaLink="false">https://medium.com/p/da34e6949c02</guid>
            <category><![CDATA[information-retrieval]]></category>
            <category><![CDATA[nearest-neighbor-search]]></category>
            <category><![CDATA[search-engines]]></category>
            <category><![CDATA[graph-algorithms]]></category>
            <category><![CDATA[vector-search]]></category>
            <dc:creator><![CDATA[Pranshu Shukla]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 15:31:01 GMT</pubDate>
            <atom:updated>2026-09-22T15:31:01.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9rwzGb_3RCcTywuGcFH9fw.png" /></figure><p>In 2014, Malkov et al. published <em>Approximate Nearest Neighbor Algorithm Based on Navigable Small World Graphs</em>, exploring a deceptively simple idea: <strong>what if nearest-neighbor search could be treated as navigation through a small-world network?</strong></p><p>The paper builds on a property observed in small-world graphs: most connections are local, but a small number of longer-range links make distant parts of the graph reachable in surprisingly few steps. If a proximity graph could develop the same structure, greedy search could use those links to move rapidly across the dataset before narrowing in on the neighborhood of the query.</p><p>This shifts the interesting problem away from simply connecting nearby vectors. The graph has to be <strong>navigable</strong>: its structure must allow a search making local, greedy decisions to efficiently find its way through the dataset.</p><p>This article digs into how NSW constructs such a graph, why small-world structure makes greedy search work, and where the approach eventually leaves room for HNSW.</p><p>I’ll use vectors and Euclidean diagrams throughout for intuition, although NSW itself only requires a meaningful distance function between objects.</p><h3>Understanding the Core Idea — Representing the dataset as a graph</h3><p>For greedy search to navigate toward a query, the vectors first need to be connected in a way that gives the search somewhere to move.</p><p>This is the first important step in NSW. The dataset is represented as a graph G(V, E), where every object becomes a vertex and the graph-construction algorithm determines which vertices are connected.</p><p>The paper describes the structure as:</p><blockquote>“The structure S is constructed as a navigable small world network represented by a graph G(V,E), where objects from the set X are uniquely mapped to vertices from the set V. The set of edges E is determined by the structure construction algorithm.”<em><br> — Section 3</em></blockquote><p>So if the dataset contains vectors (A, B, C, D, E …), each receives a corresponding vertex in the graph. The important part is not the mapping itself, but the edges created between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ReQYRMIqBM_buLS5QVx-Bw.png" /><figcaption>Each vector is mapped to a vertex, while the construction algorithm determines the edges that make the graph navigable during search.</figcaption></figure><p>Once these connections exist, search no longer has to examine every vector independently. It can begin from a vertex and move through its neighbors, using distance to the query to decide which parts of the graph are worth exploring.</p><p>This makes the topology of the graph critical. A graph containing only very local connections may require many small steps to cross the dataset, while poorly placed connections can leave greedy search trapped in the wrong region.</p><p>NSW’s central idea is to construct a graph that combines <strong>local proximity with enough longer-range connectivity to remain navigable</strong>.</p><p>What makes the algorithm particularly interesting is how it builds this structure: <strong>the graph is constructed using the same search process that will later be used to query it.</strong> Each new vector searches the existing graph for nearby vertices, then creates connections to the vertices it discovers.</p><p>Because construction itself depends on this search procedure, we first need to understand how NSW navigates the existing graph.</p><h4>Greedy Search</h4><p>Greedy search makes the best local move it can at each step. Starting from a vertex, it compares the query with that vertex’s neighbors and moves to a neighbor only if it is closer to the query than the current vertex. It then repeats the same process from the new position until no neighboring vertex is closer, at which point the search stops.</p><p>Suppose we begin at node A. Its neighbors are B, C and D .</p><p>Now, for the query Q, we try to find the closest vector.</p><pre>distance(Q, A) = 10<br>distance(Q, B) = 8<br>distance(Q, C) = 6 &lt;---  Closest, expand from here<br>distance(Q, D) = 9</pre><p>Among A&#39;s neighbors, C is closest to the query. Since C is also closer to Q than the current node A, the search moves to C.</p><p>The same process is then repeated using C as the current node: examine its neighbors, find the one closest to Q, and move there if it improves upon the current distance.</p><p>Greedy search can quickly move toward increasingly relevant regions without scanning the whole graph. But its effectiveness depends entirely on the routes the graph provides. If most connections are short-range, the search may need a long sequence of small hops to cross the space. More importantly, it can reach a vertex whose neighbors are all farther from the query, even though much closer vectors exist elsewhere in the graph.</p><p>This is the <strong>local minimum problem</strong>.</p><h4>The Local Minimum Problem</h4><p>The weakness of greedy search becomes especially important during graph construction. Now consider what happens when we are <strong>inserting a new node </strong><strong>P into the graph</strong>.</p><p>To decide where P should connect, the algorithm starts from an existing entry point and greedily walks toward nodes that are closer to P. At every step, it only evaluates the neighbors of its <strong>current vertex</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0jZpktMXyNVo1a1syRLlwQ.png" /><figcaption>Diagram showing greedy insertion search for a new node P. The search follows D → I → J → K as distance to P decreases, but stops at K even though G and H elsewhere in the graph are closer to P, illustrating the local minimum problem.</figcaption></figure><p>In the example above, the search progresses:</p><p><strong>D (7) → I (5) → J (4) → K (3.5)</strong></p><p>Each move brings us closer to P, so the greedy rule appears to be working.</p><p>But once the search reaches <strong>K</strong>, it has a problem. None of K’s connected neighbors are closer to P than K itself. From K&#39;s local view, there is nowhere better to go, so the greedy search stops.</p><p>Yet K is <strong>not</strong> the closest node in the graph.</p><p>Elsewhere, <strong>G (3)</strong> and <strong>H (2)</strong> are both closer to P. The search simply cannot see them from K because reaching that region would require following graph connections that do not immediately improve the distance.</p><p>This is the <strong>local minimum problem</strong>:</p><h4>Can We Build a Graph Where Greedy Search Never Gets Stuck?</h4><p>In Euclidean space, an ideal graph for this purpose is the <strong>Delaunay graph</strong>.</p><p>Imagine every data point surrounded by a region containing all locations closer to that point than to any other. Together, these regions form a <strong>Voronoi diagram</strong>.</p><p>When two such regions share a boundary, their corresponding data points are Voronoi neighbors. Connecting those neighboring points gives the <strong>Delaunay graph</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lyAMbRNzpFx0J9E1ZGzARg.png" /></figure><p>With this graph, if the current vertex is not the closest point to the query, there is always a neighboring vertex that moves the search closer. In other words, greedy search does not get trapped at a false local minimum. That makes the Delaunay graph a useful picture of the kind of connectivity we would ideally like.</p><p><strong>But NSW cannot simply construct this ideal graph.</strong> The paper targets general metric spaces, where an exact Delaunay graph cannot generally be determined from the distance function alone. The trivial way to guarantee that no required connection is missing would be to keep the complete graph — which defeats the purpose of building a sparse search structure.</p><p>NSW therefore takes a more practical approach: rather than constructing the perfect neighborhood graph, it relies on approximate graph search to discover useful nearby vertices.</p><p>But before we can see how that works during insertion, we need to understand the full NSW search procedure. The simple greedy walk we have seen so far is only the starting point.</p><h3>Extending Greedy Search Beyond a Single Nearest Neighbor</h3><p>The basic greedy walk is useful for finding one nearby vertex, but NSW needs something more robust for k-nearest-neighbor search. The paper extends the search in three important ways: <strong>multiple entry points, shared exploration, and best-first expansion of promising candidates.</strong></p><h4>Multiple Entry Points</h4><p>Starting from a single vertex is risky. If that entry point leads the search into the wrong region of the graph, better neighbors may never be discovered.</p><p>NSW therefore allows the search to start from several randomly chosen entry points. The parameter m controls how many such attempts are made. Each additional start gives the search another opportunity to enter a useful part of the graph that an earlier traversal may have missed.</p><p>As m increases, more of the graph can potentially be explored. In the extreme, with enough distinct starting points, the process approaches exhaustive search.</p><h4>Share What Has Already Been Explored</h4><p>These search attempts do not operate independently. They share the same visitedSet.</p><p>Once a vertex has already been explored and its neighbors examined, another search does not need to expand it again. This avoids repeating the same work when different traversals eventually reach the same part of the graph.</p><p>The benefit is that new entry points can spend their effort exploring <strong>new regions</strong>, rather than retracing paths that earlier attempts have already covered.</p><h4>Keep Exploring While the Best k Results Can Still Improve</h4><p>For a single nearest neighbor, a simple greedy walk can stop when no immediate neighbor is closer to the query.</p><p>For k-NN search, NSW explores more broadly. It keeps track of the best k vertices found so far, while also maintaining discovered vertices whose neighbors have not yet been examined.</p><p>The search repeatedly expands the <strong>closest promising discovered vertex</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6yXmxGoTqLsYBoYBCm74g.png" /><figcaption>Step-by-step best-first k-nearest-neighbor search showing discovered candidates being expanded in increasing distance to query Q, while maintaining the current top three results and stopping when the closest unexplored candidate is farther than the worst current result.</figcaption></figure><p>Expanding one of these vertices may reveal new nodes that either enter the current top k or become useful candidates for further exploration.</p><p>Eventually, the closest unexplored candidate is farther from the query than the current k-th best result. At that point, the remaining candidates are no more promising than the worst result already in the current top k, so that search attempt can stop.</p><p>Together, these ideas turn simple greedy descent into a broader <strong>best-first graph search</strong>: start from several places, avoid revisiting work already done, and continue exploring the most promising vertices while they still have a chance to improve the current nearest neighbors.</p><p>This is not only NSW’s query algorithm. The same search procedure is also used to decide where new nodes should be connected during construction.</p><h3>Building the Graph Using the Search Itself</h3><p>When a new point P is inserted, NSW runs the same graph search against the existing network to find approximately its nearest existing vertices.</p><p>To insert P, NSW runs its k-NN search with k = f, using w search attempts. The f neighbors returned by that search are then connected bidirectionally to P. This creates an important feedback loop:</p><p><strong>NSW uses search to build the graph, and the graph produced by that construction makes future searches more effective.</strong></p><p>As more points are inserted, the structure available to later insertions becomes richer, allowing the search to find increasingly useful neighborhoods without scanning the entire dataset.</p><h3>Choosing the Construction Parameters</h3><p>Now that we have seen how NSW inserts a new node, we can look more closely at the two parameters that control construction.</p><p>They govern two different decisions:</p><ul><li>w controls <strong>how thoroughly we search for nearby neighbors</strong></li><li>f controls <strong>how many of those neighbors the new node connects to</strong></li></ul><p>Together, they balance construction cost, graph quality, memory, and search efficiency.</p><h4>How Accurately Should We Find Neighbors? — w</h4><p>Construction reuses the same multi-search procedure described earlier. At query time, m controls the number of search attempts; during insertion, that role is played by w.</p><p>A small w means the graph is searched less thoroughly, increasing the chance of missing better neighbors and creating weaker connections.</p><p>Increasing w explores the graph more thoroughly and improves the recall of the neighbors found during insertion. As w increases, the construction search explores more of the graph and its neighbor recall can approach 1.0.</p><p>The authors suggest choosing w so that this recall is roughly <strong>0.95–0.99</strong>. Beyond that, the paper reports little benefit: increasing insertion recall above 0.99 did not measurably improve the final search quality.</p><p>So the goal is not perfect neighbor discovery. It is to make the construction search accurate enough that most of the connections being added are useful.</p><p>The paper also observes that the w required to maintain this quality grows only slowly, approximately <strong>logarithmically with the dataset size</strong>. This means that a much larger dataset does not require a proportional increase in construction-time search effort.</p><h4>How Many Neighbors Should We Connect? — f</h4><p>Once nearby vertices have been found, NSW still needs to decide how many of them the new node should connect to.</p><p>The parameter f controls the number of neighbors selected <strong>when a node is inserted</strong>.</p><p>Importantly, f is not a permanent maximum degree. Because edges are bidirectional, an older node can continue receiving additional connections whenever future insertions choose it as a neighbor. Its degree can therefore grow beyond f.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C6cNY5vgi3DgFtzCkztrVg.png" /><figcaption><em>Diagram showing how the NSW parameter f controls the number of neighbors chosen by a newly inserted node. Increasing f adds more initial connections, while older nodes can later accumulate additional incoming connections and therefore have degree greater than f.</em></figcaption></figure><p>Increasing f makes the graph more connected and generally improves recall, but it also increases memory usage and the amount of work required when expanding a node during search.</p><p>For the Euclidean datasets evaluated in the paper, with dimensions d = 1...20, the authors found empirically that a good choice was approximately: f ≈ 3d</p><p>Smaller values reduce graph density and search cost, but can also reduce recall.</p><h3>Where the “Small World” Comes From</h3><p>The authors tested NSW on uniformly distributed Euclidean datasets and measured how the <strong>average number of hops taken by greedy search</strong> changed as the dataset grew.</p><p>They found that the number of hops increased approximately <strong>logarithmically with dataset size</strong> — the navigation behavior expected from a small-world graph.</p><p>The more interesting question was why this property emerged at all.</p><p>To investigate that, the authors changed the construction process. The logarithmic behavior disappeared when either:</p><ol><li>points were inserted in a non-random order, gradually expanding the occupied region of the space, or</li><li>old connections were removed so that each node retained only its current f nearest neighbors.</li></ol><p>Together, these experiments point to the same mechanism: the small-world behavior depends on <strong>preserving older connections that can become long-range as the graph grows</strong>.</p><p>When an edge is first created, its endpoints may be relatively close because only a small number of points exist in the graph. But as more points are inserted between them, those endpoints may no longer be close in the final dataset.</p><p>The edge remains.</p><p>So a connection that began as a <strong>local edge</strong> can gradually become a <strong>long-range shortcut</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1pZMGIvdtlGRsLmbUchSA.png" /><figcaption>Three-panel diagram showing how an early edge between A and D remains as more nodes are inserted between them, turning an originally short-range connection into a long-range shortcut in the final graph.</figcaption></figure><p>The paper describes this directly:</p><blockquote>“As more and more elements are inserted into the structure, links that previously served as short-range links now become long-range links…”</blockquote><p>If the graph were continuously rewired to keep only the current nearest neighbors, these older edges would disappear — and with them, many of the shortcuts that allow greedy search to cross the graph quickly.</p><p>This is the key idea behind NSW’s small-world structure: <strong>long-range links are not added explicitly. They emerge naturally as old local connections are preserved while the graph continues to grow.</strong></p><p>Random insertion order matters because it allows this process to happen throughout the dataset, producing a mixture of short local edges and older long-range shortcuts.</p><h3>What Did NSW Actually Buy Us?</h3><p>A single greedy traversal becomes longer only slowly as the dataset grows, with the paper observing an approximately logarithmic increase in path length. But NSW does not rely on just one traversal when it wants very high recall.</p><p>To maintain a fixed recall of 0.999 as the dataset grew, the authors also increased the number of multi-search attempts m, and empirically this required m to grow approximately logarithmically with dataset size. Combining these two effects — roughly log n work per traversal and roughly log n traversal attempts — the observed fixed-recall search cost grew approximately as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_4J0APMqnHqrj62Esi-MlA.png" /></figure><p>One logarithmic factor comes from the navigation path length, while the second comes from the increasing number of search attempts required to maintain high recall.</p><p>This was the practical payoff of NSW: a sparse proximity graph whose search cost grew much more slowly than an exhaustive scan.</p><h3>But There Is Still a Problem</h3><p>NSW has now given us the two kinds of links identified by the paper itself: <strong>short-range links</strong> that approximate the local neighborhood structure, and <strong>long-range links</strong> that make the graph navigable at scale.</p><p>But both kinds of edges live together in one flat graph. Their different distance scales emerge indirectly from insertion history rather than being organized explicitly.</p><p>That raises a natural question: what if those scales were separated?</p><p>Search could begin on a sparse graph containing mostly long-range connections, use it to quickly approach the right region, and then move into progressively denser graphs containing increasingly local connections.</p><p>Instead of asking one graph to provide every scale of navigation at once, we could organize those scales into different levels.</p><p>That is the idea that leads from <strong>Navigable Small World</strong> to <strong>Hierarchical Navigable Small World — HNSW</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da34e6949c02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vector-search-from-first-principles/deep-dive-how-navigable-small-world-graphs-made-greedy-ann-search-work-da34e6949c02">Deep Dive: How Navigable Small World Graphs Made Greedy ANN Search Work</a> was originally published in <a href="https://medium.com/vector-search-from-first-principles">Vector Search From First Principles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector Search From First Principles: Navigable Small World Graphs]]></title>
            <link>https://medium.com/vector-search-from-first-principles/vector-search-from-first-principles-navigable-small-world-graphs-b64d362c981d?source=rss----c3d8c12616d1---4</link>
            <guid isPermaLink="false">https://medium.com/p/b64d362c981d</guid>
            <category><![CDATA[hnsw]]></category>
            <category><![CDATA[nearest-neighbor-search]]></category>
            <category><![CDATA[graph-algorithms]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[vector-search]]></category>
            <dc:creator><![CDATA[Pranshu Shukla]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 05:22:52 GMT</pubDate>
            <atom:updated>2026-08-22T05:22:52.072Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VjNq3AvmAPyp7geZUEMYug.png" /></figure><p><a href="https://medium.com/vector-search-from-first-principles/vector-search-from-first-principles-from-exact-search-to-approximate-nearest-neighbors-6125d53c680e">In the previous article</a>, we moved from <strong>exact nearest-neighbor search</strong> to <strong>Approximate Nearest Neighbor search</strong>.</p><p>ANN gave us an important freedom: we no longer have to examine every vector in the dataset.</p><p>But that immediately creates another problem. <strong><em>If we are going to ignore most of the dataset, how do we decide which vectors are worth examining?</em></strong></p><p>We need some structure that can guide the search toward promising parts of the vector space without first calculating the distance to everything.</p><p>One surprisingly intuitive solution is:</p><blockquote><strong><em>Turn the vectors into a graph, and navigate through that graph toward the query.</em></strong></blockquote><p>Instead of asking: <em>Which of these millions of vectors is closest to my query?</em></p><p>we can begin asking: <em>From where I currently am, which neighboring vector moves me closer to the query?</em></p><p>This is the idea behind <strong>graph-based ANN search</strong>, and one of its earliest influential forms is the <strong>Navigable Small World graph</strong>, or <strong>NSW</strong>.</p><h3>Turning vector search into graph navigation</h3><p>Consider a small collection of two-dimensional vectors:</p><pre>A = [1.0, 1.0]<br>B = [1.2, 1.1]<br>C = [2.0, 1.8]<br>D = [6.0, 5.8]<br>E = [7.0, 6.5]<br>F = [8.0, 7.0]</pre><p>Plotted in vector space, these would simply appear as scattered points.</p><p>But instead of leaving the vectors independent, suppose we connect nearby vectors to one another.</p><p>We now have a <strong>proximity graph</strong>:</p><ul><li>each vector becomes a node;</li><li>an edge connects one vector to another vector considered nearby.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJI8mLJIImhx5dvZrIl5bA.png" /><figcaption><strong>From vectors to graph navigation:</strong> nearby vectors form a proximity graph, allowing greedy search to move through the space toward the query instead of examining every vector.</figcaption></figure><p>The graph now contains information about the geometry of the dataset. If we are currently at A and want to move toward the region around C, we do not need to inspect every vector in the database.</p><p>The graph already gives us a possible route:</p><pre>A → B → C</pre><p><strong>Vector search has now become a routing problem.</strong></p><p>We no longer need to examine every vector directly. Instead, we need a graph that gives the search useful routes through the dataset.</p><h3>Greedy graph search</h3><p>Suppose the query vector is <strong>Q = [7.4, 6.7]</strong>, and imagine that our search begins at <strong>A</strong>.</p><p>From <strong>A</strong>, we compute its distance to the query and then look at A’s neighbors. If one of those neighbors — say <strong>B</strong> — <strong>is closer to the query than A is, we move to B</strong>.</p><p>We then repeat the same process: from <strong>B</strong>, we inspect its neighbors, and if <strong>C</strong> is closer to the query, we move again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQt1fn9F68ZWEjORevdRNA.png" /><figcaption><strong>Greedy graph search:</strong> at each step, the search evaluates the current node’s neighbors, ignores those that do not improve the distance to the query, and continues only along the most promising path.</figcaption></figure><p>At each step, it chooses the next node by asking a simple question: <em>Which neighbor looks closest to the query?</em></p><p>This is the basic intuition behind <strong>greedy graph search</strong>. The algorithm does not try to understand the whole graph at once. It only uses local information — the current node, its neighbors, and which of those neighbors seems to move the search in the right direction.</p><p>This simple rule gives us a way to move through the graph without examining every vector.</p><p>But how useful that search is now depends heavily on <strong>what connections the graph contains</strong>.</p><p>A graph can have perfectly valid edges and still be painfully slow to navigate.</p><p>The first obvious construction exposes why.</p><h3>A graph containing only local neighbours has a problem</h3><p>The first attempt seems obvious: <em>Connect every vector only to its nearest neighbors.</em></p><p>Our graph might look something like:</p><pre>●──●──●──●──●──●──●──●──●──●──●</pre><p>This gives us excellent <strong>local connectivity</strong>: once the search is in roughly the right region, it can easily move between nearby vectors and refine its answer.</p><p>But local connectivity does not necessarily give us <strong>global navigability</strong>. If the query lies on the other side of the vector space, the search may have to follow many short edges just to get there.</p><p>Our query lies near the right side:</p><pre>start                           query<br>  ↓                                ↓</pre><pre>  ●──●──●──●──●──●──●──●──●──●──●──●</pre><p>If every connection is short, we may need many hops to cross the graph.</p><p>That starts looking suspiciously similar to the problem we were trying to avoid.</p><p>Instead of comparing the query with every vector, we may now be <strong>walking through a large number of vectors one short hop at a time</strong>.</p><p>The data structure changed, but we still have not solved the problem of moving quickly across the dataset.</p><p>We need another kind of connection.</p><h3>Long-range connections change the graph</h3><p>Suppose we keep the local connections but introduce a few longer ones.</p><p>Now the graph contains two kinds of connections, each useful at a different stage of the search.</p><h4>Short connections</h4><p>These connect very similar vectors. They are useful when the search is already near the query and needs to refine its location.</p><h4>Long connections</h4><p>These can jump between distant regions of the vector space. They are useful when the search is still far from the query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4i9t3x3Yzm-X_rkr7dNVjQ.png" /><figcaption><strong>Local vs. long-range navigation:</strong> short connections provide precise local movement, while occasional long-range links let the search cross the vector space in far fewer hops.</figcaption></figure><p>Together, they solve two different parts of the navigation problem:</p><blockquote><strong><em>Long links help us move quickly across the space.</em></strong></blockquote><blockquote><strong><em>Short links help us search precisely once we get there.</em></strong></blockquote><p>This is where the idea of a <strong>small world</strong> enters vector search.</p><h3>The small-world idea</h3><p>The term comes from network science.</p><p>A social network gives us a useful intuition. Most people have many connections within relatively local communities, creating tightly connected clusters. But a smaller number of relationships cross between otherwise distant communities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w2ZjlYr447Qa6ISq-RLRuA.png" /><figcaption><strong>Small-world intuition:</strong> most connections stay within local communities, while a few long-range links connect distant groups and dramatically shorten paths across the network.</figcaption></figure><p>Those occasional long-range connections can dramatically reduce the number of steps required to move through the network.</p><p>That gives us exactly the combination we want for vector search:</p><ul><li><strong>Locally:</strong> many short connections</li><li><strong>Globally:</strong> a smaller number of long-range connections</li></ul><p>The result is a graph where nearby points remain easy to explore, while distant parts of the graph can still be reached in relatively few hops.</p><h3>But where do the long-range connections come from?</h3><p>We now know what we want from the graph:</p><ul><li>short connections that help us navigate precisely within a neighborhood;</li><li>longer connections that let us move quickly between distant regions.</li></ul><p>But do we actually need to decide in advance which edges should be <em>local</em> and which should become <em>long-range shortcuts</em>?</p><p>NSW gets this mixture in a much more interesting way.</p><blockquote><strong><em>It does not explicitly create separate short-range and long-range edges.</em></strong></blockquote><p>Instead, both kinds of connections emerge from the way the graph is constructed.</p><h3>Building a Navigable Small World graph</h3><p>NSW builds the graph <strong>incrementally</strong>.</p><p>Vectors arrive one at a time, and each new vector must make its connections using the graph that exists at that moment.</p><p>Suppose our vectors are arranged in space like this:</p><pre>A    B    C    D    E    F</pre><p>But they are inserted in a random order:</p><pre>D → A → F → B → E → C</pre><p>When a new vector is inserted, NSW searches the graph that already exists, finds approximately its nearest existing vectors, and connects the new vector to them.</p><p>The important detail is that the new vector can only choose among the points that have <strong>already been inserted</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ftVi8dNiqDcqIDy-voJqg.png" /><figcaption><strong>Incremental graph construction:</strong> each new vector can connect only to vectors already present in the graph. As the graph grows, connections created early can persist even after much closer vectors are inserted later.</figcaption></figure><p>Consider what happens early in construction. Suppose only D and A have been inserted:</p><pre>A ─────────── D</pre><p>A and D may be quite far apart in the final dataset.</p><p>But at this moment, there are very few alternatives. Among the vectors that currently exist, they may still be among each other’s closest available neighbors.</p><p>So the connection is created.</p><p>As more vectors arrive, the graph becomes denser. Newly inserted vectors now have more nearby existing points to choose from, so their connections tend to become shorter.</p><h4>An old connection becomes a shortcut</h4><p>When A ─ D was first created, it was not deliberately designed as a shortcut. At that moment, there were simply very few alternatives.</p><p>But after more vectors are inserted between them, the graph might eventually look more like:</p><pre>A ── B ── C ── E ── D<br> \_________________/<br>       old edge</pre><p>What began as a reasonable connection in a sparse graph has become a <strong>long-range shortcut</strong> in the denser graph.</p><p>And this can happen repeatedly as the graph grows.</p><blockquote><strong>Old connections can become shortcuts simply because newer vectors fill the space around them.</strong></blockquote><p>This is how NSW can naturally end up with a mixture of short and long connections without explicitly deciding which edges should belong to each category.</p><h3>But how many connections should we create?</h3><p>So far we have been saying: <em>Connect the new vector to its nearest existing vectors.</em></p><p>But we skipped an important question: <strong><em>How many of them?</em></strong></p><p>This is where a parameter usually written as <strong>M</strong> enters the picture.</p><p>If M = 2, a newly inserted vector creates at most two connections.</p><p>If M = 16, it can connect to many more existing vectors, giving the graph more possible routes.</p><p>At first, increasing M sounds obviously better.</p><p>More connections give the search more alternatives. If one route is unhelpful, another edge may still lead toward a better part of the graph.</p><p>So increasing connectivity can make the graph <strong>easier to navigate</strong>.</p><p>But those additional routes are not free.</p><h4><strong>More edges require more memory.</strong></h4><p>For N vectors, increasing the average number of stored connections increases graph storage roughly with:</p><pre>N × number of connections</pre><p>A graph where every node keeps 32 neighbors needs roughly twice as many neighbor references as one keeping 16.</p><h4>More edges also mean more work during search</h4><p>Suppose the search arrives at a node with four neighbors. It may need to calculate four distances to decide which candidates look promising. If the node has 40 neighbors, there are potentially far more distances to evaluate.</p><p>So M creates a fundamental trade-off:</p><blockquote>More connections give the search more possible routes, but increase both graph storage and the amount of work required when nodes are explored.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oNwEqgUVGQngcOzTMUhIpQ.png" /><figcaption><strong>The connectivity trade-off:</strong> increasing M gives the search more possible routes through the graph, but requires more graph memory and more work each time a node is expanded.</figcaption></figure><h3>Even a good graph does not guarantee that search finds the right path</h3><p>There is one more source of approximation.</p><p>At any point in the search, the algorithm can only make decisions using the part of the graph it can currently see. It prefers the next step that appears to move it closest to the query.</p><p>But there is an important limitation:</p><blockquote><strong><em>The best-looking next step is not necessarily on the best path to the true nearest neighbor.</em></strong></blockquote><p>Suppose, from its current position, the search can continue through either B or D.</p><p>D is currently closer to the query, so it looks like the better choice:</p><pre>distance(D, Q) &lt; distance(B, Q)</pre><p>A purely greedy search would continue through D.</p><p>But the graph behind B might contain a connection to a region much closer to the query.</p><p><strong>Greedy search cannot see that yet.</strong></p><p>From its current perspective, D looks better, so that is the route it prefers.</p><p>This is where the approximation enters: greedy search makes the best decision it can <strong>with the information currently visible to it</strong>.</p><p>The search therefore faces another trade-off.</p><p>If it follows only the single best-looking route, it performs very little work — but it can miss a better region of the graph.</p><p>If it keeps more alternative candidates alive, it has a better chance of discovering those regions — but it must explore more nodes.</p><p>Once again, the ANN trade-off appears: <strong><em>more exploration can improve recall, but it also increases search work.</em></strong></p><h3>NSW solves one problem — and exposes the next one</h3><p>NSW has now given us something powerful.</p><p>A single sparse graph can contain both:</p><ul><li><strong>short connections</strong>, which help refine the search locally; and</li><li><strong>long-range shortcuts</strong>, which help move quickly across the dataset.</li></ul><p>But NSW still leaves us with two related problems.</p><p>First, <strong>all connection scales live inside the same graph</strong>. Short local edges, medium-range connections, and long-range shortcuts are all mixed together.</p><p>Second, <strong>search still has to decide how many alternative routes it is willing to explore</strong>. Exploring fewer routes means less work, while keeping more alternatives alive can improve recall at the cost of additional exploration.</p><p>This suggests a natural question: <strong><em>What if we organized the different connection scales instead of mixing all of them into one graph?</em></strong></p><p>What if search could first use a sparse set of long-range connections to move quickly across the dataset, and then switch to progressively denser, more local connections as it gets closer to the query?</p><p>Instead of putting every connection scale into one graph, <strong>we could organize them into a hierarchy.</strong></p><p>That idea gives us:</p><p><strong>Hierarchical Navigable Small World graphs — HNSW.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b64d362c981d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vector-search-from-first-principles/vector-search-from-first-principles-navigable-small-world-graphs-b64d362c981d">Vector Search From First Principles: Navigable Small World Graphs</a> was originally published in <a href="https://medium.com/vector-search-from-first-principles">Vector Search From First Principles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector Search From First Principles: From Exact Search to Approximate Nearest Neighbors]]></title>
            <link>https://medium.com/vector-search-from-first-principles/vector-search-from-first-principles-from-exact-search-to-approximate-nearest-neighbors-6125d53c680e?source=rss----c3d8c12616d1---4</link>
            <guid isPermaLink="false">https://medium.com/p/6125d53c680e</guid>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[approximate-nearest]]></category>
            <dc:creator><![CDATA[Pranshu Shukla]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 19:15:14 GMT</pubDate>
            <atom:updated>2026-08-19T19:15:14.798Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02Ku3Qel7n7jEBGxqfSzSQ.png" /></figure><p>In the <a href="https://medium.com/vector-search-from-first-principles/vector-search-from-first-principles-what-does-nearest-actually-mean-26948f6a39e6">previous article</a>, we reduced vector search to a surprisingly simple problem:</p><blockquote><em>Given a query vector, find the </em><em>k vectors nearest to it.</em></blockquote><p>Once we choose how to measure “nearest” — using Euclidean distance, cosine similarity, dot product, or another similarity or distance measure —</p><blockquote>The simplest exact k-NN approach is exhaustive search: compare the query against every vector in the database.</blockquote><p>Suppose our database contains</p><pre>A = [1.0, 1.0]<br>B = [1.2, 1.1]<br>C = [8.0, 7.0]<br>D = [7.5, 8.0]</pre><p>and the query is:</p><pre>Q = [1.1, 1.0]</pre><p>We could simply calculate:</p><pre>distance(Q, A)<br>distance(Q, B)<br>distance(Q, C)<br>distance(Q, D)</pre><p>compare the results, and return the closest k.</p><p>With four vectors, this is trivial. Even better, it is exact. Because we inspected every vector, there is nowhere for a nearer neighbor to hide.</p><p>The problem begins when four vectors become four million.</p><h3>Exact search solves the right problem — but does too much work</h3><p>Imagine an index containing one million vectors, each with 768 dimensions. An exact search needs to compare the query with all one million vectors. Very roughly, that means processing:</p><pre>1,000,000 × 768 = 768,000,000</pre><p>vector coordinates for a single query. And this work happens again for the next query. And again for the next one.</p><p>The issue is therefore not that exact nearest-neighbor search gives poor results. Quite the opposite: <em>Exact search is expensive precisely because it refuses to skip anything.</em></p><p>If there is a vector somewhere in the collection that is closer to the query, exact search will find it because every vector is examined.</p><p>But that raises an important question:</p><p><strong><em>Do we really need to inspect every vector to find the nearest ones?</em></strong></p><p>If our query lies in one part of the vector space, perhaps we can use some structure in the index to determine that large parts of the collection are unlikely to contain its nearest neighbors.</p><p>Instead of comparing the query against every vector, we could focus the search on <strong>promising regions or promising paths</strong>, examine a much smaller set of candidate vectors, and return the best matches from that set.</p><p>That is the idea behind <strong>Approximate Nearest Neighbor search</strong>, usually shortened to <strong>ANN</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8opXtPnsjn-CL-dqPYNfg.png" /><figcaption>A simplified ANN pipeline: focus on a promising part of the index, collect a smaller candidate set, then rank those candidates to return the top-k nearest neighbors.</figcaption></figure><p>To make this possible, ANN algorithms typically build additional structure over the vectors ahead of query time. That structure gives the search clues about where to look next, instead of forcing it to inspect the collection blindly.</p><h3>Why does “zooming in” work?</h3><p>Embedding spaces often contain useful local structure: objects that the embedding model considers similar tend to be mapped to nearby vectors.</p><p>So rather than behaving like a completely random collection of points, the space contains neighborhoods that can help guide search.</p><p>A query about dogs, for example, may land near vectors representing other dog-related content rather than vectors representing database configuration or financial reports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*592MFOZFkBG_PnwY6o0kiA.png" /><figcaption>An illustrative view of local structure in an embedding space: semantically related items tend to occupy nearby neighborhoods.</figcaption></figure><p>ANN itself does not understand what these vectors mean. It simply exploits the geometry created by the embedding model: <strong>vectors that are already near the query give us clues about where other nearby vectors may be found.</strong></p><p>That gives us an important property to exploit:</p><blockquote><strong><em>Once the search reaches a neighborhood that is close to the query, nearby vectors are good places to continue looking.</em></strong></blockquote><p>An exhaustive search does not exploit this structure: it still computes the distance from the query to every vector. ANN tries to use that structure to avoid unnecessary comparisons.</p><p>ANN algorithms therefore need additional structures that help decide where to search.</p><p>Some algorithms, such as IVF, partition vectors into regions and search only the regions that appear most promising. Others, such as HNSW, connect vectors through a graph and navigate through promising neighbors toward the query.</p><p>Different ANN algorithms build this structure differently, but they are all trying to exploit the same underlying idea: <strong><em>nearby vectors give us clues about where other nearby vectors are likely to be.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WxZRjX5t8X_BzIa7kO4gdA.png" /><figcaption>Two common ANN strategies: search a promising region (as in IVF) or follow promising neighbors through a graph (as in HNSW). Both rely on the same idea: nearby vectors help reveal where other nearby vectors are likely to be.</figcaption></figure><p>Of course, skipping parts of the collection introduces a new risk. What if the vector directing us to a region sends us toward a region that <em>looks</em> promising, while one of the true nearest neighbors lies somewhere we never examine?</p><p>That is where the word <strong>approximate</strong> becomes important.</p><h3>The price of skipping work</h3><p>The idea of searching only a promising part of the vector space sounds compelling. But the moment we decide <strong>not to search every region</strong>, we introduce a new risk.</p><p>Consider a partition-based ANN index, such as IVF, that has divided the vector space into several regions.</p><p>A query lands close to the boundary between <strong>Region A</strong> and <strong>Region B</strong>. Some of its true nearest neighbors therefore lie in Region A, while others lie just across the boundary in Region B.</p><p>During search, however, the index decides that Region A is the most promising region and examines only the vectors inside it.</p><p>It may find several very good neighbors from Region A while completely missing an even closer vector in Region B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xq0n6aDk1XdGy1kGY9PSpA.png" /><figcaption>A partition-based ANN search can miss a true nearest neighbor near a region boundary: the index searches Region A, returns good candidates from that region, but fails to examine Region B, where an even closer neighbor may exist.</figcaption></figure><p>The problem is simply that <strong>the search never looked inside Region B</strong>.</p><p>Graph-based algorithms such as HNSW can miss neighbors for a different reason: the search may simply never navigate through the part of the graph containing them. We will explore that failure mode in more detail when we look at HNSW.</p><p>This is an important point about ANN:</p><blockquote><strong><em>A vector can be very close to the query and still be missed if the search does not explore the part of the index containing it.</em></strong></blockquote><p>An exhaustive exact search cannot make this mistake because it examines every vector, regardless of which region contains it. ANN gains speed precisely because it chooses not to.</p><p>To measure what ANN missed, we compare its results against the results from an exact search. Those exact nearest neighbors form our ground truth.</p><blockquote>Recall tells us <strong>how many of the true nearest neighbors were actually found by the approximate search</strong>.</blockquote><p>For example, suppose exact search identifies the true top-5 nearest neighbors, but ANN recovers only four of them:</p><pre>Exact top-5:   A B C D E<br>ANN top-5:     A B C D F<br><br>recall@5 = 4 / 5 = 0.8</pre><p>The ANN search therefore achieved <strong>80% recall@5</strong>.</p><p>In practice, recall is usually measured offline on benchmark queries, because computing the exact answer for every production query would defeat the purpose of ANN.</p><h3>Then why not simply search more and more?</h3><p>Because eventually we begin undoing the optimization that ANN gave us. At the extreme, if we might end up examining essentially every vector anyway, we are moving back toward the brute-force search we were trying to avoid.</p><p>So ANN is not about maximizing recall regardless of cost.</p><p>It is about finding a useful operating point:</p><blockquote>Explore enough of the index to achieve the recall we need, without exploring so much that ANN loses its advantage.</blockquote><p>Different ANN algorithms expose this trade-off differently.</p><p>In IVF, nprobe controls how many partitions are searched: increasing it explores more of the index and typically improves recall at additional cost.</p><p>In HNSW, ef_search controls how broadly the search explores the graph: increasing it generally allows more candidates to remain under consideration, which usually improves recall at the cost of additional work.</p><p>The mechanisms are different, but both expose the same underlying knob: <em>How much extra work are we willing to perform in exchange for a better chance of recovering the true nearest neighbors?</em></p><h3>ANN is a trade-off, not a single algorithm</h3><p>Approximate nearest-neighbor search is not one specific algorithm. It is a family of techniques built around the same goal: <strong><em>Avoid doing all the work of exact search, while still recovering enough of the true nearest neighbors.</em></strong></p><p>Different ANN algorithms achieve this in different ways. Some divide the vector space into regions and search only the most promising ones. Others build graphs that allow the search to navigate through nearby vectors.</p><p>The mechanism may differ, but the underlying trade-off remains the same:</p><p><strong>Less exploration means less work and lower latency, but a greater chance of missing a true neighbor. More exploration usually improves recall, but gradually gives back the performance advantage that ANN was meant to provide.</strong></p><p>So far, however, we have only established <strong>why</strong> approximate search can be useful.</p><p>We have not yet answered the harder question: <strong>How can a search actually navigate through millions of vectors without examining them all?</strong></p><p>One approach is to turn the vectors into a graph.</p><p>Each vector becomes a node, and nearby vectors are connected to one another. Instead of comparing the query against the entire collection, the search can start from one node and move through the graph, repeatedly following connections that appear to bring it closer to the query.</p><p>But simply connecting nearby vectors is not enough.</p><p>A graph may contain the right nearest neighbor and still make it difficult for the search to reach it efficiently. The structure of those connections determines whether the graph can actually be navigated.</p><p>That leads to the next question:</p><blockquote><strong>What kind of graph allows us to move from almost anywhere in the dataset toward the neighborhood of a query using only a small number of steps?</strong></blockquote><p>That question takes us to the next article: <strong>Vector Search From First Principles: Navigable Small World Graphs</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6125d53c680e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vector-search-from-first-principles/vector-search-from-first-principles-from-exact-search-to-approximate-nearest-neighbors-6125d53c680e">Vector Search From First Principles: From Exact Search to Approximate Nearest Neighbors</a> was originally published in <a href="https://medium.com/vector-search-from-first-principles">Vector Search From First Principles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>