Lesson 3 of 9 · Concepts
Indexes: HNSW and IVF
How vector indexes work: IVF searches the closest clusters, HNSW walks a graph of neighbours. See both in Python, tune n_probe, M and ef_search, and quantize.
- 9 min read
- Intermediate
- Reviewed
- Explain how an IVF index narrows a search to a few clusters
- Explain how an HNSW index finds neighbours by walking a graph
- Tune the main settings: n_probe for IVF, and M and ef_search for HNSW
- Describe how quantization trades accuracy for memory
What an index does
Two ideas power most vector databases: IVF (search a few groups) and HNSW (follow a graph). Both are approximate, and both have settings that move you along the speed–recall trade-off.
IVF: search only the nearest groups
Think of a library: books are grouped by subject, and you only walk to the two or three shelves closest to what you want. Building the index uses k-means, the clustering method from the Embeddings course.
import heapq
import random
random.seed(3)
DIMS, N, TOPICS = 8, 1500, 15
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def sq_dist(a, b):
return sum((x - y) ** 2 for x, y in zip(a, b))
# Real embeddings are clumpy: texts on the same topic sit close together.
centres = [[random.uniform(-1, 1) for _ in range(DIMS)] for _ in range(TOPICS)]
vectors = []
for i in range(N):
c = centres[i % TOPICS]
vectors.append([x + random.uniform(-0.3, 0.3) for x in c])
# ---- Build an IVF index: k-means puts every vector in one of n_lists lists ----
n_lists = 15
centroids = random.sample(vectors, n_lists)
for _ in range(5): # a few rounds of k-means
lists = [[] for _ in range(n_lists)]
for i, v in enumerate(vectors):
nearest = min(range(n_lists), key=lambda c: sq_dist(v, centroids[c]))
lists[nearest].append(i)
for c in range(n_lists):
if lists[c]:
members = [vectors[i] for i in lists[c]]
centroids[c] = [sum(col) / len(members) for col in zip(*members)]
# ---- Search: only look inside the n_probe lists whose centroids are closest ----
def ivf_search(query, n_probe, k=5):
closest_lists = heapq.nsmallest(n_probe, range(n_lists), key=lambda c: sq_dist(query, centroids[c]))
candidates = [i for c in closest_lists for i in lists[c]]
best = heapq.nsmallest(k, candidates, key=lambda i: sq_dist(query, vectors[i]))
return best, len(candidates) + n_lists # vectors compared + centroids compared
def exact_search(query, k=5):
return heapq.nsmallest(k, range(N), key=lambda i: sq_dist(query, vectors[i]))
queries = [[x + random.uniform(-0.4, 0.4) for x in random.choice(centres)] for _ in range(30)]
for n_probe in [1, 2, 4]:
found = work = 0
for q in queries:
approx, compared = ivf_search(q, n_probe)
found += len(set(approx) & set(exact_search(q)))
work += compared
print(f"n_probe={n_probe}: compared {work // len(queries):>4} of {N} vectors, recall@5 = {found / (5 * len(queries)):.0%}")With n_probe = 1, the search compared about a tenth of the vectors and still found 90% of the true neighbours. Probing two lists brought recall close to 100%. A neighbour is missed when it sits just over the border in a neighbouring list, which is why probing more lists helps.
| IVF setting | What it controls | Raise it to |
|---|---|---|
| n_lists (also called nlist or lists) | How many groups the vectors are split into | Make each list smaller (faster searches) |
| n_probe (also called probes) | How many lists each search looks inside | Raise recall (slower searches) |
A common starting point is a number of lists around the square root of the number of vectors, then tune n_probe while measuring recall.
HNSW: walk a graph of neighbours
Here is a single layer of that idea in Python: 800 points, each linked to its 6 nearest neighbours plus one random long link.
import heapq
import random
random.seed(11)
N = 800
points = [(random.uniform(0, 100), random.uniform(0, 100)) for _ in range(N)]
def dist(a, b):
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
# ---- Build a graph: link every point to its 6 nearest neighbours,
# plus 1 random long-distance link (the "small world" shortcut) ----
links = []
for i, p in enumerate(points):
nearest = heapq.nsmallest(7, range(N), key=lambda j: dist(p, points[j]))[1:]
links.append(nearest + [random.randrange(N)])
# ---- Greedy search: hop to whichever neighbour is closer to the query ----
def graph_search(query, entry=0, ef=8):
computed = 1
visited = {entry}
d = dist(query, points[entry])
candidates = [(d, entry)] # points still to explore, closest first
best = [(-d, entry)] # the ef closest points found so far
while candidates:
d, node = heapq.heappop(candidates)
if d > -best[0][0] and len(best) >= ef:
break # nothing left that could improve the results
for nb in links[node]:
if nb in visited:
continue
visited.add(nb)
computed += 1
dn = dist(query, points[nb])
if len(best) < ef or dn < -best[0][0]:
heapq.heappush(candidates, (dn, nb))
heapq.heappush(best, (-dn, nb))
if len(best) > ef:
heapq.heappop(best)
nearest = max(best)[1]
return nearest, computed
hits = work = 0
tests = 50
for _ in range(tests):
q = (random.uniform(0, 100), random.uniform(0, 100))
found, computed = graph_search(q)
true_nearest = min(range(N), key=lambda j: dist(q, points[j]))
hits += found == true_nearest
work += computed
print(f"Found the true nearest point in {hits} of {tests} searches")
print(f"Average distances computed: {work // tests} (brute force: {N})")About 61 distance calculations instead of 800, and the true nearest point was found in 48 of 50 searches. The search keeps a short list of the best points found so far (ef in the code), which stops it getting stuck in a dead end. Real HNSW adds layers on top: a few points with long links on the top layer, more points on each layer below, like taking a motorway, then main roads, then side streets.
| HNSW setting | What it controls | Raise it to |
|---|---|---|
| M | Links per vector | Raise recall, at the cost of memory and build time |
| ef_construction | How hard the build searches for good links | Build a better graph (slower to build) |
| ef_search (or ef) | How many candidates a search keeps | Raise recall (slower searches) |
Which one is used where?
| HNSW | IVF | |
|---|---|---|
| Speed and recall | Excellent; the usual default | Good; depends on n_probe |
| Memory | Higher (stores the graph) | Lower |
| Build | Can add vectors one at a time | Needs representative data first to find centroids |
| Seen in | Most vector databases, including Chroma, Qdrant and pgvector | pgvector (ivfflat), FAISS, Milvus |
Common mistakes
Do the first step of an IVF search by hand: pick the one list (n_probe = 1) whose centroid is nearest to the query, and show which items would be compared.
centroids = {"travel": (8, 2), "food": (2, 8), "tech": (-6, -5)}
lists = {
"travel": ["flights", "hotels", "trains"],
"food": ["pasta", "curry"],
"tech": ["laptops", "wifi", "phones", "apps"],
}
query = (6, 4)
# IVF search with n_probe = 1:
# find the list whose centroid is closest to the query, then print
# Search list: <name>
# Compare with: <items separated by commas>
Searches with an HNSW index are fast but miss some true neighbours. Which change raises recall at query time?
Summary
- A vector index finds near neighbours without comparing against every vector.
- IVF clusters vectors into lists and searches only the n_probe closest lists.
- HNSW links vectors into a layered graph and walks towards the query; M and ef_search tune it.
- Quantization compresses vectors to save memory, usually followed by re-scoring the top candidates.
- Tune any index by measuring recall on real queries.
Next: combining similarity search with filters such as language, date or user.
Finished reading? Tick it off to track your progress.