Embeddings and Vector Databases: A Hands-On Introduction
Keyword search fails when users and documents use different words: "reset my password" vs. "account recovery". Embeddings fix this by representing meaning as numbers.
What Is an Embedding?
An embedding model turns text into a vector — a list of hundreds or thousands of numbers. Texts with similar meaning end up close together in that space.
"How do I reset my password?" → [0.12, -0.44, 0.91, ...]
"Steps for account recovery" → [0.10, -0.41, 0.88, ...] ← close
"Best biryani in Chennai" → [-0.73, 0.22, -0.05, ...] ← far
Measuring Similarity
Cosine similarity measures the angle between two vectors: closer to 1 means more similar.
const cosine = (a, b) => {
let dot = 0, na = 0, nb = 0;
for (let i = 0; i < a.length; i++) { dot += a[i] * b[i]; na += a[i] ** 2; nb += b[i] ** 2; }
return dot / (Math.sqrt(na) * Math.sqrt(nb));
};
Building Semantic Search
- Split your documents into chunks
- Generate an embedding for each chunk with an embedding API or an open-source model
- Store vectors with the original text and metadata
- At query time, embed the question and find the nearest chunks
- Show results — or pass them to an LLM (that's RAG)
Choosing a Vector Store
- pgvector — vector search inside PostgreSQL; great default if you already use Postgres
- Pinecone, Weaviate, Qdrant, Milvus — dedicated vector databases
- Elasticsearch / OpenSearch — vectors plus mature keyword search
- Cloud services — managed vector search in AWS, Azure, and Google Cloud
For a few thousand documents, even an in-memory array works for learning.
Tips
- Use the same embedding model for documents and queries
- Combine vector and keyword search (hybrid) for best accuracy
- Store metadata (source, date, permissions) to filter results
- Re-embed when you change embedding models
Beyond Search
Embeddings also power recommendations, duplicate detection, clustering support tickets by theme, and classification.
Embeddings are one of the most practical AI building blocks. Learn them once and you'll use them everywhere.