A vector database stores embeddings – lists of numbers that represent meaning – and finds the ones most similar to a query very quickly. It is the memory behind semantic search, recommendations and RAG.
What You Will Learn
- Why normal databases are not enough for meaning-based search
- Cosine similarity and nearest-neighbour search, in NumPy
- How to use ChromaDB with metadata filters
- Indexing methods (HNSW, IVF) in simple words
- How to choose a vector database
Prerequisites
OpenAI API (embeddings section).
Keyword Search vs Vector Search
| Query | Keyword search finds | Vector search also finds |
|---|---|---|
| “learn ML” | Pages with the exact words “learn ML” | “Machine learning course”, “data science training” |
| “cheap laptop” | “cheap laptop” | “budget notebook computer” |
Example: Similarity Search in NumPy
import numpy as np
vectors = {
"python course": np.array([0.9, 0.1, 0.0]),
"data science": np.array([0.7, 0.6, 0.1]),
"cooking recipes": np.array([0.0, 0.1, 0.9]),
"machine learning": np.array([0.6, 0.8, 0.0]),
}
query = np.array([0.65, 0.75, 0.05]) # embedding of "learn ML"
def cosine(a, b):
return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
ranked = sorted(vectors.items(), key=lambda kv: cosine(query, kv[1]), reverse=True)
for name, v in ranked[:3]:
print(f"{name:18s} {cosine(query, v):.3f}")
Explanation: Real embeddings have hundreds of dimensions, but the idea is the same: the query is compared with every stored vector and the closest are returned. “Cooking recipes” points in a different direction, so it is not in the top 3.
machine learning 0.996 data science 0.987 python course 0.733
Example: ChromaDB
# pip install chromadb
import chromadb
client = chromadb.PersistentClient(path="chroma_db")
col = client.get_or_create_collection("tutorials")
col.add(
ids=["t1", "t2", "t3"],
documents=["Linear regression predicts numbers",
"CNNs classify images",
"Pandas cleans tabular data"],
metadatas=[{"level": "beginner"}, {"level": "intermediate"}, {"level": "beginner"}],
)
res = col.query(query_texts=["How do I recognise pictures?"], n_results=1)
print(res["documents"])
res = col.query(query_texts=["data"], n_results=2, where={"level": "beginner"})
print(res["documents"])
Explanation: Chroma embeds the documents with a built-in model, saves them in the chroma_db folder and answers similarity queries. where filters by metadata before ranking.
How ANN Indexes Work
| Index | Idea in one line |
|---|---|
| HNSW | A multi-layer graph of neighbours; jump through it quickly to the closest vectors |
| IVF | Group vectors into clusters, search only the nearest clusters |
| PQ (product quantization) | Compress vectors to save memory, trading a little accuracy |
Popular Vector Databases
| Tool | Type | Good for |
|---|---|---|
| Chroma | Open source, embedded | Learning, prototypes |
| FAISS | Library from Meta | Fast local search on large sets |
| pgvector | PostgreSQL extension | Apps already using Postgres |
| Pinecone | Managed cloud service | Production without managing servers |
| Qdrant, Weaviate, Milvus | Open source servers / cloud | Scalable production, filtering |
Common Errors
| Problem | Cause and fix |
|---|---|
| Results look random | Use the same embedding model for documents and queries. |
| Dimension mismatch error | Every vector in a collection must have the same length. |
| Slow queries on big data | Use an ANN index (HNSW) instead of brute force. |
Series
LLM series: LLM Fundamentals · Transformer Architecture · OpenAI API · Hugging Face · LangChain · LlamaIndex · Vector Databases · LLM Evaluation
Interview Questions
Q: Why cosine similarity?
It compares direction (meaning) rather than vector length.
Q: What is HNSW?
Hierarchical Navigable Small World graph – a fast approximate nearest-neighbour index.
Practice Exercises
- Add 5 more items to the NumPy example and test 3 queries.
- Store 20 tutorial titles in Chroma and search them.
- Filter Chroma results by a “category” metadata field.
Summary
Vector databases store embeddings and quickly return the most similar items using ANN indexes. They power semantic search and RAG; Chroma and FAISS are great for learning, managed services for production.
Next: LLM Evaluation · RAG
Machine Learning Tutorials, Courses and Certifications