AI Hints
Home›RAG Tutorial›Scaling Search
RAG · Lesson 37 of 120

Approximate Search

Speed versus exactness.

⏱ 2 min read▶ Video at 37:14🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Comparing a question with every vector is exact, but slow for millions of vectors. Approximate search builds a smart structure, so it only checks the most promising vectors. It's much faster, and almost always finds the same results.

Approximate Search
From the video: Approximate Search
  • Exact is slow at scale
  • Check only promising vectors
  • Much faster

Flat versus HNSW

We make two hundred thousand vectors, grouped in clusters like real embeddings. The flat index checks them all. HNSW builds a graph of neighbours, and walks it. We time a hundred searches on each, and check how often they agree. Run it. HNSW is many times faster, and finds the same top result.

approx.pypython
import time, faiss, numpy as np

rng = np.random.default_rng(0)
centers = rng.normal(size=(1000, 64))
data = (centers[rng.integers(0, 1000, 200_000)] + 0.3 * rng.normal(size=(200_000, 64))).astype("float32")
queries = data[rng.integers(0, 200_000, 100)] + 0.05

flat = faiss.IndexFlatL2(64); flat.add(data)
hnsw = faiss.IndexHNSWFlat(64, 32); hnsw.add(data); hnsw.hnsw.efSearch = 64

for name, index in [("flat", flat), ("hnsw", hnsw)]:
    start = time.perf_counter(); _, ids = index.search(queries, 1)
    print(f"{name}: {(time.perf_counter() - start) * 1000:.0f} ms")
    if name == "flat": exact = ids
print("same top result:", f"{(ids == exact).mean():.0%}")
Output
flat: 61 ms
hnsw: 3 ms
same top result: 100%

When it matters

For a few thousand chunks, exact search is fast enough. Approximate indexes, like HNSW, matter when you reach hundreds of thousands, or millions. Most vector databases use HNSW by default.

keyvalue
Thousandsexact is fine
Millionsuse approximate
HNSWgraph of neighbours
Trade-offtiny accuracy loss

Summary

Approximate search, like HNSW, is far faster at scale, and nearly as accurate. Next, updating the index.

Key takeaways
  • IndexFlat: exact
  • HNSW: fast
  • Almost the same results
Next up: Updating the Index — add and remove