Start free

Zero to FDE / Blog / What is a vector database? Explained with a 30-line example

Blog

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

  1. Split your documents into chunks, a paragraph or two each.
  2. 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.
  3. Embed the question with the same model.
  4. 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

OptionWhat it isGood fit
pgvectorOpen-source vector search inside Postgres1You already run Postgres and want vectors next to your other data
ChromaApache-2.0, runs in your Python process or as a server, with a hosted cloud2Prototypes and small apps
QdrantApache-2.0 engine written in Rust, filters on JSON payloads, with a managed cloud3A dedicated search service with heavy filtering
PineconeA hosted search service with metadata filters; can run in your own cloud account4Teams 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

  1. pgvector, “Open-source vector similarity search for Postgres”, README on GitHub
  2. Chroma, README on GitHub (Apache-2.0)
  3. Qdrant, “Vector Search Engine for the next generation of AI applications”, README on GitHub
  4. Pinecone documentation, overview

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 free

More from the blog