On this page
Suppose your search engine holds 100 million 1,536-dimensional embeddings, and a query arrives with a 15-millisecond latency budget. Exact scan streams 572 GiB of float32 numbers and scores 153.6 billion scalar components for a single request. Yet skipping 99.9% of the corpus risks missing the exact passage the user needed. How can an index ignore almost every vector in and still land in the right neighborhood?
Every modern vector database builds on three ideas: Hierarchical Navigable Small World (HNSW) navigates a multi-layer proximity graph, Inverted File (IVF) partitions space into coarse Voronoi cells and opens only a few, and Product Quantization (PQ) compresses vectors into short byte codes so billions fit in RAM.
The embedding lesson fixed the ranking rule (metric and normalization). A vector index approximates that exact ranking faster and in less memory; it cannot rescue weak embeddings, and its accuracy is always judged against exact search on the same vectors.
The brute-force problem
Exact search (flat search) scores query vector against every stored vector in work. Raw float32 storage alone requires:
Classic k-d trees partition one coordinate axis at a time and prune subtrees via bounding boxes, which works in 2D or 3D but collapses around 20 dimensions.[1] When many coordinates carry independent variance, distance concentration clusters pairwise distances tightly around their mean so bounding boxes overlap almost everywhere (whereas zero-padding 1D points into 768D leaves their true intrinsic distances unchanged).
Approximate nearest-neighbor (ANN) search inspects a tiny candidate subset and scores its accuracy against exact top- with Recall@k:
If exact top-5 is [10, 21, 34, 55, 89], a fast setting returning [10, 21, 8, 13, 5] achieves 40% Recall@5, while a tuned setting returning [10, 21, 34, 55, 3] reaches 80%. Keep ANN recall distinct from relevance recall: an index can hit 100% ANN recall while faithfully reproducing a mediocre embedding model.

HNSW (Hierarchical Navigable Small World)
When your working set fits in RAM and you want low latency without offline clustering, HNSW is usually the first index to try.[3]
Skip-lists generalized to high-dimensional graphs
HNSW generalizes a 1D skip-list to a proximity graph in .[3] Each inserted vector samples its maximum layer from an exponential decay distribution. Setting yields a geometric ladder:
Every vector resides on Layer 0, roughly on Layer 1, on Layer 2, up to height . Upper layers act as sparse express highways; Layer 0 is the dense local road network.
Search runs in two phases:
- Greedy descent on upper layers: From the global entry point on the top layer, hop to any closer neighbor until reaching a local minimum, then drop to the same vector on the next layer below.
- Beam search on Layer 0: A greedy walk on Layer 0 traps in local minima, so Layer 0 expands a beam of width
ef_searchusing two heaps: a min-heapcandidates(closest unexpanded node first) and a max-heapresults(holding at mostef_searchclosest vectors found so far). Pop the closest candidate ; ifresultsis full and is farther than the worst item inresults, stop and return the best items. Otherwise inspect 's unvisited neighbors and push improvements onto both heaps.
ef_search on Layer 0.Why HNSW prefers diverse neighbors over nearest neighbors
Three build parameters shape the graph: M (upper-layer link cap), M0 (Layer-0 cap, normally ), and ef_construction (insertion beam width). Wiring a new node blindly to its closest neighbors creates dense local cliques with poor inter-cluster bridges. HNSW's diversity heuristic (SELECT-NEIGHBORS-HEURISTIC) visits candidates in ascending distance to and keeps candidate only if it is closer to than to every already-selected neighbor :
Skipping candidates hidden right behind existing links forces edges to point outward in fresh directions.[3]
Tracing an insertion and building a working HNSW
Insertion mirrors search: sample top layer , greedily descend layers above , then run beam search of width ef_construction on layers down to , adding reciprocal links and pruning adjacency lists exceeding 2M (Layer 0) or M (upper layers). The global entry point changes only if strictly exceeds the current maximum layer.
This self-contained HNSW (using nearest- pruning for brevity) builds a 2-layer graph and shows why widening ef_search rescues a query whose only path to the true nearest neighbor crosses a farther bridge node:
import heapq
import math
import random
from dataclasses import dataclass, field
def sq_l2(a: tuple[float, ...], b: tuple[float, ...]) -> float:
return sum((x - y) ** 2 for x, y in zip(a, b))
def sample_level(mL: float, rng: random.Random) -> int:
return math.floor(-math.log(max(rng.random(), 1e-12)) * mL)
@dataclass
class MiniHNSW:
M: int = 2
ef_construction: int = 4
vectors: dict[int, tuple[float, ...]] = field(default_factory=dict)
edges: dict[tuple[int, int], list[int]] = field(default_factory=dict)
entry_point: int | None = None
max_level: int = -1
def neighbors(self, node_id: int, level: int) -> list[int]:
return list(self.edges.get((node_id, level), []))
def prune(graph: MiniHNSW, node_id: int, level: int, cap: int) -> None:
linked = graph.edges[(node_id, level)]
if len(linked) > cap:
graph.edges[(node_id, level)] = sorted(
linked, key=lambda other: sq_l2(graph.vectors[node_id], graph.vectors[other])
)[:cap]
def greedy_search(graph: MiniHNSW, query: tuple[float, ...], entry: int, level: int) -> int:
current = entry
while True:
best = min([current, *graph.neighbors(current, level)], key=lambda n: sq_l2(query, graph.vectors[n]))
if best == current:
return current
current = best
def search_layer(graph: MiniHNSW, query: tuple[float, ...], entry: int, level: int, ef: int) -> list[int]:
visited = {entry}
d0 = sq_l2(query, graph.vectors[entry])
candidates, results = [(d0, entry)], [(-d0, entry)] # min-heap & bounded max-heap
while candidates:
dist, current = heapq.heappop(candidates)
if len(results) >= ef and dist > -results[0][0]:
break
for nb in graph.neighbors(current, level):
if nb in visited:
continue
visited.add(nb)
d = sq_l2(query, graph.vectors[nb])
if len(results) < ef or d < -results[0][0]:
heapq.heappush(candidates, (d, nb))
heapq.heappush(results, (-d, nb))
if len(results) > ef:
heapq.heappop(results)
return [node for _, node in sorted((-neg, node) for neg, node in results)]
def insert(graph: MiniHNSW, node_id: int, vector: tuple[float, ...], level: int) -> None:
graph.vectors[node_id] = vector
for layer in range(level + 1):
graph.edges.setdefault((node_id, layer), [])
if graph.entry_point is None:
graph.entry_point, graph.max_level = node_id, level
return
entry = graph.entry_point
for layer in range(graph.max_level, level, -1):
entry = greedy_search(graph, vector, entry, layer)
for layer in range(min(level, graph.max_level), -1, -1):
candidates = search_layer(graph, vector, entry, layer, graph.ef_construction)
chosen = sorted(candidates, key=lambda i: sq_l2(vector, graph.vectors[i]))[: graph.M]
cap = 2 * graph.M if layer == 0 else graph.M
for nb in chosen:
if nb != node_id:
if nb not in graph.edges[(node_id, layer)]:
graph.edges[(node_id, layer)].append(nb)
graph.edges.setdefault((nb, layer), [])
if node_id not in graph.edges[(nb, layer)]:
graph.edges[(nb, layer)].append(node_id)
prune(graph, nb, layer, cap)
prune(graph, node_id, layer, cap)
entry = min(candidates, key=lambda i: sq_l2(vector, graph.vectors[i]))
if level > graph.max_level:
graph.entry_point, graph.max_level = node_id, level
def search(graph: MiniHNSW, query: tuple[float, ...], k: int = 2, ef_search: int = 4) -> list[int]:
if ef_search < k:
raise ValueError("ef_search must be at least k")
current = graph.entry_point
assert current is not None
for layer in range(graph.max_level, 0, -1):
current = greedy_search(graph, query, current, layer)
return search_layer(graph, query, current, 0, ef_search)[:k]
rng = random.Random(0)
mL = 1 / math.log(16)
draws, level = 0, 0
while level == 0:
level = sample_level(mL, rng)
draws += 1
print(f"mL for M=16: {mL:.3f}, P(level >= 1) = {1/16:.1%}, first upper draw after {draws} samples")
graph = MiniHNSW()
for node_id, vec, lvl in [
(0, (0.0, 0.0), 1), (1, (0.2, 0.1), 0), (2, (0.3, 0.0), 1),
(3, (5.0, 5.0), 0), (4, (5.1, 4.8), 0), (5, (0.1, 0.3), 0),
]:
insert(graph, node_id, vec, lvl)
q = (0.25, 0.05)
print("HNSW top-2: ", search(graph, q, k=2, ef_search=4))
print("Exact top-2:", sorted(graph.vectors, key=lambda i: sq_l2(q, graph.vectors[i]))[:2])
# Bridge test: node 1 is farther than entry 0, yet it is the only path to node 2.
bridge = MiniHNSW(
vectors={0: (0.9, 0.0), 1: (2.0, 0.0), 2: (0.1, 0.0)},
edges={(0, 0): [1], (1, 0): [2], (2, 0): []},
entry_point=0, max_level=0,
)
print("bridge ef=1:", search(bridge, (0.0, 0.0), k=1, ef_search=1))
print("bridge ef=3:", search(bridge, (0.0, 0.0), k=1, ef_search=3))mL for M=16: 0.361, P(level >= 1) = 6.2%, first upper draw after 36 samples
HNSW top-2: [1, 2]
Exact top-2: [1, 2]
bridge ef=1: [0]
bridge ef=3: [2]With ef_search = 1, node 1 is farther than entry 0 so the beam stops immediately and misses node 2; raising ef_search to 3 crosses the bridge. Always keep ef_search >= k (results holds at most ef_search items, and engines like hnswlib reject ef < k).[4][2]
Key HNSW knobs and memory budget
| Parameter | Role | Starting value | Trade-off |
|---|---|---|---|
M | Upper-layer link cap per node | 16 | Higher M boosts recall at extra RAM and build time. |
M0 | Layer-0 adjacency cap | 2 * M | Denser base layer improves local routing. |
ef_construction | Build-time beam width | 200 | Cleaner graph at slower indexing speed. |
ef_search | Query-time beam width (>= k) | 64 (for k=10) | Tunable per query without rebuilding; higher raises recall and latency. |
mL | Layer-sampling scale | Controls upper-layer density. |
At high float32 dimensions, raw vectors dominate RAM rather than graph links: for and , each vector takes bytes while 4-byte Layer-0 neighbor IDs take only bytes (98.0% vector, 2.0% Layer-0 links). Links become a large share only after compression or at low dimensions. Tune ef_search at query time by sweeping recall against p95 latency and choosing the fastest setting that clears your floor (for example, choosing ef_search = 48 at 0.97 recall and 6.8 ms p95 over ef_search = 24 at 0.91 recall or 96 at 12.4 ms against a 0.96 recall / 10 ms target).
Graph traversal shines in RAM, yet it still requires adjacency lists and lacks a fixed scan fraction. Partitioning space into cells solves both.
IVF (Inverted File Index)
IVF replaces graph links with coarse geometric partitions. Offline k-means learns cluster centroids (the coarse quantizer), dividing into Voronoi cells:
Each indexed vector appends to its nearest centroid's inverted list. A query scores all nlist centroids, picks the closest nprobe cells, and scans only those lists.[5][6] With 1 million vectors, nlist = 1,024, and nprobe = 5, balanced IVF scores centroids plus list vectors ( total comparisons, 169x less work than brute force).
Why nprobe = 1 misses neighbors across cell edges
When a query lands near the dividing plane between two Voronoi cells, its true nearest neighbor can sit just across the line in the neighboring cell. Raising nprobe opens adjacent cells and recovers it:

q = (4.9, 0) falls on the List 0 side of the Voronoi dividing line x = 5. Probing List 0 alone misses v3 = (5.4, 0) (distance 0.50); probing both lists recovers the exact top-2.def sq_l2(a: tuple[float, ...], b: tuple[float, ...]) -> float:
return sum((x - y) ** 2 for x, y in zip(a, b))
centroids = {0: (0.0, 0.0), 1: (10.0, 0.0)}
vectors = {0: (0.2, 0.1), 1: (0.4, -0.1), 2: (4.6, 0.0), 3: (5.4, 0.0), 4: (9.8, 0.2)}
lists: dict[int, list[int]] = {0: [], 1: []}
for vid, vec in vectors.items():
lists[min(centroids, key=lambda c: sq_l2(vec, centroids[c]))].append(vid)
def ivf_search(query: tuple[float, ...], nprobe: int, k: int = 2) -> list[int]:
probed = sorted(centroids, key=lambda c: sq_l2(query, centroids[c]))[:nprobe]
scored = [(sq_l2(query, vectors[vid]), vid) for cid in probed for vid in lists[cid]]
return [vid for _, vid in sorted(scored)[:k]]
query = (4.9, 0.0)
print("inverted lists:", lists)
print("exact top-2: ", sorted(vectors, key=lambda vid: sq_l2(query, vectors[vid]))[:2])
print("nprobe=1: ", ivf_search(query, nprobe=1))
print("nprobe=2: ", ivf_search(query, nprobe=2))inverted lists: {0: [0, 1, 2], 1: [3, 4]}
exact top-2: [2, 3]
nprobe=1: [2, 1]
nprobe=2: [2, 3]With balanced lists, IVF scans roughly nprobe / nlist of the corpus. In IVF-Flat, probing all nlist cells recovers exact search; in IVF-PQ, quantization error remains even at full scan.
Distance metrics and centroid geometry
Every index ranks under one metric: squared L2, Inner Product (IP) (), or Cosine similarity (L2-normalize stored vectors and queries, then run IP).[7] On unit vectors, L2 and IP induce identical rankings because :
import numpy as np
vectors = np.array([[3.0, 0.0], [1.0, 1.0], [0.0, 2.0]])
query = np.array([1.0, 0.8])
unit_v = vectors / np.linalg.norm(vectors, axis=1, keepdims=True)
unit_q = query / np.linalg.norm(query)
print("IP rank on unit vectors:", np.argsort(-(unit_v @ unit_q)).tolist())
print("L2 rank on unit vectors:", np.argsort(np.sum((unit_v - unit_q) ** 2, axis=1)).tolist())IP rank on unit vectors: [1, 0, 2]
L2 rank on unit vectors: [1, 0, 2]HNSW vs. IVF-Flat at a glance
| Feature | HNSW | IVF-Flat |
|---|---|---|
| Structure | Multi-layer proximity graph | Coarse centroids + inverted lists |
| Offline training | None | Required (-means centroids) |
| Memory | Raw vectors + ~ Layer-0 IDs | Raw vectors + IDs (no graph edges) |
| Updates & drift | Incremental inserts; deletes vary by engine | Easy inserts; distribution drift stales centroids |
| Main query knob | ef_search | nprobe |
| Best fit | Low-latency, high-recall in-RAM search | Predictable scan fraction or base for PQ |
Graph search and compression are orthogonal (IndexHNSWFlat, IndexHNSWSQ, IndexHNSWPQ, IndexIVFPQ in Faiss).[6] Yet raw float32 vectors still break RAM at billion scale: . Fitting a billion vectors into RAM requires shrinking each vector.
Product Quantization (PQ)
Product Quantization (PQ) splits a -dimensional vector into disjoint subvectors () and runs -means independently on each subspace to learn a codebook of centroids.[8] Because , each centroid ID fits in one uint8 byte:
For and (), a 3,072-byte float32 vector shrinks to 96 bytes (32x code-only compression; adding an 8-byte ID gives 104 bytes per record). The 96 shared codebooks use only globally while spanning reconstructed points. In L2 IVF-PQ, PQ normally encodes the residual around each coarse centroid so residuals cluster near zero and quantize more accurately.[9] Optimized Product Quantization (OPQ) learns an orthogonal rotation jointly with the codebooks to balance variance across subspaces while preserving L2 distance (OPQ96,IVF4096,PQ96).[10][11]

Asymmetric Distance Computation (ADC)
At query time, Asymmetric Distance Computation (ADC) leaves the query uncompressed and never reconstructs stored vectors. Slice , precompute one cache-resident lookup table (96 KiB for ), and score any code with indexed additions:[9]
The script below implements ADC and shows code collision: two distinct vectors sharing one PQ code cannot be ordered until you overfetch and rerank against full-precision originals.
import numpy as np
def adc_search(query: np.ndarray, codes: np.ndarray, codebooks: np.ndarray, k: int = 2) -> list[int]:
m, _, d_sub = codebooks.shape
q_subs = query.reshape(m, d_sub)
tables = np.sum((codebooks - q_subs[:, None, :]) ** 2, axis=2) # (m, K*) lookup table
dists = np.sum(tables[np.arange(m), codes], axis=1) # m additions per code
return sorted(range(len(codes)), key=lambda i: (float(dists[i]), i))[:k]
raw_bytes, code_bytes = 768 * 4, 96
print(f"768D float32: {raw_bytes} B -> PQ96: {code_bytes} B ({raw_bytes // code_bytes}x), +8B ID = {code_bytes + 8} B")
codebooks = np.array([
[[0.0, 0.0], [2.0, 0.0], [0.0, 2.0], [2.0, 2.0]],
[[0.0, 0.0], [2.0, 0.0], [0.0, 2.0], [2.0, 2.0]],
])
codes = np.array([[0, 0], [1, 0], [0, 1], [1, 1]])
print("ADC top-2 for origin:", adc_search(np.array([0.0, 0.0, 0.0, 0.0]), codes, codebooks, k=2))
# Code collision: two originals quantize to [0, 0]; overfetch + exact rerank fixes top-1.
q = np.array([0.9, 0.0, 0.0, 0.0])
originals = np.array([[0.1, 0.0, 0.0, 0.0], [0.9, 0.0, 0.0, 0.0]])
same_codes = np.array([[0, 0], [0, 0]])
compressed_top1 = adc_search(q, same_codes, codebooks, k=1)
overfetched = adc_search(q, same_codes, codebooks, k=2)
reranked_top1 = sorted(overfetched, key=lambda i: float(np.sum((q - originals[i]) ** 2)))[:1]
print(f"collision top-1 without overfetch: {compressed_top1} | after overfetch+rerank: {reranked_top1}")768D float32: 3072 B -> PQ96: 96 B (32x), +8B ID = 104 B
ADC top-2 for origin: [0, 1]
collision top-1 without overfetch: [0] | after overfetch+rerank: [1]What work does Asymmetric Distance Computation (ADC) move out of the per-vector scoring loop?
Answer
ADC precomputes a small lookup table of distances between the uncompressed query subvectors and every subspace centroid once per query, reducing each candidate's score to m table lookups and additions instead of full-vector decompression and coordinate math.
Filtered search
Real retrieval filters by tenant, region, or date (region = 'EU'). Three strategies behave very differently under selective filters:
- Pre-filter then exact scan: Resolve metadata first via B-tree or bitmap, then run flat search on the matching rows. Fast and exact when only a few thousand rows match; too slow when millions match (and stripping disallowed nodes from an HNSW graph beforehand can disconnect it).
- Post-filtering: Fetch an unfiltered buffer of ANN candidates, then discard non-matches. With selectivity and , expected matches are , and the probability of zero results is under independence (or when nearby vectors share excluded metadata).
- Filter-aware traversal and iterative scans: pgvector expands iterative ANN scans (
hnsw.max_scan_tuples,ivfflat.max_probes) until matches are collected or a scan cap hits.[2] Weaviate sweeps across disallowed nodes without returning them and supports ACORN traversal, skipping distance computation on non-matches with multi-hop jumps from eligible entry points.[12][13]
L, s = 100, 0.005
print(f"expected matches: {L * s:.2f}")
print(f"independent empty probability: {(1 - s) ** L:.1%}")
print(f"correlated empty probability: {1 - s:.1%}")
candidates = ["eu-1", "us-1", "us-2", "us-3", "eu-2"]
region = {"eu-1": "eu", "us-1": "us", "us-2": "us", "us-3": "us", "eu-2": "eu"}
def post_filter(pool: list[str], target: str, k: int) -> list[str]:
return [doc for doc in pool if region[doc] == target][:k]
print("buffer L=3:", post_filter(candidates[:3], "eu", k=2))
print("buffer L=5:", post_filter(candidates, "eu", k=2))expected matches: 0.50
independent empty probability: 60.6%
correlated empty probability: 99.5%
buffer L=3: ['eu-1']
buffer L=5: ['eu-1', 'eu-2']
Scaling to billions and choosing an index
Beyond single-machine RAM, three architectures dominate:
- IVF-PQ in RAM: Faiss's
IndexIVFPQstoresceil(m_pq * nbits / 8) + 8bytes per vector (code + 64-bit ID): ~40 GB for 1B vectors at 32-byte codes, or ~104 GB at 96-byte codes.[6] - SSD-backed graphs (DiskANN): Keeps a compact compressed index in RAM and stores full vectors and adjacency lists on NVMe SSD to minimize random reads, achieving >5,000 QPS at <3 ms mean latency and 95%+ 1-recall@1 on SIFT1B on one 16-core, 64 GB RAM + SSD machine.[14]
- Horizontal sharding (scatter-gather): Partition the corpus across disjoint shards, query all shards, and merge local top- lists on comparable scores. When every shard runs exact search with consistent tie-breaking and all shards respond, the candidates are guaranteed to contain the exact global top- (any omitted item already trails items on its own shard); dropping a slow shard or using approximate per-shard search breaks that guarantee.

Full fan-out amplifies tail latency (). If each shard independently clears its threshold with probability , all shards clear it with probability : 96.1% across 4 shards, dropping to 81.8% across 20 shards (where cluster p99 is driven by the single-shard percentile). Use replica hedging or per-shard deadlines with explicit partial-result flags to rein in tails.
Index family comparison
| Index family | Core mechanism | Strength | Main cost | Reach for it when |
|---|---|---|---|---|
| HNSW | Hierarchical proximity graph | Fast, high-recall in-RAM search | Raw-vector RAM, build time, deletes | Vectors fit in RAM and low latency matters |
| IVF-Flat | Coarse Voronoi cells + exact list scan | Predictable scan fraction | Offline training, raw-vector RAM | You want fixed scan budgets without graph edges |
| IVF-PQ | IVF + subspace byte codes + ADC | ~10x-32x smaller footprint | Quantization error, rerank tuning | RAM capacity is the primary bottleneck |
| DiskANN | SSD-resident graph + compact RAM guide | Billion-scale on one NVMe node | Storage-layout and I/O engineering | Corpus exceeds RAM but single-node SSD fits |
When evaluating any vector engine, check four fundamentals: which ANN families it exposes, how it executes filtered search, where the index lives (RAM, NVMe, object storage), and what compression plus full-precision reranking knobs it supports.
When vector indexes break
| Symptom | Likely root cause | Concrete fix |
|---|---|---|
| IVF recall drops over months | Embedding distribution drifted from stale centroids | Retrain centroids on recent data and rebuild lists |
| HNSW exhausts RAM | Float32 vectors + links + allocator overhead exceed memory | Measure bytes/vector; adopt SQ, PQ, or IVF-PQ |
| Fast queries miss obvious matches | Too-small ef_search / nprobe, PQ error, or metric mismatch | Check exact baseline first; separate recall from reranking |
| Cosine switch tanks IVF recall | Centroids trained on unnormalized L2 vectors | Normalize all vectors and retrain centroids for IP |
| Deleted docs still appear | Tombstones, dead tuples, or lagging replicas | Test delete visibility; run compaction or index rebuild |
| Adding shards spikes p99 | Full fan-out waits on slowest shard | Prune shard routing, hedge requests, or cap shard deadlines |
Hands-on: metric migration and deletion in Faiss
Run this self-contained Faiss script with uv run vector-index-replay.py to see metric geometry and deletion behavior directly.[6][7] Under raw L2, [1, 1] beats [10, 0] for query [1, 0.1]; after L2 normalization and inner-product indexing, [10, 0] aligns along the query and wins. Removing ID 101 leaves Faiss's -1 sentinel in the unfilled second slot:
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = ["faiss-cpu==1.15.1", "numpy==2.4.3"]
# ///
import faiss
import numpy as np
faiss.omp_set_num_threads(1)vectors = np.array([[10.0, 0.0], [1.0, 1.0]], dtype="float32")
ids = np.array([101, 202], dtype="int64")
query = np.array([[1.0, 0.1]], dtype="float32")
raw_l2 = faiss.IndexIDMap2(faiss.IndexFlatL2(2))
raw_l2.add_with_ids(vectors, ids)
_, raw_ids = raw_l2.search(query, 1)
unit_vectors, unit_query = vectors.copy(), query.copy()
faiss.normalize_L2(unit_vectors)
faiss.normalize_L2(unit_query)
cosine = faiss.IndexIDMap2(faiss.IndexFlatIP(2))
cosine.add_with_ids(unit_vectors, ids)
_, cosine_ids = cosine.search(unit_query, 1)
removed = cosine.remove_ids(np.array([101], dtype="int64"))
_, after_delete = cosine.search(unit_query, 2)
print("Raw L2 winner:", int(raw_ids[0, 0]))
print("Cosine winner after rebuilding:", int(cosine_ids[0, 0]))
print("Removed records:", removed)
print("Results after delete:", after_delete[0].tolist())Raw L2 winner: 202
Cosine winner after rebuilding: 101
Removed records: 1
Results after delete: [202, -1]Check for -1 sentinels when fewer than k matches exist, propagate deletes across replicas before cutover, and benchmark ef_search or nprobe against an exact top- baseline under real queries and metadata filters.