What is a vector database? Explained with a 30-line example
A vector database stores embeddings, lists of numbers that capture what a piece of text means, and finds the ones closest to the embedding of a question. It is the retrieval step in RAG: before a model answers, the database hands it the few passages most likely to contain the answer.
How it works
- Split your documents into chunks, a paragraph or two each.
- Embed each chunk with an embedding model and store the vector next to the text and some metadata, such as the customer it belongs to.
- Embed the question with the same model.
- Search for the stored vectors closest to it, usually by cosine similarity, after filtering on metadata.
Close vectors mean similar meaning, so a question about refunds lands near the refund policy even when the words differ.
A vector database in 30 lines
This toy version uses word counts as embeddings so it runs anywhere. Real embedding models return hundreds of numbers per chunk, but the search is the same idea.
import math
VOCAB = ["refund", "days", "payment", "failed", "card", "password", "reset", "email", "login"]
def embed(text):
"""A toy embedding: word counts over a tiny vocabulary. Real models return hundreds of numbers."""
words = "".join(c for c in text.lower() if c.isalnum() or c == " ").split()
return [words.count(w) for w in VOCAB]
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm = math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b))
return dot / norm if norm else 0.0
# The "database": each row keeps the vector, the text and metadata to filter on.
rows = [
{"text": "Refund within 7 days of payment.", "customer": "acme"},
{"text": "If a card payment failed, try another card.", "customer": "acme"},
{"text": "Reset your password from the login email.", "customer": "acme"},
{"text": "Refund requests take 10 days.", "customer": "globex"},
]
for r in rows:
r["vector"] = embed(r["text"])
def search(question, customer, k=2):
q = embed(question)
allowed = [r for r in rows if r["customer"] == customer] # filter first: never show another client's data
scored = sorted(allowed, key=lambda r: cosine(q, r["vector"]), reverse=True) # exact search: compare with every row
return [(round(cosine(q, r["vector"]), 2), r["text"]) for r in scored[:k]]
print(search("How many days for a refund?", customer="acme"))
print(search("My payment failed", customer="acme"))
It prints the refund policy first for the refund question, with a score of 0.82, and the failed-payment advice first for the payment question. Now remove the customer filter: the top answer to the refund question becomes the other company’s “Refund requests take 10 days”, with a perfect score of 1.0. Similarity knows nothing about who is allowed to see what. That is why the filter runs before the ranking, and why it belongs in code, not in a prompt.
Exact or approximate search
The example compares the question with every row. That is exact search: perfect recall, and fine for thousands of chunks. With millions, databases build an approximate index instead. pgvector, for example, offers HNSW, a multilayer graph with a better speed and recall trade-off but slower builds and more memory, and IVFFlat, which divides vectors into lists, builds faster and uses less memory.1 Approximate means a close match can occasionally be missed, so measure it.
Which one to use
| Option | What it is | Good fit |
|---|---|---|
| pgvector | Open-source vector search inside Postgres1 | You already run Postgres and want vectors next to your other data |
| Chroma | Apache-2.0, runs in your Python process or as a server, with a hosted cloud2 | Prototypes and small apps |
| Qdrant | Apache-2.0 engine written in Rust, filters on JSON payloads, with a managed cloud3 | A dedicated search service with heavy filtering |
| Pinecone | A hosted search service with metadata filters; can run in your own cloud account4 | Teams that do not want to operate a database |
For most first projects the honest answer is pgvector or Chroma. A client with data rules will often decide for you: the vectors are derived from their documents, so they usually have to live where the documents live.
Where it goes wrong
- Bad chunks. A chunk that cuts a policy in half retrieves half an answer.
- Two embedding models. Documents embedded with one model and questions with another land in different spaces.
- No filter. As above, the most similar text may belong to someone else.
- No measurement. Track whether the right chunk appears in the top few results for a fixed set of questions. That is an eval, and it tells you whether a change helped. See also RAG vs fine-tuning and context engineering.
Week 3 of the Zero to FDE roadmap builds exactly this: a document Q&A tool with a vector store, metadata filters and answers that cite their sources.
Zero to FDE is a self-paced 16-week course, ₹2,999 once, with a 7-day full refund. Week 1 is free, and one Week 4 lesson is free if you already write backend code. It has no live classes, no mentors and no accredited certificate.
Sources
Zero to FDE is a 16-week path, for working engineers and AIML graduates, to the work Forward Deployed Engineers do: backend basics, LLMs, RAG, agents, evaluation and deployment, with a shipped deliverable every week. Week 1 is free and complete, no card needed.
Start Week 1 freeMore from the blog
- Forward Deployed Engineer jobs in 2026: what the data says
- What is RAG? Retrieval-augmented generation, explained with working code
- What is an AI agent? The agent loop, explained with code
- AI engineer roadmap 2026: what to learn, and in what order
- Will AI replace software engineers? What the data says in 2026
- Forward Deployed Engineer courses in India (2026): fees, format and how they compare
- Forward Deployed Engineer vs ML engineer: which AI role fits you?
- Forward Deployed Engineer salary in India: what the 2026 data says for 2027
- Forward Deployed Engineer interview questions: the six rounds and how to answer
- Why Forward Deployed Engineer is a smart next move for a software engineer
- Forward Deployed Engineer certification in 2026: what exists, what it costs, and what employers check
- Forward Deployed Engineer skills: what 1,000 job posts ask for
- Forward Deployed Engineer vs Solutions Engineer: the real difference
- Forward Deployed Engineer resume: what to put on one page
- Forward Deployed Software Engineer (FDSE): what the Palantir title means
- Forward deployed AI engineer, AI deployment engineer, FDE: the titles explained
- Prompt injection explained: what it is and how to defend against it
- Context engineering explained: beyond prompt engineering
- RAG vs fine-tuning: which one to use, and when
- LLM evals explained: how to test a system that gives different answers
- LLM observability explained: traces, cost and what to log
- Tool calling explained: how an LLM uses your functions
- What is MCP? The Model Context Protocol explained
- AI agent vs workflow: which one does your problem need?
- AI engineer vs ML engineer: what each one does
- AI engineer interview questions: 25 that test whether you have built anything
- EY now hires Forward Deployed Engineers for audit. The role is leaving the AI labs
- LangGraph explained: state, nodes and edges, with a 30-line example
- Randstad: 90% of Indian employers are growing tech teams for AI. What it means for engineers
- AI agent memory explained: short-term vs long-term, with a tested example
- LLM cost optimization: prompt caching, batching and model routing, with the numbers
- Structured outputs from an LLM: JSON schema, validation and retries
- Embeddings explained: vectors, cosine similarity and dimensions
- Data engineer to AI engineer: what carries over and what to learn
- AWS launches a Forward Deployed Engineering Competency, with Infosys, TCS and Coforge among 22 launch partners
- Forward Deployed Architect: what the role is, certifications and courses
- Persistent launches a Forward Deployed Engineering program with Microsoft, a day after NIIT's FDE talent blueprint
- How to become an AI engineer in India: the route depends on where you start
- Self-paced Forward Deployed Engineer courses in India under ₹10,000 (and under ₹3,000)
- AWS and OpenAI will jointly staff forward deployed engineering teams inside customer environments
- Backend developer to AI engineer: what carries over and what to learn
- Claude now runs on premises in customers' own data centers through AWS AI Factories
- Agentic AI courses compared: four free options, and what a course must make you build
- AWS: attacks on AI systems grew about 800% in 2026, and an AI agent broke into a decoy MCP server in 12.7 minutes