Level 2 Agentic Coding · Building with AI
Vector Databases
How to search millions of embeddings in milliseconds. Approximate nearest-neighbour indexes such as IVF and HNSW trade a little accuracy for huge speed-ups, and vector databases add storage, updates and metadata filters. Includes pgvector and Chroma, and when you don't need any of it.
- Level
- ●●●●● Intermediate
- Reading
- 14 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 8 concepts →
- Quiz
- 5 questions ↓
Read first
Embeddings and Semantic SearchThis leads to
Advanced RAGThe full path from zero — 8 concepts before this one
- What Is AI?
- Vectors
- Python for AI
- How Machines Learn
- Dot Product, Norms and Similarity
- Large Language Models, Explained Simply
- Using LLM APIs
- Embeddings and Semantic Search
- Vector Databases
Read them roughly in this order. See it on the concept map →
Why it matters
Semantic search compares a query vector with every stored vector. With 10,000 passages that is instant. With 10 million passages of 1,536 dimensions it is 15 billion multiply-adds per query, and the vectors alone take about 61 GB as 32-bit floats. Fine for one query a minute. Hopeless for an app with hundreds of users searching at once.
The problem of finding the stored vectors closest to a query is called nearest neighbour search. Doing it exactly means looking at everything. The way out is approximate nearest neighbour (ANN) search: an index that finds almost all of the true nearest neighbours while looking at a tiny fraction of the data. A vector database wraps such an index with what an application needs: saving to disk, adding and deleting vectors, storing the original text and metadata next to each vector, and filtering ("only this user's documents", "only documents from 2025").
Vector databases sit under most retrieval-augmented generation systems, recommendation engines, image search and agent memory. Knowing how their indexes work tells you which knobs to turn, what can go wrong, and, just as useful, when you don't need one at all.
The intuition
Suppose you want the café nearest to a friend's house in another country. You don't measure the distance to every café on the continent. You take the motorway to the right region, then main roads to the right town, then local streets to the right block, and only then look at individual cafés. Each stage throws away most of the candidates without examining them.
ANN indexes do the same with vectors. There are two main ways to build the "road network":
- Divide the space into neighbourhoods and search only the few nearest neighbourhoods. This is the inverted file index (IVF).
- Link each vector to its near neighbours in a graph, add a few long-distance "motorway" links, and walk greedily towards the query. This is HNSW, the most widely used index today.
Both are approximate: occasionally the true nearest neighbour sits just across a boundary, or down a path the greedy walk didn't take. You trade a little accuracy for a speed-up of tens to thousands of times, and you choose the trade-off with a parameter.
Key idea A vector index avoids comparing the query with every vector by searching only promising regions (IVF) or by walking a graph of neighbours (HNSW). It returns almost all the true nearest neighbours, and one parameter trades speed against how many it finds.
How it works
Measuring "almost": recall@k
How good is an approximate search? Run the exact (brute-force) search too, and see how many of the true top the index returned:
The bars mean "number of items in", and means "in both". If the true 10 nearest neighbours are passages 3, 8, 15… and the index returns 9 of them plus one slightly farther passage, recall@k is 9/10 = 0.9. Production systems typically tune for recall@10 of 0.95 or more. The same measure, computed against human-labelled relevant documents instead of exact search, is used to evaluate whole retrieval systems (Advanced RAG).
IVF: search the nearest neighbourhoods
An inverted file index works in two phases:
- Build. Run k-Means Clustering on the vectors to find, say, 256 cluster centres. Each vector is filed under its nearest centre. Each cluster is a "cell", the vector equivalent of a neighbourhood.
- Search. Compare the query with the 256 centres (cheap), pick the
nprobenearest cells, and compare the query exactly with only the vectors filed in those cells.
With 256 equal-sized cells and nprobe = 4, you score about 4/256 ≈ 1.6% of the vectors. The risk is that a true neighbour lies in a cell whose centre is a bit farther from the query than the four you searched. Raising nprobe lowers that risk and costs time. The code below measures exactly this trade-off.
HNSW: a navigable small world
HNSW (Hierarchical Navigable Small World, Malkov and Yashunin, 2016) is a graph. Each vector is a node, linked to a handful of its nearest neighbours.
Greedy search on one layer. Start at some node. Look at its neighbours, and move to whichever is closest to the query. Repeat until no neighbour is closer than where you are. That node is (probably) a near neighbour of the query. On a graph of only short links, this takes many small hops to cross the space.
Layers. HNSW fixes that with a hierarchy. Every node is on the bottom layer, layer 0. Each node is also placed on higher layers with a probability that drops geometrically, so each layer has only about as many nodes as the one below, where is the number of links per node. With and a million vectors, layer 1 has about 62,500 nodes, layer 2 about 4,000, layer 3 about 250. The sparse top layers have long links, like motorways. The search starts at a fixed entry point on the top layer, walks greedily, drops to the next layer from where it stopped, and repeats. The number of hops grows only roughly with the logarithm of the number of vectors, so going from a million to a billion vectors adds only a few hops per layer.
Worked example. Picture a query whose true nearest neighbour is node 812. On layer 2 the search starts at the entry point, node 5, at distance 0.90 from the query. Its neighbours include node 431 at distance 0.55, so it hops there. None of 431's layer-2 neighbours is closer, so it drops to layer 1 at node 431 and finds node 690 at 0.31, then node 774 at 0.18. On layer 0 it hops from 774 to 812 at 0.07, and none of 812's neighbours is closer. Five hops, a few dozen distance computations, out of a million vectors.
The knobs. Three parameters matter:
M: links per node. More links give better recall and use more memory. Values of 16 to 64 are typical.ef_construction: how many candidates are considered when inserting a node. Higher builds a better graph, more slowly.ef_search(oref): how many candidates the search keeps in its list on the bottom layer, rather than following only the single best path. This is the speed-versus-recall dial you tune at query time, likenprobefor IVF.
HNSW gives excellent recall and speed and supports adding vectors one at a time, which is why most vector databases use it by default. Its cost is memory: the graph links come on top of the vectors, and the whole index generally needs to fit in RAM.
Compression: product quantisation
At hundreds of millions of vectors, memory becomes the bottleneck. Product quantisation compresses each vector by splitting it into chunks and replacing each chunk with the id of the nearest entry in a small learned codebook. A 1,536-dimension float vector of 6 KB can shrink to under 100 bytes, at some cost in accuracy. Libraries such as Faiss combine it with IVF. Simpler alternatives store vectors as 8-bit integers or even single bits, often followed by re-scoring the best candidates with full-precision vectors.
Metadata filters
Real queries come with conditions: this user's notes only, published after 2024, in English. A metadata filter restricts the search to vectors whose stored attributes match. There are two naive strategies, and both have traps:
- Post-filtering: find the top 10 by similarity, then drop those that fail the filter. If the filter is strict, you may be left with 2 results, or none, even though matching documents exist.
- Pre-filtering: find all vectors that pass the filter, then search only those. Exact and correct, but if the filter matches millions of vectors you are back to brute force, and graph indexes don't handle arbitrary subsets well.
Good vector databases combine the two, for example by checking the filter during the graph walk and widening the search until enough matches are found. When you evaluate a database, test it with your real filters, not just plain similarity search.
What a vector database adds, and your options
A vector database stores, for each item, an id, the vector, the original text, and metadata. It lets you insert, update and delete, persists everything to disk, builds and maintains the index, filters, and often also offers keyword or hybrid search (Advanced RAG). As of late 2026 the main families are:
- A vector extension to a database you already run: pgvector for PostgreSQL, and vector search in Elasticsearch, OpenSearch, MongoDB, Redis and others. Your vectors live next to your ordinary data, in the same transactions and backups.
- Dedicated vector databases: open-source systems such as Qdrant, Weaviate and Milvus, and managed services such as Pinecone. Built for scale and vector-specific features.
- Embedded libraries: Chroma and LanceDB run inside your Python process with no server, which is ideal for prototypes and small apps. Faiss is a fast index library without database features.
When you don't need one
- Under roughly 100,000 vectors, a NumPy matrix and a dot product (as in Embeddings and Semantic Search) answer a query in milliseconds. Save the matrix to a file. Done.
- If you already use PostgreSQL, pgvector is usually the right first choice. One less system to run.
- If your corpus is small enough to fit in the model's context window, you may not need retrieval at all for some tasks. Just put the documents in the prompt and use prompt caching (Context Engineering and Memory).
Reach for a dedicated vector database when you have millions of vectors, high query volume, heavy filtering, or need features such as multi-tenancy and replication.
In code
A brute-force versus approximate comparison you can run on a laptop. It builds an IVF index with scikit-learn's k-means over 50,000 random unit vectors that form loose clusters, like topics, and measures recall@10 against exact search as nprobe grows:
import numpy as np
from sklearn.cluster import KMeans
rng = np.random.default_rng(0)
n, d, k = 50_000, 64, 10
centres = rng.normal(size=(200, d)) # data with topic clusters
X = centres[rng.integers(0, 200, n)] + 1.5 * rng.normal(size=(n, d))
X /= np.linalg.norm(X, axis=1, keepdims=True) # unit length: dot = cosine
queries = X[rng.integers(0, n, 200)] + 0.05 * rng.normal(size=(200, d))
def exact(q): # brute force: score everything
return np.argsort(-(X @ q))[:k]
# IVF index: k-means splits the vectors into 256 cells; search only the nearest few.
km = KMeans(n_clusters=256, n_init=1, random_state=0).fit(X)
cells = [np.where(km.labels_ == c)[0] for c in range(256)]
def ivf(q, nprobe):
nearest_cells = np.argsort(-(km.cluster_centers_ @ q))[:nprobe]
ids = np.concatenate([cells[c] for c in nearest_cells])
return ids[np.argsort(-(X[ids] @ q))[:k]], len(ids)
truth = [set(exact(q)) for q in queries]
for nprobe in [1, 4, 16, 64]:
results = [ivf(q, nprobe) for q in queries]
recall = np.mean([len(truth[i] & set(r)) / k for i, (r, _) in enumerate(results)])
scanned = np.mean([s for _, s in results]) / n
print(f"nprobe={nprobe:2d}: recall@10 {recall:.3f}, scans {scanned:5.1%} of vectors")
# nprobe= 1: recall@10 0.621, scans 0.4% of vectors
# nprobe= 4: recall@10 0.804, scans 1.5% of vectors
# nprobe=16: recall@10 0.910, scans 6.1% of vectors
# nprobe=64: recall@10 0.982, scans 24.9% of vectors
Real indexes do better than this toy, because they are tuned and the data is real rather than random. Faiss gives you HNSW in a few lines (pip install faiss-cpu):
import faiss
index = faiss.IndexHNSWFlat(d, 32, faiss.METRIC_INNER_PRODUCT) # M = 32 links
index.hnsw.efConstruction = 200
index.add(X.astype("float32"))
index.hnsw.efSearch = 64 # the recall/speed dial
scores, ids = index.search(queries.astype("float32"), 10) # top 10 per query
# on the toy data above, recall@10 is 0.93 at efSearch=16, 0.985 at 64, 0.998 at 128
pgvector keeps vectors in PostgreSQL. <=> is cosine distance (1 minus cosine similarity), so smaller is closer:
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE notes (
id bigserial PRIMARY KEY,
owner_id int,
body text,
embedding vector(1536)
);
CREATE INDEX ON notes USING hnsw (embedding vector_cosine_ops);
-- the 5 notes nearest to a query vector, for one user only
SELECT id, body
FROM notes
WHERE owner_id = 42
ORDER BY embedding <=> '[0.012, -0.031, ...]'
LIMIT 5;
Chroma runs inside your Python process (pip install chromadb). If you pass text, it embeds it for you with a small default model:
import chromadb
client = chromadb.PersistentClient(path="./notes_db") # saved to disk
notes = client.get_or_create_collection("notes")
notes.add(ids=["n1", "n2", "n3"],
documents=["The car would not start; the battery was flat.",
"Water tomato plants twice a week in hot weather.",
"Renew the car insurance before the end of the month."],
metadatas=[{"owner": "ana"}, {"owner": "ana"}, {"owner": "ben"}])
hits = notes.query(query_texts=["my automobile won't turn on"], n_results=2,
where={"owner": "ana"}) # metadata filter
print(hits["documents"])
For production, pass your own embeddings (embeddings= instead of documents=) so you control the model.
Common pitfalls
- Never measuring recall. Default index settings may quietly lose 10–20% of the true neighbours on your data. Compute recall@k against brute force on a sample of real queries before you trust the index.
- Mismatched distance metrics. An index built for Euclidean distance on vectors that aren't normalised ranks differently from cosine similarity. Normalise vectors, or set the index's metric explicitly.
- Filtered queries returning too few results. Strict filters plus post-filtering can return 2 results instead of 10. Test with your real filters.
- Forgetting the text. Store the passage text and source (or a reliable id pointing to it) with each vector. A vector alone can't be turned back into words.
- Re-embedding is a migration. Changing the embedding model means re-embedding and re-indexing everything. Record which model produced each vector.
- Running a new database for 5,000 vectors. Operational complexity is a real cost. Start with NumPy or pgvector.
Watch out Deleting from a vector index is often a soft delete: the vector is marked as removed but stays in the graph until the index is rebuilt or compacted. If you must honour deletion requests (for privacy law, for example), check how your database actually removes data, and make sure deleted documents can't come back in search results. See Privacy, Data and Copyright.
Where it leads
- Retrieval-Augmented Generation: the main consumer of vector search.
- Advanced RAG: hybrid search combining vectors with keywords, reranking, and evaluating retrieval with recall@k and MRR.
- Context Engineering and Memory: vector stores as long-term memory for chatbots and agents.
- k-Nearest Neighbours: the same nearest-neighbour search used as a classifier.
- Recommender Systems and CLIP and Contrastive Learning: vector search over products, users and images.
A bit of history
Nearest-neighbour search is an old problem in computer science. k-d trees (Bentley, 1975) work well in a few dimensions but degrade in hundreds, an instance of the curse of dimensionality. Locality-sensitive hashing (Indyk and Motwani, 1998) offered the first strong approximate methods. Product quantisation (Jégou, Douze and Schmid, 2011) made billion-scale search fit in memory, and Meta released Faiss in 2017 with GPU support. HNSW (Malkov and Yashunin, preprint 2016) became the dominant graph index thanks to its speed, recall and simplicity. Around 2019–2021 dedicated vector databases appeared, and the RAG boom of 2023 turned them into a crowded market. By 2024 most mainstream databases, including PostgreSQL through pgvector, had added vector search themselves.
Try it
- In the code, change the number of k-means cells from 256 to 64 and to 1,024. How do recall and the fraction scanned change at
nprobe=4? Explain why.- Add a metadata filter to the IVF search: give each vector a random
ownerfrom 0 to 99, and return only one owner's vectors. Implement post-filtering and count how often you get fewer than 10 results.- If you can install
faiss-cpu, build the HNSW index above and plot recall@10 againstefSearchfor values 16, 32, 64 and 128.Hint for 2: with 100 owners, only about 1% of the vectors in each searched cell belong to the owner you want. Post-filtering the top 10 will usually leave none.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Hierarchical Navigable Small Worlds (HNSW)
A clear illustrated walk-through of how HNSW builds and searches its layers, with Faiss code and the effect of each parameter.
Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs
The HNSW paper: a layered graph you search greedily from a sparse top layer to a dense bottom one. The default index in most vector databases.
pgvector
Vector similarity search inside PostgreSQL: a vector column type, distance operators and HNSW and IVFFlat indexes, next to your ordinary tables.
Chroma documentation
An open-source embedding database you can run in-process with pip install. The quickest way to try a vector store from Python.
Faiss
The standard library for fast similarity search over dense vectors, with flat, IVF, product-quantisation and HNSW indexes on CPU and GPU.
Vector Databases: from Embeddings to Applications
A short course on how vector databases work: embeddings, brute-force and approximate search, HNSW, hybrid search and multilingual search.
Retrieval Augmented Generation (RAG)
A longer course on designing, building and evaluating production RAG systems: retrievers, vector databases, chunking, prompting and evaluation.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/building/vector-databases.md