pgvector Similarity Search and RAG with Metadata Filters
30-second answer
With pgvector you store each chunk's embedding in a vector(1536) column, embed the user's question with the same model, and run ORDER BY embedding <=> %s LIMIT 5 to get the closest chunks by cosine distance. For retrieval-augmented generation (RAG) you add a metadata filter in the WHERE clause (such as tenant_id or lang), send those chunks to the model as context, and tell it to answer only from them. An HNSW index keeps the search fast, and hnsw.ef_search trades speed for recall.
Exam objective: 2.2.5 Run vector similarity search, including storing embeddings, semantic retrieval, and implementing retrieval-augmented generation (RAG) patterns by using metadata filter. 2.2.3 Implement indexing strategies, including optimizing query latency and reducing pgvector compute overhead. (Skills measured as of October 7, 2026)
Simulations
Feel it before you read it. No account needed, nothing leaves this page.
Extensions must be <strong>allow-listed</strong> first. Open <strong>Server parameters</strong>, find <code>azure.extensions</code> and tick <strong>VECTOR</strong>.
👆 Click the glowing item in the portal to continue
Read the steps as text
- Extensions must be allow-listed first. Open Server parameters, find azure.extensions and tick VECTOR.
- Saved. Now open a terminal and create the extension in your database.
- vector(1536) holds one embedding. HNSW with vector_cosine_ops makes nearest-neighbour search fast; a normal index on tenant_id helps the filter.
- <=> is cosine distance: smaller means closer. Filter by tenant, order by distance, take the top 3.
- EXPLAIN shows Index Scan using docs_embedding_idx. Without the index it would be a sequential scan over every row.
🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.
🖱️ Drag to rotate · scroll or pinch to zoom
RAG with a metadata filter
Retrieval-augmented generation (RAG): embed the question, fetch the closest chunks (ORDER BY embedding <=> $1 LIMIT 5), filter by metadata such as tenant_id or lang, then send those chunks to the model as context. The answer is grounded in your own data.
🤔 What happens if…
Read this tour as text
- Text becomes a vector. An embedding model turns text into a list of numbers, a vector (1,536 numbers for
text-embedding-3-small). Texts that mean similar things get vectors that sit close together, so "refund" lands near "money back". - Cosmos DB: items, partitions, RUs. In Azure Cosmos DB for NoSQL, JSON items live in containers, spread across logical partitions by the partition key. Every operation costs Request Units (RUs). A point read by id and partition key costs about 1 RU. A query that scans every partition costs far more.
- Indexing and consistency. By default Cosmos DB indexes every property, so writes cost more RUs. An indexing policy can exclude paths you never filter on, such as the big
embeddingarray. Consistency levels trade freshness for speed and cost: Strong, Bounded staleness, Session (default), Consistent prefix, Eventual. - Vector search in Cosmos DB. A vector embedding policy tells Cosmos DB where the vectors are, their dimensions and distance function. A vector index makes search fast:
diskANNorquantizedFlatfor large sets, orflatfor exact search on small vectors (up to 505 dimensions). ThenORDER BY VectorDistance(c.embedding, @q)returns the closest items. - Change feed. The change feed is an ordered log of inserts and updates in a container (deletes only show up in the *all versions and deletes* mode). A change feed processor reads it with a lease container that remembers how far each worker got, so a new product can be embedded the moment it’s saved.
- PostgreSQL with pgvector. In Azure Database for PostgreSQL, the pgvector extension adds a
vector(1536)column type. Without an index, every search compares against every row (a sequential scan). An HNSW or IVFFlat index finds near neighbours fast, trading a little recall for a lot of speed. - RAG with a metadata filter. Retrieval-augmented generation (RAG): embed the question, fetch the closest chunks (
ORDER BY embedding <=> $1 LIMIT 5), filter by metadata such astenant_idorlang, then send those chunks to the model as context. The answer is grounded in your own data. - Azure Managed Redis. Azure Managed Redis keeps hot data in memory. Cache-aside: check Redis, and on a miss read the database and store the result with a TTL. When data changes, invalidate the key. Redis can also hold a vector index for fast similarity search, for example a semantic cache of answers.
Build the retrieval half of a RAG app on PostgreSQL. Connect with psql, get past the extension allow-list, load 5,000 chunks for three tenants, then make similarity search fast with HNSW and safe with a tenant filter.
🎓 Education-only simulation. Your lab is saved in this browser, so you can leave and continue later.
😟 THE PROBLEM
The support bot answers from another customer’s documents.
😊 THE SOLUTION
Search embeddings with pgvector and always filter by tenant.
- No metadata filter✓ WHERE tenant_id = %s
- Ungrounded answers✓ Top-k chunks in the prompt
- Slow nearest-neighbour search✓ HNSW index
Start with a question
How does a chatbot answer from your company's own documents instead of making things up?
Imagine a new support agent on their first day. They don’t know your refund policy, so before answering a customer they open the policy binder, find the right page and read it out. They don’t guess.
Retrieval-augmented generation (RAG) makes a language model do the same. Your app finds the most relevant passages in your own data, hands them to the model, and asks it to answer only from those. With pgvector, the “find the right page” part is a SQL query in the PostgreSQL database you already run.
Explain it like I’m 10
Visual: RAG retrieval in motion
Here’s one question going through the whole retrieval path, including what happens when the tenant filter is missing.
Read the video script
- A question comes inA Contoso customer asks: can I get a refund after thirty days? Your app knows who they are, so it knows their tenant. That matters in a minute.
- Embed it with the same modelFirst, the question becomes an embedding, a list of 1,536 numbers. Use the same model that embedded your documents, or the numbers won't line up.
- Closest chunks firstNow one SQL query. The arrow operator is cosine distance, and smaller means closer, so you sort ascending and keep the top five.
- No filter, wrong tenantBut row two is Fabrikam's refund policy, another customer's data. With no tenant filter it's close in meaning, so it gets in. That's a leak.
- Filter in the same queryThe fix is a WHERE clause in the same query. Now only Contoso's rows can rank, and all five results are ones this user may see.
- HNSW instead of a full scanWithout an index, Postgres compares the question with every row. An HNSW index hops through a graph and keeps a short candidate list, forty by default. Raise ef search for better recall.
- Chunks go into the promptThe five chunks go into the prompt with their ids, plus an instruction: answer only from these, cite them, and say you don't know if they don't cover it.
- A grounded answer with sourcesSo the model answers from your data, not from memory, and every claim points back to a chunk you can check.
The technical explanation
RAG has two halves. Ingestion happens ahead of time. Retrieval and generation happen on every question.
-
1 Chunk and embed
Split documents into chunks and store each chunk with its embedding and metadata.
-
2 Embed the question
Use the same embedding model and dimensions.
-
3 Retrieve with a filter
WHERE tenant_id = ... ORDER BY embedding <=> question LIMIT 5.
-
4 Generate
Send the chunks as context and ask the model to answer only from them.
Ingestion: store chunks with embeddings
This uses the doc_chunks table from the schema lesson (tenant_id, content, metadata jsonb, embedding vector(1536)) and the pgvector Python package, which teaches psycopg how to send and receive vectors.
# pip install pgvector numpy openai
import numpy as np
from pgvector.psycopg import register_vector
register_vector(conn) # lets psycopg pass numpy arrays as vector values
def embed(text: str) -> np.ndarray:
resp = openai_client.embeddings.create(model="text-embedding-3-small", input=text)
return np.array(resp.data[0].embedding, dtype=np.float32)
with conn.cursor() as cur:
for i, chunk in enumerate(chunks):
cur.execute(
"""INSERT INTO doc_chunks (tenant_id, doc_id, chunk_no, content, metadata, embedding)
VALUES (%s, %s, %s, %s, %s, %s)""",
("contoso", doc_id, i, chunk, Jsonb({"lang": "en", "product": "router"}), embed(chunk)),
)
conn.commit()
Jsonb comes from psycopg.types.json. In a real loader you’d embed in batches (the embeddings API takes a list) and bulk-load with COPY.
Retrieval: similarity search plus metadata filter
SELECT id, content, embedding <=> %(q)s AS distance
FROM doc_chunks
WHERE tenant_id = %(tenant)s
AND metadata @> '{"lang": "en"}'
ORDER BY embedding <=> %(q)s
LIMIT 5;
Three details matter here:
<=>is cosine distance, which is 1 minus cosine similarity. Smaller is closer, so you sort ascending. If you want a similarity score for display, use1 - (embedding <=> q).- The filters live in the same query. That’s how a customer only ever sees their own documents, and it means all 5 rows are useful.
- The HNSW index must be built with
vector_cosine_opsto match<=>. OpenAI embeddings are normalised to length 1, so inner product (<#>,vector_ip_ops) gives the same order and is slightly cheaper.
Generation: ground the answer
q = embed(question)
with conn.cursor() as cur:
cur.execute(RETRIEVE_SQL, {"q": q, "tenant": tenant_id})
rows = cur.fetchall()
context = "\n\n".join(f"[{r[0]}] {r[1]}" for r in rows)
response = openai_client.responses.create(
model="gpt-4.1-mini", # your deployment name
instructions=(
"Answer only from the sources below. Cite source ids in square brackets. "
"If the sources don't contain the answer, say you don't know."
),
input=f"Sources:\n{context}\n\nQuestion: {question}",
)
print(response.output_text)
The instruction “say you don’t know” is what stops the model from filling gaps with guesses.
Tuning recall at query time
HNSW is approximate. It examines a candidate list of size hnsw.ef_search (default 40) and returns the best of those. Raise it for better recall, lower it for speed:
BEGIN;
SET LOCAL hnsw.ef_search = 100; -- only for this transaction
SELECT ... ORDER BY embedding <=> %s LIMIT 5;
COMMIT;
With IVFFlat, the matching knob is ivfflat.probes (default 1): how many clusters to search.
Architect level When filters and HNSW don't get along
HNSW walks its graph to find ef_search candidates, and only then applies your WHERE. If the filter matches 1% of rows, most of those 40 candidates get thrown away and you might get 2 rows back instead of 5. Fixes, roughly from simplest: raise hnsw.ef_search; add a B-tree index on the filter column so the planner can choose an exact search over the few matching rows when the filter is very selective; build a partial index per big tenant or partition by tenant; or, on pgvector 0.8.0 and later, SET hnsw.iterative_scan = relaxed_order so the index keeps scanning until enough rows pass the filter (hnsw.max_scan_tuples caps the work). Check your version with SELECT extversion FROM pg_extension WHERE extname = 'vector';.
Real-world business scenario
Contoso Telecom (fictional)
- The problem
- A support assistant served three brands from one database. Retrieval fetched the top 5 chunks across all brands and filtered in Python, so answers sometimes quoted the wrong brand's plan prices, and once showed a partner's internal note.
- What they used
- pgvector on Azure Database for PostgreSQL with the brand and language filters moved into the SQL WHERE clause, an HNSW index with vector_cosine_ops, and a prompt that answers only from cited chunks.
- Why that choice
- Filtering in the same query guarantees every retrieved chunk is allowed and relevant, and the grounding instruction stops the model inventing details when nothing matches.
- The result
- Wrong-brand answers stopped, and the team can trace every answer back to the chunk ids it cited.
When to use it and when not to
✓ Use it when…
- Your documents or product data already live in PostgreSQL and you want RAG without another data store.
- You need strict per-tenant or per-user filtering in the same query as the similarity search.
- You want to join retrieved chunks with business tables (orders, entitlements) in SQL.
✕ Think twice when…
- You need hybrid keyword plus vector ranking with semantic reranking out of the box.
- The question is about exact values, such as an order number. A normal WHERE lookup is faster and exact.
↔ Alternatives to consider
- Azure AI Search for hybrid search, semantic ranking and indexers that pull from many sources.
- Azure Cosmos DB for NoSQL vector search for document-first apps.
- Azure Managed Redis vector search for very low-latency lookups such as a semantic cache.
Test yourself with exercises
5 original practice questions in the AI-200 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.
Interview preparation
Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.
Beginner Walk me through a RAG request that uses PostgreSQL.
Model answer
The user asks a question. I turn it into an embedding with the same model I used for the documents. I run a SQL query that filters by tenant and orders by embedding <=> the question vector, limit 5. I put those 5 chunks into the prompt as context and ask the model to answer only from them, citing the chunk ids. Then I return the answer.
Interviewer follows up
Why must the question use the same embedding model as the documents?
You
Different models put meaning in different places. A vector from one model compared with vectors from another gives nonsense distances, even if the dimensions match.
Intermediate Why do you put the tenant filter in SQL instead of filtering the results in Python?
Model answer
Two reasons. Security: if I fetch the top 5 across all tenants and filter afterwards, another customer's text is already in my app's memory and could leak through a bug. And quality: if 4 of the 5 nearest chunks belong to other tenants, I'm left with one useful chunk. Filtering in SQL means all 5 are from the right tenant.
Experienced developer With an HNSW index and a selective filter, your query sometimes returns 2 rows instead of 5. Why, and how do you fix it?
Model answer
HNSW finds ef_search candidates first and the filter is applied afterwards. If the filter is selective, most candidates get thrown away. I can raise hnsw.ef_search, use a partial index or partitions per tenant, add a B-tree index on the filter column so the planner can choose it for very selective filters, or on pgvector 0.8 and later turn on hnsw.iterative_scan so the index keeps scanning until it finds enough matches.
Architecture & design When would you choose pgvector for RAG over a dedicated search service?
Model answer
When the source data already lives in PostgreSQL and I want joins, transactions and filters on business columns in the same query, with one less service to run. If I need hybrid keyword plus vector ranking, semantic reranking and built-in document cracking, Azure AI Search is usually the better fit.
Quick revision
Key points
- Embed documents and questions with the same model and dimensions.
- Nearest chunks: ORDER BY embedding <=> query_vector LIMIT k (smaller distance = closer).
- Put metadata filters (tenant_id, lang, product) in the WHERE clause of the same query.
- Send only the retrieved chunks to the model, with an instruction to answer from them and cite sources.
- hnsw.ef_search raises recall at the cost of speed. Filtered searches may need a higher value or iterative scans.
Important terminology
- Retrieval-augmented generation (RAG)
- A pattern where the app retrieves relevant passages from your data and gives them to a language model as context, so the answer is grounded in your content.
- Cosine distance (<=>)
- The pgvector operator that returns 1 minus cosine similarity. Smaller means more similar.
- Metadata filter
- A normal SQL condition (tenant, language, product, date) applied alongside the vector search so only allowed, relevant rows come back.
- Top-K
- The number of nearest chunks you retrieve, set with LIMIT.
- hnsw.ef_search
- A query-time setting for HNSW indexes (default 40) that controls how many candidates are examined. Higher gives better recall but slower queries.
- Iterative index scan
- A pgvector 0.8 feature (hnsw.iterative_scan) that keeps scanning the index when a filter removes too many candidates, so you still get enough rows.
Common mistakes
- Treating <=> as similarity and sorting DESC, which returns the least similar chunks first.
- Filtering by tenant in application code after the vector search.
- Sending whole documents instead of the top chunks, which wastes tokens and dilutes the answer.
Exam tips
- "Return the 5 most similar items" = ORDER BY embedding <=> @q LIMIT 5.
- "Only return documents for the signed-in customer" = metadata filter in the WHERE clause.
- "Improve recall of an HNSW search" = increase hnsw.ef_search.
Five quick revision questions
-
1.Which operator returns cosine distance?Show
<=>
-
2.Does a smaller cosine distance mean more or less similar?Show
More similar.
-
3.Where should a tenant filter go?Show
In the SQL WHERE clause, alongside the vector ORDER BY.
-
4.What's the default hnsw.ef_search?Show
40
-
5.What does the R in RAG stand for?Show
Retrieval.
Official references
Finished this lesson? Tick it off. Your progress is saved in this browser.
Next up: Size and Tune PostgreSQL for Vector Workloads
Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges.