Lesson 4 of 4 Vector Search and RAG with PostgreSQL

Building Filtered RAG Retrieval in PostgreSQL

This lesson explains filtered retrieval queries, how filters interact with approximate indexes, hybrid retrieval and how to keep retrieval correct.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the shape of a filtered retrieval query.
  • Explain overfiltering with HNSW.
  • Describe remedies such as iterative scans and partial indexes.
  • Explain how hybrid retrieval merges rankings.

A filtered retrieval query

A RAG retrieval query embeds the user's question, then selects the most similar chunks that the user is allowed to see and that match the context of the question. In PostgreSQL this is one SQL statement: a WHERE clause on metadata columns, an ORDER BY on vector distance, a LIMIT, and a join to the documents table for titles and source links that the answer will cite.

SELECT c.content, d.title, d.source_uri, c.embedding <=> %(q)s AS distance
FROM chunks AS c
JOIN documents AS d ON d.id = c.document_id
WHERE c.tenant_id = %(tenant)s
  AND d.category = %(category)s
  AND d.updated_at > now() - interval '2 years'
ORDER BY c.embedding <=> %(q)s
LIMIT 5;

The application then places the returned chunks, with their titles and links, in the prompt for the chat model, and instructs it to answer only from them and to cite the sources. The tenant filter comes from the authenticated session, never from the user's text, so that it enforces isolation; row-level security policies can enforce the same rule inside the database.

Spot the bug

A retrieval query that leaks

Exam skills 2.2.5

Find the lines that break tenant isolation or citation in this RAG retrieval code.

Log in to try this activity Interactive activities are free with an account.

How filters interact with approximate indexes

An HNSW index scan produces candidates in order of distance and PostgreSQL then applies the WHERE clause to them. The scan collects only hnsw.ef_search candidates (40 by default). If the filter is selective, say only 2% of chunks belong to the tenant, most candidates are discarded and the query may return fewer rows than its LIMIT, or none at all, even though matching rows exist. This is called overfiltering, and it is a classic cause of RAG answers that say "no information found".

pgvector 0.8 added iterative index scans: when the filter removes too many candidates, the scan continues to fetch more until enough rows pass or a limit is reached. They are enabled per session or transaction with hnsw.iterative_scan (strict_order or relaxed_order), with hnsw.max_scan_tuples capping the extra work; IVFFlat has equivalent settings. Other remedies suit specific cases.

  • Partial indexes per common filter value, such as one HNSW index per large tenant or category, so the index contains only matching rows.
  • Partitioning by tenant, with an index per partition, so the filter selects a partition before the vector search.
  • Exact search for very selective filters: when a B-tree filter leaves a few thousand rows, an exact distance sort over them is fast and complete, and the planner may choose it on its own.
  • Higher ef_search, which increases the candidates collected, at a latency cost.
BEGIN;
SET LOCAL hnsw.iterative_scan = relaxed_order;
SET LOCAL hnsw.ef_search = 100;
-- filtered retrieval query here
COMMIT;

The following diagram shows how a tenant filter empties the candidate list of a shared HNSW index, and the two fixes.

Overfiltering with one HNSW index for 2,000 tenants. The index scan returns about 40 candidates from the whole table, which rarely include a small tenant's chunks, so the tenant filter leaves too few rows and the assistant says no information exists. Iterative index scans continue until enough rows match, and partitioning by tenant makes each search cover only that tenant's vectors.
The candidate count is the default hnsw.ef_search of 40.
Scenario questions

Fixing overfiltering

Exam skills 2.2.5 · 2.2.3

Choose the remedy for overfiltering that fits each case.

Log in to try this activity Interactive activities are free with an account.

Hybrid retrieval

Vector similarity misses exact terms such as product codes, and keyword search misses paraphrases, so the strongest retrieval often combines both. PostgreSQL's full-text search ranks rows by term relevance with ts_rank over a tsvector column with a GIN index. A common way to merge the two rankings is Reciprocal Rank Fusion (RRF): each result scores 1/(k + rank) in each list, with k often 60, and the scores are summed.

WITH semantic AS (
    SELECT id, row_number() OVER (ORDER BY embedding <=> %(q)s) AS r
    FROM chunks WHERE tenant_id = %(tenant)s
    ORDER BY embedding <=> %(q)s LIMIT 20),
keyword AS (
    SELECT id, row_number() OVER (ORDER BY ts_rank(content_tsv, query) DESC) AS r
    FROM chunks, websearch_to_tsquery('english', %(text)s) AS query
    WHERE tenant_id = %(tenant)s AND content_tsv @@ query
    ORDER BY ts_rank(content_tsv, query) DESC LIMIT 20)
SELECT c.id, c.content,
       coalesce(1.0 / (60 + s.r), 0) + coalesce(1.0 / (60 + k.r), 0) AS rrf
FROM chunks c
LEFT JOIN semantic s ON s.id = c.id
LEFT JOIN keyword  k ON k.id = c.id
WHERE s.id IS NOT NULL OR k.id IS NOT NULL
ORDER BY rrf DESC LIMIT 5;

Azure Database for PostgreSQL also offers the azure_ai extension, which can call Azure OpenAI from SQL to generate embeddings, for example during ingestion with azure_openai.create_embeddings. Whether embeddings are generated in SQL or in Python, the same model must be used for documents and queries.

Fill in the value

Reciprocal Rank Fusion

Exam skills 2.2.5

Calculate RRF scores with k = 60.

Log in to try this activity Interactive activities are free with an account.

Keeping retrieval correct

Three details decide whether retrieval stays trustworthy over time. Re-ingesting a changed document should replace its chunks in one transaction, so that a query never sees half old and half new chunks. Deleting a document must delete its chunks, which the ON DELETE CASCADE foreign key ensures. And retrieval quality should be evaluated with a set of representative questions and expected sources whenever chunking, embedding model, index type or query parameters change.

Match the pairs

Keeping retrieval trustworthy

Exam skills 2.2.5

Match each risk with the practice that prevents it.

Log in to try this activity Interactive activities are free with an account.
Worked example

Answers that say no information exists

A multitenant help assistant stores 30 million chunks for 2,000 tenants in one table with a single HNSW index. Small tenants often get "I could not find information about that", although their documents clearly cover the question. Large tenants get good answers. The query filters on tenant_id and uses LIMIT 5 with default settings.

This is overfiltering: the HNSW scan collects 40 candidates from the whole table, which rarely include a small tenant's chunks, so the tenant filter leaves zero to two rows. Enabling iterative index scans with hnsw.iterative_scan makes the scan continue until enough of the tenant's rows are found. For a more structural fix, partitioning the chunks table by tenant (or partial indexes for the largest tenants) makes each tenant's search cover only its own vectors.

Raising LIMIT to 50 does not help, because the index still yields only its candidate list. Removing the tenant filter would return other tenants' content. Switching to IVFFlat has the same overfiltering behaviour with probes.

Check yourself

Which pgvector setting lets an HNSW scan keep fetching candidates when a filter removes too many of them?

Show answer

hnsw.iterative_scan (strict_order or relaxed_order), available from pgvector 0.8, with hnsw.max_scan_tuples capping the extra work.

Exam Tips

Remember for the exam

  • Retrieval is one SQL statement: metadata WHERE, ORDER BY distance, LIMIT, joined to documents for citations.
  • Selective filters with HNSW can return too few rows; enable hnsw.iterative_scan (pgvector 0.8+).
  • Partial indexes or partitioning by tenant shrink each search's scope.
  • Hybrid retrieval merges vector and full-text rankings, for example with RRF.