Vector Databases (AI Engg #9)
You have 200,000 support articles, each with an embedding. A user types a question. The naive way to find the closest article is to compute the similarity against all 200,000 vectors — every query, every user. At 200K vectors that is merely slow; at 200 million it is impossible. A vector database makes nearest-neighbor search fast by approximating it, and folds in the filtering that real applications need: this tenant, this language, not deleted.
This chapter is about where embeddings live. You will learn what a vector database actually does, the ANN idea that makes it fast, how to choose among the popular options, and the index/filter details that determine whether your RAG works in production.
What a vector database does
At minimum, it stores a set of records, each with:
- a vector (the embedding),
- a unique ID,
- metadata (tenant, source, date, language, permissions),
- optionally the original text or a pointer to it.
And it answers this query:
\[ \text{results} = \operatorname{top}_k\{\, \mathrm{sim}(q, v_i) \;\big|\; \mathrm{filter}(\text{meta}_i) \,\} \]
In English: “the \(k\) most similar vectors among those matching my metadata filter.” The filter part is what separates a vector database from a plain nearest-neighbor library. Without it you cannot say “only this customer’s documents” or “only documents updated this year” — and without that, you have a security incident waiting to happen.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=2.7cm, minimum height=0.72cm, font=\rmfamily\small, align=center},
a/.style={->, thick}]
\node[b, fill=blue!10] (q) at (0,1.5) {embed(query) $\to$ vector};
\node[b, fill=orange!15] (i) at (0,0) {ANN index + metadata filter};
\node[b, fill=green!12] (d) at (0,-1.5) {top-$k$ records + scores};
\draw[a] (q) -- (i); \draw[a] (i) -- (d);
\node[font=\rmfamily\small, text=black!60, anchor=west, align=left] at (3.1,0) {filter runs \emph{with} search,\\e.g. tenant = "acme"};
\end{tikzpicture}
The ANN idea: why approximate is enough
Exact nearest-neighbor search over \(N\) vectors costs \(O(N)\) per query — fine for thousands, hopeless for hundreds of millions. Approximate nearest neighbor (ANN) indexes trade a tiny recall loss for enormous speedups. Two families dominate:
- HNSW (Hierarchical Navigable Small World). A multi-layer graph where each node links to nearby neighbors; search descends from coarse to fine. Excellent recall and latency, memory-heavy. The default for most vector databases.
- IVF (Inverted File). Cluster vectors into cells; at query time, search only the nearest cells. Cheaper memory, needs tuning (
nprobe), used with product quantization (IVF-PQ) to compress vectors.
There is also flat / brute-force exact search, which many databases offer for small collections — often the right choice under ~100K vectors, because it is simple and exact.
You do not implement these. You choose parameters: M and ef_construction for HNSW, nlist and nprobe for IVF. The trade is always recall vs latency vs memory. Raise recall for evaluation; tune down for cost once you know it holds.
Choosing a database
The right first question is not “which is fastest?” but “do I want a library, a server, or a managed service?”
| Option | Form | Strengths | Pick it when |
|---|---|---|---|
| Chroma | embedded/server | Python-first, trivial begin | PoC, small/medium apps |
| FAISS | library | Raw speed, full control | research, custom pipelines |
| Qdrant | server (Rust) | strong filters, hybrid, scale | production self-host |
| Weaviate | server | built-in hybrid + modules | app servers, hybrid search |
| LanceDB | embedded | columnar, on-disk, fast | local/edge, no server |
| Pinecone | managed | zero ops, scales | you want no infrastructure |
| MongoDB Atlas / pgvector / Supabase | existing DB | vectors next to your data | you already run Postgres/Mongo |
| Milvus / Zilliz | server/managed | very large scale | billions of vectors |
A pragmatic default: Chroma or LanceDB to prototype, pgvector if you already have Postgres and value transactional consistency, Qdrant or Pinecone when filters, scale, and hybrid search become the bottleneck. The API shapes are similar enough that switching later is a day, not a quarter — so do not over-deliberate.
Indexing and searching, concretely
Chroma is the fastest way to feel the whole pipeline:
import chromadb
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
client = chromadb.Client() # in-memory; use PersistentClient() for disk
col = client.create_collection("docs", metadata={"hnsw:space": "cosine"})
docs = [
"Refunds are accepted within 30 days of purchase.",
"To reissue an invoice, go to Billing > History.",
"Reset your password from the security settings page.",
]
col.add(
ids=["1", "2", "3"],
documents=docs,
embeddings=model.encode(docs, normalize_embeddings=True).tolist(),
metadatas=[{"tenant": "acme", "lang": "en"}] * 3,
)
q = model.encode(["how do I get my money back"], normalize_embeddings=True).tolist()
res = col.query(query_embeddings=q, n_results=2, where={"tenant": "acme"})
for doc, dist in zip(res["documents"][0], res["distances"][0]):
print(round(dist, 3), doc)
The details that matter:
where={"tenant": "acme"}— scoping is not optional. Always filter by tenant and permissions.hnsw:space— set the metric at creation and match it at query time.- Batch inserts. Adding documents one at a time is 10–100× slower than batching.
- Persist. In-memory is for experiments; use a persistent client or a server for anything real.
Filters, hybrid search, and reranking
Three upgrades take a toy index to production quality.
Metadata filters. Store tenant, source, date, language, permissions, and document type. Filter before or during search. Post-filtering (retrieve top-100, then drop) destroys recall when the filter is selective — if only 1% of docs match your tenant, you can retrieve 100 and find zero valid results.
Hybrid search. Dense vectors miss exact keywords (SKUs, error codes, names). Combine dense similarity with a keyword scorer (BM25) and merge the two ranked lists. Most production retrievers are hybrid.
# conceptual hybrid: merge dense and keyword rankings (Reciprocal Rank Fusion)
def rrf(dense_ids, keyword_ids, k=60):
score = {}
for rank, doc_id in enumerate(dense_ids):
score[doc_id] = score.get(doc_id, 0) + 1 / (k + rank)
for rank, doc_id in enumerate(keyword_ids):
score[doc_id] = score.get(doc_id, 0) + 1 / (k + rank)
return sorted(score, key=score.get, reverse=True)
Reranking. Retrieve a wide set (top-50), then score each candidate against the query with a cross-encoder, and keep the top 5. Cross-encoders are slower per item but far more precise, and they run only on 50 items, not the whole corpus. This “retrieve wide, rerank narrow” pattern is one of the highest-ROI upgrades in RAG.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=2.0cm, minimum height=0.68cm, font=\rmfamily\small, align=center},
a/.style={->, thick}]
\node[b, fill=blue!10] (q) at (-3.4,0) {query};
\node[b, fill=cyan!15] (r) at (-1.2,0) {retrieve\\top-50};
\node[b, fill=orange!15] (rr) at (1.2,0) {rerank\\cross-encoder};
\node[b, fill=green!12] (t) at (3.4,0) {top-5\\to LLM};
\draw[a] (q) -- (r); \draw[a] (r) -- (rr); \draw[a] (rr) -- (t);
\end{tikzpicture}
Operations you will forget, then regret
- Reindexing. When you change embedding model or dimensions, the entire index is invalid. Plan for a rebuild path and a shadow index for zero-downtime swaps.
- Deletes and updates. Soft-delete + periodic compaction, or your index accumulates ghost documents and recalls stale ones.
- Backups. Your index is derived data, but rebuilding millions of embeddings costs real money and time. Back it up.
- Observability. Log query vectors, filters, returned IDs, and scores. When RAG goes wrong, you need to see what was retrieved, not just the answer.
Pitfalls
- No tenant filter. One shared index without filters is a cross-customer data leak. Always scope.
- Metric mismatch. Creating a collection with cosine and querying as if Euclidean (or forgetting to normalize) silently wrecks ranking.
- Pure dense search. Keywords, codes, and exact names need BM25 alongside vectors.
- Retrieve-too-narrow. Sending top-3 chunks to the LLM with no rerank leaves recall on the table. Retrieve wide, rerank narrow.
Why is ANN acceptable when it is not exact? When does post-filtering fail badly?
ASolution
Because a tiny loss in recall (missing one near-neighbor occasionally) buys orders-of-magnitude speed, and reranking plus generous \(k\) recovers quality. Post-filtering fails when the filter is selective: if only 1% of documents match the tenant, retrieving 100 candidates can yield zero matches, and you never see the valid ones — so filter during search.
Next: RAGs (AI Engg #10) — assembling retrieval and generation into an answer you can cite and trust.