Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 16 of 28
❮Prev Next❯

pgvector Similarity Search and RAG with Metadata Filters

Module 2: Data for AI ⏱ 12 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    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.

    Simulate it » No Azure account needed

    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.

    Azure portal: Allow pgvector, create the table and search Enable pgvector and run a similarity query.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    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
    1. Extensions must be allow-listed first. Open Server parameters, find azure.extensions and tick VECTOR.
    2. Saved. Now open a terminal and create the extension in your database.
    3. vector(1536) holds one embedding. HNSW with vector_cosine_ops makes nearest-neighbour search fast; a normal index on tenant_id helps the filter.
    4. <=> is cosine distance: smaller means closer. Filter by tenant, order by distance, take the top 3.
    5. 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.

    😟 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
    🛠️ Solved with: pgvector RAG

    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.

    ▶ Explainer video See it in motion 8 steps · 1 min 34 sec

    An animation of retrieval-augmented generation with pgvector. A Contoso user asks about refunds, the question is embedded with the same model as the documents, and a SQL query orders chunks by cosine distance and keeps five. Without a tenant filter a Fabrikam chunk leaks into the results; adding WHERE tenant_id to the same query fixes it. An HNSW index replaces a full scan, the five chunks go into the prompt, and the model answers citing chunk ids.
    Read the video script
    1. 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.
    2. 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.
    3. 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.
    4. 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.
    5. 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.
    6. 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.
    7. 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.
    8. 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. 1 Chunk and embed

      Split documents into chunks and store each chunk with its embedding and metadata.

    2. 2 Embed the question

      Use the same embedding model and dimensions.

    3. 3 Retrieve with a filter

      WHERE tenant_id = ... ORDER BY embedding <=> question LIMIT 5.

    4. 4 Generate

      Send the chunks as context and ask the model to answer only from them.

    RAG with PostgreSQL and pgvector

    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, use 1 - (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_ops to 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

    Telecommunications

    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.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    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.

    Question 1

    Question 1 of 5

    A table named chunks contains an embedding column of type vector(1536). You need to return the five chunks that are most similar to a query vector by using cosine distance. Which ORDER BY clause should you use?

    Question 2

    Question 2 of 5

    A multi-tenant RAG application stores all tenants' document chunks in one PostgreSQL table. The application must never retrieve chunks that belong to another tenant, and it must return five relevant chunks for each question. What should you do?

    Question 3

    Question 3 of 5

    A similarity search that uses an HNSW index returns relevant results, but users report that some expected documents are missing. You want to improve recall for the query without rebuilding the index. What should you do?

    Question 4

    Question 4 of 5

    Documents were embedded by using text-embedding-3-small with 1,536 dimensions. A developer embeds user questions by using a different embedding model that also returns 1,536 dimensions. Retrieval results become irrelevant. What is the cause?

    Question 5

    Question 5 of 5 · Select 2

    You are implementing the generation step of a RAG application that retrieves chunks from Azure Database for PostgreSQL. You need to reduce the risk of the model inventing information. Which TWO actions should you take?

    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. 1.Which operator returns cosine distance?Show

      <=>

    2. 2.Does a smaller cosine distance mean more or less similar?Show

      More similar.

    3. 3.Where should a tenant filter go?Show

      In the SQL WHERE clause, alongside the vector ORDER BY.

    4. 4.What's the default hnsw.ef_search?Show

      40

    5. 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

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.