Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

Learning path · 12 steps

Build and Measure a RAG System
  1. 1
    What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  2. 2
    Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  3. 3
    Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  4. 4
    Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  5. 5
    Vector Databases Hands-On: The Same Search in Chroma and pgvector
  6. 6
    Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  7. 7
    The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  8. 8
    RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  9. 9
    Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  10. 10
    Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  11. 11
    Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  12. 12
    RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Retrieval and RAG

Learning path: Build and Measure a RAG System · Step 5 of 12

Vector Databases Hands-On: The Same Search in Chroma and pgvector

Store 12 help articles as vectors in two databases and ask both the same questions. Chroma is a folder on disk with where filters; pgvector is a table in the Postgres you already run. Same model, same answers, to the fourth decimal: 0.4259, 0.4494 and 0.8257.

Chaand Sheikh

·27 November 2026Retrieval and RAG

What you will learn

  • Name the four things a vector store keeps for every record
  • Store and search 12 articles in Chroma with upsert, query and a where filter
  • Do the same in Postgres with a vector(384) column, an HNSW index and the <=> operator
  • Read cosine distance correctly: smaller is closer

Before you start

  • Real Embedding Models
  • Basic SQL (SELECT, WHERE, ORDER BY)

A vector database keeps your vectors and answers one question: which ones are nearest to this one? In a RAG system it's the store step, and retrieval can only search what the store keeps.

We'll put the same 12 help articles into two stores, Chroma and Postgres with pgvector, ask both the same questions, and check whether they agree. The embedding model, all-MiniLM-L6-v2, runs on your machine, so no API key is needed. (New to it? See Real Embedding Models.)

A shelf sorted by topic, not by title

Think of a library sorted by topic. Our 12 articles for a notes app sit on five shelves: account, billing, security, data and integrations. A customer types I can't get into my account anymore, and the search takes the closest books. First comes Reset your password, at a distance of 0.4259, and that article shares no words with the question. It's found by meaning.

Open one book: a record

The four parts of a record id acct-01 find it again text "If you cannot sign in, Forgot password..." metadata title category: account vector 384 numbers where it sits A store keeps these four things, and answers one question: what is nearest?
The same record shape is used in Chroma and in the Postgres table.

The id lets you find a record again. The text is what people read. The metadata holds small labels, like the category, that you can filter on. And the vector is where the record sits on the shelf.

Storing in Chroma

import chromadb
from sentence_transformers import SentenceTransformer

from articles import ARTICLES, FILTER_CATEGORY, QUERIES

model = SentenceTransformer("all-MiniLM-L6-v2")
client = chromadb.PersistentClient(path="chroma_data")
articles = client.get_or_create_collection(
    "help_center", metadata={"hnsw:space": "cosine"})

texts = [a["text"] for a in ARTICLES]
articles.upsert(
    ids=[a["id"] for a in ARTICLES],
    documents=texts,
    metadatas=[{"title": a["title"], "category": a["category"]} for a in ARTICLES],
    embeddings=model.encode(texts, normalize_embeddings=True).tolist(),
)
print("stored", articles.count(), "articles in Chroma")
stored 12 articles in Chroma

PersistentClient writes the data into a folder on your disk, so there's no server to start. The collection is told to measure distance with cosine. upsert means insert, or update if the id already exists, and it takes the same four things: ids, texts, metadata and vectors.

Searching, and filtering by metadata

def search(question, category=None):
    vector = model.encode([question], normalize_embeddings=True).tolist()
    where = {"category": category} if category else None
    found = articles.query(query_embeddings=vector, n_results=3, where=where)
    tag = f"   [category = {category}]" if category else ""
    print(f"\nQ: {question}{tag}")
    rows = zip(found["ids"][0], found["metadatas"][0], found["distances"][0])
    for rank, (id_, meta, dist) in enumerate(rows, 1):
        print(f"  {rank}. {dist:.4f}  {meta['title']}  ({id_})")


search(QUERIES["q1"])
search(QUERIES["q2"])
search(QUERIES["q2"], category=FILTER_CATEGORY)
Q: I can't get into my account anymore
  1. 0.4259  Reset your password  (acct-01)
  2. 0.6236  Turn on two-factor sign-in  (sec-01)
  3. 0.6604  Delete your account  (acct-03)

Q: how do I get my money back
  1. 0.4494  Refund policy  (bill-01)
  2. 0.6527  Change or cancel your plan  (bill-02)
  3. 0.7298  Reset your password  (acct-01)

Q: how do I get my money back   [category = billing]
  1. 0.4494  Refund policy  (bill-01)
  2. 0.6527  Change or cancel your plan  (bill-02)
  3. 0.8257  Download your invoices  (bill-03)

The question goes through the same model, so it becomes the same kind of vector; that's why the two can be compared at all. These are distances, not similarities: smaller is closer.

Look at the money question. Third place is Reset your password, which has nothing to do with money. Add where={"category": "billing"} and the other shelves are ignored. Download your invoices comes in at 0.8257. That's further away than the password article was, but it's on the right shelf.

Postgres with pgvector

pgvector isn't a separate database. It's an extension inside Postgres. The project's compose.yaml starts the pgvector/pgvector:pg17 image (Postgres 17 with the extension inside) on port 5433, with a health check, so docker compose up -d --wait db returns once the database is ready.

import os

import psycopg
from pgvector.psycopg import register_vector
from sentence_transformers import SentenceTransformer

from articles import ARTICLES, FILTER_CATEGORY, QUERIES

model = SentenceTransformer("all-MiniLM-L6-v2")
host = os.environ.get("PGHOST", "localhost")
port = os.environ.get("PGPORT", "5433")
url = f"postgresql://USER:PASSWORD@{host}:{port}/helpdesk"   # the project uses local Docker defaults
conn = psycopg.connect(url, autocommit=True)
conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
register_vector(conn)

conn.execute("DROP TABLE IF EXISTS articles")
conn.execute("""CREATE TABLE articles (
    id text PRIMARY KEY, title text, category text,
    body text, embedding vector(384))""")
texts = [a["text"] for a in ARTICLES]
vectors = model.encode(texts, normalize_embeddings=True)
for a, v in zip(ARTICLES, vectors):
    conn.execute("INSERT INTO articles VALUES (%s, %s, %s, %s, %s)",
                 (a["id"], a["title"], a["category"], a["text"], v))
conn.execute(
    "CREATE INDEX ON articles USING hnsw (embedding vector_cosine_ops)")
count = conn.execute("SELECT count(*) FROM articles").fetchone()[0]
print("stored", count, "articles in Postgres")
stored 12 articles in Postgres

Same idea, in SQL. CREATE EXTENSION vector switches it on. The table is a normal table with one special column: embedding vector(384), one slot per number from MiniLM. The columns hold the same record as before. Then an HNSW index keeps searches quick.

The same search as SQL

SELECT id, title, embedding <=> %s AS distance
FROM articles
WHERE %s::text IS NULL OR category = %s
ORDER BY embedding <=> %s LIMIT 3

In pgvector, <=> is cosine distance. Each row gets a distance, the WHERE line is the billing filter (off when the category is NULL), ORDER BY sorts smallest first, and LIMIT 3 keeps the top three, just like n_results=3 in Chroma.

The run prints the same three result lists as Chroma: same articles, same order, and the same distances, 0.4259, 0.4494 and 0.8257, right down to the fourth decimal. Two different stores, one model, the same answers. The idea doesn't change, only the language you ask in.

HNSW: hop to the closer neighbour

Both stores use an index called HNSW. The idea: every point links to a few close neighbours, like a web. A search starts at one point, looks at its neighbours, hops to the one closer to the question, and repeats. It reaches the nearest point without checking every point on the map. That's what keeps search fast when you have millions of vectors instead of twelve. (Checking every vector is the brute-force method from Similarity Search.)

Which store do you pick?

Chromapgvector
Setuppip install, a folder on diskAn extension in Postgres (Docker here)
Filterwhere={"category": ...}Plain SQL WHERE, joins with your other tables
Searchcollection.query(...)ORDER BY embedding <=> ... LIMIT k
IndexHNSWHNSW

Start with Chroma to move fast. Use pgvector when your data already sits in Postgres.

Common mistakes

  • Reading a distance as a similarity. With cosine distance, smaller is closer.
  • Embedding the question with a different model, or without the same normalisation, as the stored vectors.
  • A vector(n) column whose size doesn't match the model: MiniLM gives 384.
  • Filtering after you take the top 3 instead of in the query. The right-shelf article may never make the list.
  • Hard-coding database passwords in scripts. Read them from the environment.

Quick recap

  • A record holds four things: id, text, metadata and vector.
  • A search turns the question into a vector and returns the smallest distances first.
  • A where filter narrows the shelves before the nearest ones are picked.
  • Chroma and pgvector gave identical results because the model and the distance were the same.

Try it yourself

Ask both stores your own question, like my bill is wrong, and check that they agree. Then add a 13th article to articles.py, rerun both scripts, and search for it in your own words.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in the learning path Build and Measure a RAG System · step 5 of 12

Previous
Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
Next post
Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored

Related course on Udemy

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)

Related posts

What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break

A customer types "I cannot log in" and keyword search finds nothing, although a password-reset article exists. Turn meaning into numbers by hand, find the nearest point with math.dist, build a three-topic toy embedder that finds the right article at 1.00, and watch it score 0.00 on "I can't get into my account".

The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer

Ingest, chunk, embed, store, retrieve, rerank and generate, in one Python file. Follow one question through a 26-chunk employee handbook to an answer that cites its source.

Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors

Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.

Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning

A smart model has never read your company's files, and they change every month. Three ways to give it the facts: paste everything, fine-tune, or retrieve only the right pieces. Follow a refund-policy question through all three and see why RAG wins when documents change.

On this page

  • A shelf sorted by topic, not by title
  • Open one book: a record
  • Storing in Chroma
  • Searching, and filtering by metadata
  • Postgres with pgvector
  • The same search as SQL
  • HNSW: hop to the closer neighbour
  • Which store do you pick?
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.