Vector Index Types: Flat, IVF, HNSW and PQ

How approximate nearest neighbour indexes trade recall for speed and memory.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 6 · Lesson 9 of 13 · Intermediate

Vector Index Types: Flat, IVF, HNSW and PQ

How approximate nearest neighbour indexes trade recall for speed and memory.

Comparing a query with every stored vector (exact or "flat" search) is accurate but gets slow as the collection grows: 10 million vectors means 10 million dot products per query. Approximate nearest neighbour (ANN) indexes find almost the same results while looking at a small fraction of the vectors. This lesson explains the main index types and the settings that trade speed for accuracy.

Recall: measuring "approximate"

ANN quality is measured by recall@k: the fraction of the true top-k neighbours (from an exact search) that the ANN index also returns. A recall of 0.95 means 95% of the true nearest neighbours were found. Every index has settings that increase recall at the cost of speed or memory.

Flat (exact) index

Stores the raw vectors and compares the query with all of them. 100% recall, no training, no tuning. On a modern CPU it handles roughly up to a few hundred thousand vectors with acceptable latency. Always start here and move on only when it is too slow.

IVF: inverted file index

IVF clusters the vectors into nlist groups with k-means. At query time it finds the nprobe clusters whose centres are closest to the query and searches only inside them.

  • nlist: number of clusters, often around the square root of the number of vectors.
  • nprobe: clusters searched per query. Higher means better recall and slower search.

IVF needs a training step on a representative sample, and its recall drops if the data distribution later shifts.

HNSW: hierarchical navigable small world graphs

HNSW is the most widely used ANN index in vector databases today. It builds a multi-layer graph in which each vector is linked to its near neighbours. Upper layers contain few vectors with long links, for coarse navigation; the bottom layer contains all vectors. A search starts at the top, greedily moves towards the query, and descends layer by layer.

Three graph layers; the search starts at the top layer entry point, moves towards the query, and drops down to layer 0 to find the nearest neighbour.
Figure 1. HNSW search moves greedily through sparse upper layers, then refines in the dense bottom layer.
  • M: links per node (typically 16 to 64). Higher gives better recall and uses more memory.
  • efConstruction: search breadth while building. Higher gives a better graph and slower builds.
  • efSearch: search breadth at query time, the main speed/recall dial. It must be at least k.

HNSW gives excellent recall and speed without training and supports incremental inserts. Its main cost is memory: the graph links come on top of the vectors.

PQ: product quantization

Product quantization compresses vectors. Each vector is cut into m sub-vectors, and each sub-vector is replaced by the ID of its nearest centroid from a small learned codebook. A 384-dimension float vector (1,536 bytes) can be stored in 48 bytes. Distances are computed approximately from the codes. PQ is usually combined with IVF (IVF-PQ) for billion-scale collections, with an optional re-ranking step on full vectors.

Disk-based indexes

When vectors do not fit in RAM, disk-based graph indexes such as DiskANN keep compressed vectors in memory and the full graph and vectors on SSD. Several databases (Milvus, Qdrant with on-disk storage, pgvectorscale, Azure services) use this approach.

Try them in FAISS

import time
import faiss
import numpy as np

d, n = 384, 200_000
rng = np.random.default_rng(0)
data = rng.standard_normal((n, d)).astype("float32")
data /= np.linalg.norm(data, axis=1, keepdims=True)
queries = data[rng.choice(n, 200, replace=False)] + 0.05 * rng.standard_normal((200, d)).astype("float32")
k = 10

def evaluate(index, name):
    start = time.perf_counter()
    _, found = index.search(queries, k)
    ms = (time.perf_counter() - start) / len(queries) * 1000
    recall = np.mean([len(set(f) & set(t)) / k for f, t in zip(found, truth)])
    print(f"{name:28} recall@{k}={recall:.3f}  {ms:.2f} ms/query")

flat = faiss.IndexFlatIP(d)
flat.add(data)
_, truth = flat.search(queries, k)          # ground truth from exact search
evaluate(flat, "Flat (exact)")

hnsw = faiss.IndexHNSWFlat(d, 32, faiss.METRIC_INNER_PRODUCT)
hnsw.hnsw.efConstruction = 100
hnsw.add(data)
for ef in (16, 64, 256):
    hnsw.hnsw.efSearch = ef
    evaluate(hnsw, f"HNSW M=32 efSearch={ef}")

nlist = 1024
ivf = faiss.IndexIVFFlat(faiss.IndexFlatIP(d), d, nlist, faiss.METRIC_INNER_PRODUCT)
ivf.train(data)
ivf.add(data)
for nprobe in (4, 16, 64):
    ivf.nprobe = nprobe
    evaluate(ivf, f"IVF nlist={nlist} nprobe={nprobe}")

ivfpq = faiss.IndexIVFPQ(faiss.IndexFlatIP(d), d, nlist, 48, 8, faiss.METRIC_INNER_PRODUCT)
ivfpq.train(data)
ivfpq.add(data)
ivfpq.nprobe = 16
evaluate(ivfpq, "IVF-PQ m=48 nprobe=16")

Random vectors are a harder case than real embeddings (which cluster naturally), so expect better recall on your own data. The pattern is what matters: each index has a dial that trades latency for recall.

Choosing an index

Collection sizeRecommended
Up to ~100,000 vectorsFlat (exact). Simple and fast enough.
100,000 to tens of millions, fits in RAMHNSW, the default in most vector databases.
Memory-constrained or hundreds of millionsHNSW with quantization, IVF-PQ, or a disk-based index.
BillionsIVF-PQ or DiskANN, sharded across machines.
Tip

In RAG, a small loss of ANN recall rarely matters, because retrieval returns several chunks and a reranker often re-sorts them. But measure it: with heavy metadata filtering, some HNSW implementations lose recall sharply.

Key takeaways

  • ANN indexes trade a little recall for large speed gains; measure recall@k against exact search.
  • Flat is exact and fine for small collections. HNSW is the default for most workloads.
  • IVF searches a few clusters (tune nprobe); PQ compresses vectors for very large collections.
  • Tune efSearch (HNSW) or nprobe (IVF) to hit your recall and latency targets.