Approximate Search
Speed versus exactness.
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.

- 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.
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%}")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.
| key | value |
|---|---|
| Thousands | exact is fine |
| Millions | use approximate |
| HNSW | graph of neighbours |
| Trade-off | tiny 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