Sub topic 10
Vector databases and libraries: what they add beyond an index
This chapter assumes you can write basic Python and know what an embedding is. It also assumes you have seen an exact search over a matrix of vectors and have met the idea of an approximate nearest-neighbor (ANN) index such as HNSW. Here you will see what a vector database adds on top of an index, and how to decide whether you need one.
An index is not a database
An ANN index answers one question: given a query vector, which stored vectors are closest? FAISS, which you used earlier, does this well. It has no notion of a document, a user, or a deletion that survives a restart.
A real application needs more than that:
- Storage of the original data. The index holds vectors. You also need the text, title, URL, or other payload for each hit.
- Metadata and filtering. You often want "the closest documents where
language = "en"andyear >= 2023". - Updates and deletes. Documents change. An index you rebuild from scratch each time becomes slow and fragile.
- Persistence. Vectors must survive a restart without re-embedding everything, which is the expensive step.
- Concurrency and serving. Many clients read and write at once, often over a network API.
- Scaling and reliability. Sharding, replication, backups, and access control.
A vector database packages an ANN index with these features. A vector library gives you the index and leaves the rest to you.
Libraries versus databases
| Kind | Examples | You get | You must build |
|---|---|---|---|
| Index library | FAISS, hnswlib, ScaNN | Fast search in your own process | ID mapping, payload storage, filters, persistence, serving |
| Embedded or local store | Chroma, LanceDB, SQLite with a vector extension | Storage, metadata, and search in one package, no server | Scaling beyond one machine |
| Search engine with vectors | Elasticsearch, OpenSearch, Postgres with pgvector | Vectors next to keyword search and SQL, in a system you may already run | Tuning for large vector workloads |
| Dedicated vector database | Qdrant, Milvus, Weaviate, Pinecone | Distributed serving, filtering, replication, managed options | Operating another system, or paying for a managed one |
The names change over time, so check each project's current documentation before choosing. The categories are what stay stable.
The ID mapping problem
The first thing a bare index forces on you is bookkeeping. FAISS returns integer positions, not documents. You must keep a parallel structure that maps each position to its text and metadata.
import numpy as np
import faiss
d = 4
payloads = [
{"id": "a", "text": "Reset your password", "lang": "en"},
{"id": "b", "text": "Mot de passe oublié", "lang": "fr"},
{"id": "c", "text": "Office opening hours", "lang": "en"},
]
vectors = np.array(
[[1, 0, 0, 0], [0.9, 0.1, 0, 0], [0, 0, 1, 0]], dtype="float32"
)
faiss.normalize_L2(vectors)
index = faiss.IndexFlatIP(d)
index.add(vectors) # row i of `vectors` becomes position i
query = np.array([[1, 0, 0, 0]], dtype="float32")
scores, ids = index.search(query, 2)
for score, pos in zip(scores[0], ids[0]):
print(f"{score:.3f}", payloads[pos])This works only while payloads[i] stays aligned with vector i. If you delete a document from the list but not the index, every later result points at the wrong text. This is a common source of silent bugs. A database stores the vector and payload together under one ID, so the alignment cannot drift.
Metadata filtering
Filtering is the feature that most often decides the choice. There are three ways to combine a filter with an ANN search.
- Post-filtering. Search for the top k, then drop the results that fail the filter. It is simple, but a strict filter can leave you with fewer than k results, or none.
- Pre-filtering. Apply the filter first, then search only the matching vectors. Results are correct, but a graph index like HNSW works poorly on an arbitrary subset, because removing nodes breaks the paths the search follows.
- Filtered search inside the index. The engine checks the filter while it traverses the index. This is what good vector databases implement, and it is hard to do well.
You can see the post-filtering failure with the index above.
def search_post_filter(query, lang, k=2, fetch=3):
scores, ids = index.search(query, fetch)
hits = [
(float(s), payloads[p])
for s, p in zip(scores[0], ids[0])
if payloads[p]["lang"] == lang
]
return hits[:k]
print(search_post_filter(query, "en", k=2, fetch=2)) # only one result survives
print(search_post_filter(query, "en", k=2, fetch=3)) # two resultsWith fetch=2, the French document takes one of the two slots and is then removed, so you get one result when you wanted two. Raising fetch helps, but you cannot know in advance how much to over-fetch. A selective filter, such as one customer's documents out of a million, makes post-filtering unreliable.
Persistence and updates
FAISS can write an index to disk and read it back.
faiss.write_index(index, "docs.faiss")
restored = faiss.read_index("docs.faiss")
print(restored.ntotal) # 3This saves the vectors but not your payloads list, so you must persist that yourself. Updates are the harder part. Behavior depends on the index type:
- A flat index supports adding vectors. Removing by ID needs an index wrapped with ID support, and removal can shift positions in some index types.
- HNSW graphs generally support adding vectors easily. Deletion is awkward, and many systems mark a vector as deleted and clean it up later.
- Trained indexes such as IVF learn cluster centers from your data. If the data distribution changes a lot, the clusters become poor and you must retrain and rebuild.
Databases hide this with background compaction and rebuilds, but the same trade-offs exist underneath. Heavy deletion or update workloads can lower recall or raise latency until a rebuild runs.
A local store in practice
An embedded store shows what you gain. This example uses Chroma, which keeps everything in one Python process and can persist to a folder. It embeds text with its default model on first use, which downloads the model.
import chromadb
client = chromadb.PersistentClient(path="./chroma_data")
collection = client.get_or_create_collection("help_docs")
collection.upsert(
ids=["a", "b", "c"],
documents=[
"Steps to recover access to your account",
"Our office is open from 9 to 5 on weekdays",
"Change your login credentials in the security settings",
],
metadatas=[
{"topic": "account"},
{"topic": "facilities"},
{"topic": "account"},
],
)
result = collection.query(
query_texts=["How do I reset my password?"],
n_results=2,
where={"topic": "account"},
)
print(result["ids"][0])
print(result["documents"][0])Compare this with the FAISS version. There is no ID list to keep aligned, the filter is part of the query, upsert handles both inserts and updates, and the data persists in ./chroma_data.
What else a database offers
- Hybrid search. Some systems run keyword and vector search together and fuse the results, as in the hybrid search chapter.
- Quantization. Vectors are stored in compressed form, such as 8-bit integers instead of 32-bit floats, to cut memory by a factor of four or more at some cost in accuracy.
- Multiple vectors per record. One document can hold several chunk vectors that share a parent ID.
- Access control and multi-tenancy. Each customer sees only their own data.
- Observability. Query latency, index size, and error metrics.
Memory is often the limiting factor. A rough estimate for float32 vectors is count × dimensions × 4 bytes. One million vectors at 384 dimensions needs about 1.5 GB before any index overhead. HNSW adds graph links on top, which can be a significant extra.
How to choose
Some practical criteria:
- Collection size. Exact search over a few hundred thousand vectors takes milliseconds to tens of milliseconds with a matrix product. You may not need an index at all.
- Update rate. Static collections suit a library. Frequently changing collections suit a database.
- Filtering needs. Heavy, selective filters favor systems with filtered search built in.
- Existing infrastructure. Keeping vectors next to your relational data avoids a second system and keeps data consistent. A transaction can update a row and its vector together.
- Operations budget. A managed service costs money. A self-hosted one costs engineering time.
Common mistakes
- Adopting a database too early. For a prototype with a few thousand documents, a NumPy matrix is simpler and exact.
- Mixing metrics. The index metric must match the one the model was trained for. An inner-product index with unnormalized vectors does not give cosine similarity.
- Forgetting the embedding model in the schema. Record the model name and version with the collection. Vectors from different models cannot be compared.
- Trusting defaults. HNSW and IVF parameters trade recall for speed. Measure recall against exact search on your own data, using the metrics from the evaluation chapter.
- Treating the database as the source of truth. Keep the original documents elsewhere, so you can rebuild the index after a model change.
Exercise
You have 200,000 support articles in Postgres, each tagged with a customer ID. Searches must return only the current customer's articles, and articles are edited daily. Which approach fits best, and why would a bare FAISS index be a poor fit?
Show answer
Use Postgres with a vector extension such as pgvector (or a vector database with filtered search). The articles and customer IDs already live in Postgres, so the filter, the vectors, and the edits stay in one system with transactions. A bare FAISS index would need a separate ID-to-article mapping, your own persistence, and a rebuild or delete strategy for daily edits. Its post-filtering by customer would also return too few results, because each customer owns only a small share of the data.
Exercise
A teammate says a vector database makes search results more accurate than FAISS. Is that correct? What does a database actually add?
Show answer
Not by itself. Most databases use the same kinds of ANN indexes (HNSW, IVF), so accuracy depends on the embedding model and index settings. What a database adds is storage of payloads, metadata filtering, persistence, updates and deletes, concurrent serving, and scaling features. Those solve engineering problems around the index, not ranking quality.