◆ AI All-in-One

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
↗ Plan a path here

Read first

Embeddings and Semantic Search

This leads to

Advanced RAG
The full path from zero — 8 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Python for AI
  4. How Machines Learn
  5. Dot Product, Norms and Similarity
  6. Large Language Models, Explained Simply
  7. Using LLM APIs
  8. Embeddings and Semantic Search
  9. 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.
Layer 2few nodes,long links Layer 1 Layer 0 entry 5 431 690 774 812 query Orange: the greedy search path. Hop to the neighbour closest to the query until none is closer, then drop a layer. Layer 0 holds every vector; each layer above holds about 1/M as many. Dashed lines join copies of the same node.
Fig. 1 HNSW search across three layers. The sparse top layer has a few nodes with long links. The search starts at the entry point, hops greedily towards the query, drops down a layer, continues with shorter hops, and finishes on the dense bottom layer, which holds every vector.

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 kk the index returned:

recall@k=∣ANN top-k∩exact top-k∣k\text{recall@}k = \frac{\lvert \text{ANN top-}k \cap \text{exact top-}k \rvert}{k}

The bars ∣⋅∣\lvert \cdot \rvert mean "number of items in", and ∩\cap 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:

  1. 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.
  2. Search. Compare the query with the 256 centres (cheap), pick the nprobe nearest 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 1/M1/M as many nodes as the one below, where MM is the number of links per node. With M=16M = 16 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 (or ef): 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, like nprobe for 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
0.1% 1% 10% 100% 0.5 0.6 0.7 0.8 0.9 1.0 nprobe 1 recall 0.62 nprobe 4 0.80 nprobe 16 0.91 nprobe 64 0.98 brute force 1.00 fraction of vectors scanned per query (log scale) recall@10 IVF over 50,000 vectors, 256 cells: measured by the code in this chapter
Fig. 2 Recall@10 against the fraction of vectors scanned, from the code above. Scanning 6% of the vectors already finds 91% of the true top 10, and 25% finds 98%. Brute force scans everything for perfect recall.

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

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

  1. 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.
  2. Add a metadata filter to the IVF search: give each vector a random owner from 0 to 99, and return only one owner's vectors. Implement post-filtering and count how often you get fewer than 10 results.
  3. If you can install faiss-cpu, build the HNSW index above and plot recall@10 against efSearch for 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. An ANN index returns 9 of the true 10 nearest neighbours, plus one slightly farther vector. What is its recall@10?

  2. An IVF index has 256 equal-sized cells and nprobe = 4. Roughly what fraction of vectors is scored per query, and how do you raise recall?

  3. You ask for the top 10 results for one user's documents, using post-filtering, and get only 2. Why?

  4. You have 20,000 passages and already store your app data in PostgreSQL. What does the chapter suggest?

  5. Which HNSW parameter do you turn at query time to trade speed for recall?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

Hierarchical Navigable Small Worlds (HNSW)

James Briggs (Pinecone) · Intermediate · Free

A clear illustrated walk-through of how HNSW builds and searches its layers, with Faiss code and the effect of each parameter.

Tool

pgvector

Andrew Kane and contributors · Intermediate · Free

Vector similarity search inside PostgreSQL: a vector column type, distance operators and HNSW and IVFFlat indexes, next to your ordinary tables.

Docs

Chroma documentation

Chroma · Beginner · Free

An open-source embedding database you can run in-process with pip install. The quickest way to try a vector store from Python.

Tool

Faiss

Meta AI Research · Intermediate · Free

The standard library for fast similarity search over dense vectors, with flat, IVF, product-quantisation and HNSW indexes on CPU and GPU.

Course

Vector Databases: from Embeddings to Applications

Sebastian Witalec (DeepLearning.AI with Weaviate) · Beginner · Free

A short course on how vector databases work: embeddings, brute-force and approximate search, HNSW, hybrid search and multilingual search.

Course

Retrieval Augmented Generation (RAG)

Zain Hasan (DeepLearning.AI) · Intermediate · free to audit

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