Vector databases explained: build one in numpy, then measure HNSW and IVF
Build a vector store in numpy, then measure recall@10 and latency for brute force, IVF and HNSW on 100k vectors, plus filtering and when pgvector is enough.
A vector database stores lists of numbers (embeddings) and answers one question fast: which stored vectors are closest to this query vector? Around that core sit the parts that make it a database: metadata you can filter on, inserts and deletes while queries run, persistence, and an index so a query does not have to touch every row.
This post builds the core from scratch in numpy, then shows where brute force stops being enough. The benchmark compares exact search with a hand-written IVF index, FAISS IVF and an HNSW graph (hnswlib) on 100,000 vectors of 384 dimensions, with recall@10 and per-query latency for each setting. It ends with metadata filtering, where silent recall loss is common, and with the cases where you do not need a separate vector database at all.
Choosing an embedding model, chunking and hybrid search are covered in the RAG cheat sheet and the hybrid search and reranking post, so they are skipped here.
Embeddings and distance metrics#
An embedding model maps text (or an image) to a fixed-length vector. all-MiniLM-L6-v2, a common small model, outputs 384 dimensions. Texts with similar meaning land near each other, so "find relevant documents" becomes "find nearby vectors".
"Nearby" needs a metric. Three cover almost every case:
| Metric | Formula | Higher or lower is closer | pgvector operator | hnswlib space |
|---|---|---|---|---|
| Cosine similarity | a·b / (‖a‖‖b‖) | higher | <=> (cosine distance) |
cosine |
| Dot product | a·b | higher | <#> (negative inner product) |
ip |
| Euclidean (L2) | ‖a − b‖ | lower | <-> |
l2 (squared) |
A worked example with a = (3, 4) and b = (4, 3): the dot product is 24, both lengths are 5, so cosine similarity is 24 / 25 = 0.96. Normalize both to length 1 and the squared L2 distance is 2 − 2 × 0.96 = 0.08. On unit vectors, ‖a − b‖² = 2 − 2·cos(a, b), so cosine, dot product and L2 rank results in the same order. Normalize once at insert time and you can use the cheapest operation, a plain dot product.
The metrics disagree when vectors are not normalized. Take c = (30, 40). It points the same way as a, so cosine similarity is 1.0, but a·c = 250 while a·b = 24. A dot-product index will rank c far above b for every query, because it is long, not because it is relevant. Check whether your model's outputs are already unit length, and use the metric the model card names.
A vector store in 60 lines of numpy#
The store below keeps unit-length vectors in one float32 matrix, a parallel list of texts and a list of metadata dicts. Search is one matrix-vector product followed by np.argpartition, which finds the top k in O(n) without sorting all rows (numpy docs).
The embedder sits behind a two-method interface. To keep the example offline and free, HashEmbedder is a stub that hashes words into buckets. It only matches shared words, so it is a lexical stand-in, not a semantic model. The docstring shows where a real model call goes.
import hashlib
import re
from typing import Protocol
import numpy as np
class Embedder(Protocol):
def embed(self, texts: list[str]) -> np.ndarray: ...
class HashEmbedder:
"""Offline stand-in for a real embedding model. It hashes words into
buckets, so it only matches shared words. Swap in a real model here,
e.g. SentenceTransformer("all-MiniLM-L6-v2").encode(texts)."""
def __init__(self, dim: int = 256):
self.dim = dim
def embed(self, texts):
out = np.zeros((len(texts), self.dim), dtype=np.float32)
for i, t in enumerate(texts):
for w in re.findall(r"[a-z]+", t.lower()):
h = int(hashlib.md5(w.encode()).hexdigest(), 16)
out[i, h % self.dim] += 1.0 if (h >> 64) & 1 else -1.0
return out
class TinyVectorStore:
def __init__(self, embedder: Embedder):
self.embedder = embedder
self.vectors = None # (n, d) float32, unit length
self.texts, self.meta = [], []
@staticmethod
def _normalize(x):
norms = np.linalg.norm(x, axis=1, keepdims=True)
return x / np.maximum(norms, 1e-12)
def add(self, texts, metadata):
v = self._normalize(self.embedder.embed(texts))
self.vectors = v if self.vectors is None else np.vstack([self.vectors, v])
self.texts += texts
self.meta += metadata
def search(self, query, k=3, where=None):
q = self._normalize(self.embedder.embed([query]))[0]
scores = self.vectors @ q # cosine, since rows are unit length
if where: # pre-filter: drop rows that fail the filter
mask = np.array([all(m.get(f) == v for f, v in where.items()) for m in self.meta])
scores = np.where(mask, scores, -np.inf)
k = min(k, int(np.isfinite(scores).sum()))
top = np.argpartition(-scores, k - 1)[:k] # O(n), then sort only k items
top = top[np.argsort(-scores[top])]
return [(round(float(scores[i]), 3), self.texts[i], self.meta[i]) for i in top]
if __name__ == "__main__":
store = TinyVectorStore(HashEmbedder())
store.add(
[
"Reset your password from the account settings page.",
"Refunds are processed within five business days.",
"Your password must have at least twelve characters.",
"Export invoices as PDF from the billing page.",
"Passwords for admin accounts expire every ninety days.",
],
[
{"team": "support", "lang": "en"},
{"team": "billing", "lang": "en"},
{"team": "security", "lang": "en"},
{"team": "billing", "lang": "en"},
{"team": "security", "lang": "en"},
],
)
for hit in store.search("how do I reset my password", k=3):
print(hit)
print("-- only team=billing")
for hit in store.search("how do I reset my password", k=3, where={"team": "billing"}):
print(hit)
Output:
(0.289, 'Reset your password from the account settings page.', {'team': 'support', 'lang': 'en'})
(0.144, 'Your password must have at least twelve characters.', {'team': 'security', 'lang': 'en'})
(0.0, 'Refunds are processed within five business days.', {'team': 'billing', 'lang': 'en'})
-- only team=billing
(0.0, 'Refunds are processed within five business days.', {'team': 'billing', 'lang': 'en'})
(0.0, 'Export invoices as PDF from the billing page.', {'team': 'billing', 'lang': 'en'})
Two things show up even in five documents. The stub missed "Passwords for admin accounts expire every ninety days" because "passwords" and "password" hash to different buckets. A real embedding model places those two words close together. And the filtered query returned two billing rows with a score of 0.0: the filter guarantees the rows match team=billing, not that they are relevant. Production code needs a minimum score or a reranker after the filter.
Why brute force runs out#
Exact search reads every vector for every query. At 100,000 × 384 float32 values that is 154 MB of memory and 38.4 million multiply-adds per query. At 10 million rows it is about 15 GB, scanned once per request. Memory bandwidth, not arithmetic, sets the floor.
Approximate nearest neighbor (ANN) indexes trade a little recall for reading far less data. Two families dominate.
IVF (inverted file) HNSW (layered graph)
train k-means -> 256 centroids layer 2: o-----------o
each vector goes in its nearest list |
layer 1: o---o-----o---o
query: score 256 centroids, | \
open the nprobe closest lists, layer 0: o-o-o-o-o-o-o-o-o (all points)
scan only those vectors
query: enter at the top, walk greedily
knob: nprobe (lists scanned) toward the query, drop a layer, repeat;
keep the ef best candidates on layer 0
knobs: M (links per node), ef (search width)
IVF comes from the product quantization work by Jégou, Douze and Schmid and is the IndexIVFFlat family in FAISS. HNSW is from Malkov and Yashunin. pgvector offers both families as its two index types, hnsw and ivfflat.
The benchmark#
The script builds 100,000 vectors of 384 dimensions plus 500 queries. Real embeddings cluster by topic, so the data is a Gaussian mixture around 1,000 random centers, normalized to unit length. Uniform random vectors would be a poor stand-in because they have no structure for an index to exploit. Ground truth is exact brute force; recall@10 is the share of the true top 10 that each method returns.
Each query runs alone on one thread, and latency is the median over the 500 queries, which is closer to what a single user request sees than a batched average.
import os
import time
os.environ.setdefault("OMP_NUM_THREADS", "1")
os.environ.setdefault("VECLIB_MAXIMUM_THREADS", "1")
import faiss
import hnswlib
import numpy as np
N, D, NQ, K = 100_000, 384, 500, 10
rng = np.random.default_rng(0)
def unit(x):
return (x / np.linalg.norm(x, axis=1, keepdims=True)).astype(np.float32)
def clustered(n, centers):
# Real embeddings bunch into topics. Fake that with a Gaussian mixture.
labels = rng.integers(0, len(centers), n)
return unit(centers[labels] + 0.35 * rng.standard_normal((n, D)) / np.sqrt(D) * 4)
centers = unit(rng.standard_normal((1_000, D)))
X = clustered(N, centers)
Q = clustered(NQ, centers)
# Ground truth: exact brute force over all 100k rows.
t = time.perf_counter()
S = Q @ X.T
truth = np.argpartition(-S, K, axis=1)[:, :K]
print(f"brute force, batched {NQ} queries: {(time.perf_counter() - t) * 1000:.0f} ms total")
def recall(found):
return np.mean([len(set(f) & set(g)) / K for f, g in zip(found, truth)])
def per_query_ms(fn):
# Median of single-query timings: closer to what one user request sees.
out, times = [], []
for q in Q:
t = time.perf_counter()
out.append(fn(q))
times.append(time.perf_counter() - t)
return float(np.median(times)) * 1000, out
def brute(q):
s = X @ q
return np.argpartition(-s, K)[:K]
ms, found = per_query_ms(brute)
print(f"brute force numpy recall@10={recall(found):.3f} {ms:.2f} ms/query")
# A from-scratch IVF: k-means the rows into lists, search only the nearest lists.
def kmeans(x, k, iters=10):
c = x[rng.choice(len(x), k, replace=False)]
for _ in range(iters):
a = np.argmax(x @ c.T, axis=1)
for j in range(k):
m = x[a == j]
if len(m):
c[j] = m.mean(0)
c = unit(c)
return c, np.argmax(x @ c.T, axis=1)
t = time.perf_counter()
cent, assign = kmeans(X[:20_000], 256)
assign = np.argmax(X @ cent.T, axis=1)
lists = [np.where(assign == j)[0] for j in range(len(cent))]
print(f"numpy IVF build: {time.perf_counter() - t:.1f} s")
for nprobe in (1, 4, 16):
def ivf(q, nprobe=nprobe):
probe = np.argpartition(-(cent @ q), nprobe)[:nprobe]
ids = np.concatenate([lists[j] for j in probe])
s = X[ids] @ q
return ids[np.argpartition(-s, K)[:K]]
ms, found = per_query_ms(ivf)
print(f"numpy IVF nprobe={nprobe:<3} recall@10={recall(found):.3f} {ms:.2f} ms/query")
# FAISS IVF-Flat, inner product (cosine on unit vectors).
t = time.perf_counter()
quant = faiss.IndexFlatIP(D)
fivf = faiss.IndexIVFFlat(quant, D, 256, faiss.METRIC_INNER_PRODUCT)
fivf.train(X[:20_000]); fivf.add(X)
print(f"faiss IVF build: {time.perf_counter() - t:.1f} s")
faiss.omp_set_num_threads(1)
for nprobe in (1, 4, 16):
fivf.nprobe = nprobe
ms, found = per_query_ms(lambda q: fivf.search(q[None], K)[1][0])
print(f"faiss IVF nprobe={nprobe:<3} recall@10={recall(found):.3f} {ms:.2f} ms/query")
# HNSW graph via hnswlib.
t = time.perf_counter()
h = hnswlib.Index(space="cosine", dim=D)
h.init_index(max_elements=N, M=16, ef_construction=200)
h.add_items(X, np.arange(N), num_threads=8)
print(f"hnswlib build: {time.perf_counter() - t:.1f} s")
for ef in (10, 50, 200):
h.set_ef(ef)
ms, found = per_query_ms(lambda q: h.knn_query(q, k=K, num_threads=1)[0][0])
print(f"hnswlib ef={ef:<4} recall@10={recall(found):.3f} {ms:.2f} ms/query")
# Memory: raw float32 vectors vs the extra graph links.
h.save_index("hnsw.bin")
print(f"hnsw index file: {os.path.getsize('hnsw.bin') / 1e6:.0f} MB")
print(f"raw vectors: {X.nbytes / 1e6:.0f} MB")
# Metadata filtering: 1% of rows belong to tenant 7.
tenant = rng.integers(0, 100, N)
ok = tenant == 7
h.set_ef(50)
post, inside = [], []
for i, q in enumerate(Q[:200]):
s = X @ q
s[~ok] = -np.inf
gt = set(np.argpartition(-s, K)[:K])
ids = h.knn_query(q, k=K, num_threads=1)[0][0] # post-filter: search, then drop
post.append(len(gt & {i for i in ids if ok[i]}) / K)
ids = h.knn_query(q, k=K, filter=lambda i: ok[i], num_threads=1)[0][0] # filter during graph search
inside.append(len(gt & set(ids)) / K)
print(f"filter 1% of rows, post-filter recall@10={np.mean(post):.3f}, in-search filter recall@10={np.mean(inside):.3f}")
Versions: Python 3.15, numpy 2.5.5, faiss-cpu 1.16.0, hnswlib 0.8.0, on an Apple M5 laptop. The machine was running other heavy jobs at the same time, so build times are inflated (HNSW build especially) and absolute latencies will be lower on an idle box. Compare rows against each other, not against your hardware.
brute force, batched 500 queries: 4741 ms total
brute force numpy recall@10=1.000 19.52 ms/query
numpy IVF build: 3.0 s
numpy IVF nprobe=1 recall@10=0.791 0.40 ms/query
numpy IVF nprobe=4 recall@10=0.838 1.49 ms/query
numpy IVF nprobe=16 recall@10=0.898 7.56 ms/query
faiss IVF build: 1.3 s
faiss IVF nprobe=1 recall@10=0.856 0.11 ms/query
faiss IVF nprobe=4 recall@10=0.886 0.33 ms/query
faiss IVF nprobe=16 recall@10=0.928 1.03 ms/query
hnswlib build: 495.7 s
hnswlib ef=10 recall@10=0.779 0.68 ms/query
hnswlib ef=50 recall@10=1.000 1.77 ms/query
hnswlib ef=200 recall@10=1.000 6.14 ms/query
hnsw index file: 168 MB
raw vectors: 154 MB
filter 1% of rows, post-filter recall@10=0.015, in-search filter recall@10=0.963
The same numbers as a table:
| Method | Setting | Recall@10 | ms per query | Build |
|---|---|---|---|---|
| Brute force (numpy) | exact | 1.000 | 19.52 | none |
| IVF from scratch (numpy) | nprobe=1 / 4 / 16 | 0.791 / 0.838 / 0.898 | 0.40 / 1.49 / 7.56 | 3.0 s |
| FAISS IVF-Flat | nprobe=1 / 4 / 16 | 0.856 / 0.886 / 0.928 | 0.11 / 0.33 / 1.03 | 1.3 s |
| hnswlib HNSW, M=16 | ef=10 / 50 / 200 | 0.779 / 1.000 / 1.000 | 0.68 / 1.77 / 6.14 | 495.7 s (loaded machine) |
What the numbers say:
- HNSW at ef=50 matched exact search on this data at about 11× lower latency. At ef=10 it lost a fifth of the true neighbors. The
efknob is the main trade-off you tune at query time, and pgvector's defaulthnsw.ef_searchis 40. - IVF recall stalls below HNSW. With nprobe=16 the search reads about 6% of the vectors (16 of 256 lists) and still misses 7% of true neighbors with FAISS. Neighbors that sit near a list boundary end up in a list the query never opens. IVF builds in seconds and uses less memory, which is why it shows up at very large scale, usually with compression added.
- The hand-written IVF works but is slow. Same algorithm as FAISS, 4 to 7× slower, because it gathers rows into a new array per query and runs Python loops. Write one to learn how IVF works, then use FAISS or your database's index in production.
- HNSW costs memory and build time. The saved index was 168 MB against 154 MB of raw vectors, so the graph links added about 14 MB at M=16. Building a graph is the slow part of HNSW in every engine, so plan bulk loads and re-indexing.
The synthetic data here is friendlier than real embeddings, so treat the 1.000 recall as a property of this dataset. Run the same recall check on a sample of your own vectors and queries before you trust any default setting.
Metadata filtering#
Most real queries carry a filter: this tenant, this language, documents the user may read, posted after a date. The last line of the benchmark tests what happens when only 1% of rows match.
- Post-filter (search the index for the top 10, then drop rows that fail the filter) returned recall@10 of 0.015. Most queries got zero matching rows back, because the 10 nearest vectors almost never belong to the right tenant.
- Filter during search (hnswlib's
filter=callback, which skips non-matching nodes while it walks the graph) returned 0.963.
Post-filtering fails quietly because it does not raise an error. The result list is short or empty and the LLM answers from nothing. The pgvector README gives the same arithmetic: with HNSW and the default ef_search of 40, a filter that matches 10% of rows leaves about 4 rows. Since version 0.8.0 pgvector has iterative index scans (SET hnsw.iterative_scan = strict_order;), which keep scanning until enough rows pass the filter. Qdrant pairs its HNSW index with payload indexes on the fields you filter by, and uses them to estimate how many points a filter matches before it picks a search strategy (indexing docs).
Rules that follow from this:
- Very selective filters (one tenant out of thousands) are often better served by exact search over the filtered rows, using a normal B-tree index on the filter column. pgvector's README recommends the same.
- For multi-tenant apps, give large tenants their own index or partition, so one tenant's vectors do not crowd out another's.
- Log how many results each query returns after filtering. A spike in short result lists is your alert.
When you do not need a vector database#
A separate vector database is one more service to run, back up, secure and keep in sync with your source data. Skip it when you can.
| Situation | What to use |
|---|---|
| Under about 100k vectors, data fits in RAM, read-mostly | numpy or FAISS IndexFlatIP in your app process. 19 ms exact search above, less on an idle machine. |
| You already run Postgres | pgvector. Exact search by default, HNSW or IVFFlat when you need it, and filters, joins and transactions come with Postgres. |
| Prototype or notebook | Chroma's in-memory client, or the numpy store above. |
| Tens of millions of vectors, heavy filtering, many tenants, high QPS | A dedicated engine (Qdrant, Weaviate, Milvus and others), or pgvector with partitioning if the team knows Postgres well. |
pgvector has limits to check before you commit: an indexed vector column takes up to 2,000 dimensions, halfvec up to 4,000, and the README lists binary quantization and subvector indexing for larger models.
Keeping embeddings next to the rows they describe also removes a whole class of bugs: a document deleted in the main database but still returned by the vector store. If you do run a separate store, the sync job is part of the design. The RAG ingestion pipeline post covers that side.
How to test your own setup#
- Take 1,000 to 10,000 real queries, or embed real chunks as stand-in queries.
- Compute exact top-k with brute force. That is your ground truth. The pgvector README suggests the same comparison for monitoring recall.
- Run the ANN index at a few settings (
ef_search20, 40, 100, 200 for HNSW; severalprobesfor IVF) and record recall@10 and p50/p95 latency. - Repeat with your real filters applied. Filtered recall is usually the number that drops.
- Pick the cheapest setting that meets your recall target, then re-run the check after every re-index or model change.
Index recall only tells you whether the index found the vectors brute force would have found. Whether those vectors answer the question is a retrieval-quality problem; the RAG evaluation post covers that layer, and RAG architectures compared covers what to build on top.
Failure modes#
- Metric mismatch. Index built with L2 or dot product on vectors that are not normalized, while the model was trained for cosine. Rankings drift toward long vectors.
- Mixed embedding models. Vectors from two model versions in one index. Distances between them mean nothing, and nothing errors. Store the model name with each vector and re-embed everything on a model change.
- Post-filtering a selective filter. Short or empty result lists, as measured above.
- No score floor. The nearest neighbor of a nonsense query is still returned with a score. Set a minimum similarity from your own data.
- Default index settings at a new scale. An
efthat gave 0.99 recall at 100k rows can give less at 10 million. Re-measure as data grows.
Sources#
- HNSW paper: Malkov and Yashunin, arXiv:1603.09320
- Jégou, Douze, Schmid: Product quantization for nearest neighbor search (IEEE TPAMI)
- FAISS wiki: index types and guidelines to choose an index
- hnswlib on GitHub (spaces,
knn_queryfilter) - pgvector README (operators, dimension limits, filtering, iterative index scans)
- Qdrant docs: indexing and filtering
- Chroma docs
- sentence-transformers/all-MiniLM-L6-v2 model card
- numpy.argpartition