Tenant-filtered retrieval with citations in pgvector
Chunk, embed and query documents per tenant and return answers with sources or an honest low-confidence reply.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 11 minutes to read.
In short
Retrieval turns stored documents into small, searchable chunks with embeddings, then finds the chunks closest to a question. With pgvector the chunks, vectors and metadata live in Postgres, so you can filter by tenant in the same query as the similarity search. Each result keeps its source so the answer can cite it, and weak matches lead to an honest low-confidence reply.
Explained simply
Retrieval is how an AI app finds the parts of your documents that answer a question. Instead of sending a whole manual to the model, you send only the few passages that matter. The model then answers from those passages and says where each fact came from.
To make this work, documents are cut into chunks, short passages of a few hundred words or less. Each chunk goes through an embedding model, which turns text into a long list of numbers. Texts with similar meaning get similar lists. A question gets an embedding too, and you look for the chunks whose numbers are closest.
pgvector is a Postgres extension that stores these number lists and finds the nearest ones quickly. Because everything sits in Postgres, one query can say: only chunks from this tenant, only from documents that still exist, and closest to this question.
Each chunk remembers where it came from: which document, which page, which position. That is its provenance. The answer can then show citations a person can check. When even the best match is a poor fit, the honest reply is that the documents do not cover the question.
Press Play on a diagram to walk through it one step at a time.
- 1Extract
Text and page numbers from the file
- 2Chunk
Overlapping pieces of a few hundred tokens
- 3Embed
One vector per chunk, model version recorded
- 4Query
Tenant filter, then nearest chunks
- 5Cite
Answer with document, page and chunk IDs
- Client to FastAPI: POST /chat with question1POST /chat with question
- FastAPI to Model: Embed the question2Embed the question
- FastAPI to Postgres + pgvector: Top 5 chunks WHERE tenant_id = caller3Top 5 chunks WHERE tenant_id = caller
- Postgres + pgvector to FastAPI: Chunks with doc, page, similarity4Chunks with doc, page, similarity
- FastAPI to Model: Prompt with numbered passages5Prompt with numbered passages
- Model to FastAPI: Answer citing [1] and [3]6Answer citing [1] and [3]
- FastAPI to Client: Answer plus citation list7Answer plus citation list
In depth
Extracting and chunking text
Extraction pulls plain text out of a file. For PDFs, libraries such as pypdf return text per page, so record the page number as you go. Scanned PDFs contain only images and need OCR, which is a separate, slower step. Clean up repeated headers, footers and broken hyphenation before chunking.
Chunking decides what a search result looks like. Chunks that are too large blur several topics into one vector; chunks that are too small lose context. A common start is 300 to 800 tokens with 10 to 20 percent overlap, splitting on headings and paragraphs where possible. Keep the chunk's heading path, such as Handbook > Leave > Parental, as metadata. Treat these numbers as a starting point and measure retrieval quality on your own questions.
- Every N tokens with overlap
- Simple and predictable
- May cut sentences in half
- Good first baseline
- Split on headings and paragraphs
- Keeps ideas together
- Chunk sizes vary
- Needs clean extraction
- One or two chunks per page
- Easy page citations
- Pages mix topics
- Fine for short forms
Storing embeddings with versions
Create the extension once with CREATE EXTENSION vector, then add a column such as embedding vector(1024), where the number matches your embedding model's dimensions. Store the model name and a version beside it. Vectors from different models live in different spaces, so comparing them gives nonsense.
When you change models, do not overwrite in place. Write new chunks under the new embedding_version, backfill in the worker, switch queries to the new version, then delete the old rows. For speed on larger tables, add an HNSW index with the operator class that matches your distance, for example vector_cosine_ops for the <=> operator. Without an index pgvector does an exact scan, which is accurate and fine for small tenants.
- <-> L2 distance, <=> cosine distance, <#> negative inner product
- HNSW: fast approximate search, ef_search tunes recall
- Exact scan: no index, perfect recall, slower
- One embedding_version per query
Filter by tenant before top-k
Put the tenant filter in the WHERE clause of the same query that orders by distance. Never fetch the global top 5 and drop other tenants' rows in Python: that can return other tenants' text into your process and often leaves you with zero results.
Approximate indexes add a twist. An HNSW scan finds a candidate set first and Postgres applies the WHERE filter afterwards, so a small tenant may get fewer than k rows. Options include raising hnsw.ef_search, turning on iterative index scans (pgvector 0.8.0 and later, hnsw.iterative_scan), a partial index per large tenant, or partitioning the chunks table by tenant. Small tenants are often best served by an exact scan using a B-tree index on tenant_id.
Provenance, low confidence and deletion
Return each passage with its chunk ID, document ID, title, page and similarity score. Number the passages in the prompt and ask the model to cite those numbers; then map the numbers back to provenance on the server and drop any citation that does not match a passage you sent.
Decide what low confidence means. If the best similarity is under a threshold you tuned on test questions, skip the model call or ask it to say the documents do not cover the topic. Optional reranking, a second model that scores each question and passage pair, can improve ordering before you cut to the final few passages.
Deletion must be real. Mark the document deleted, exclude it in every query at once, then remove its chunks and stored file in the worker.
Learn it in 5 short steps
About 55m each. Track them with a timer in your plan.
- 1Extract and chunk text~55m
- 2Store embeddings with versions~55m
- 3Filter by tenant before top-k~55m
- 4Return provenance for citations~55m
- 5Handle low confidence and deletion~55m
Key points
- Store chunk text, embedding, tenant ID, document ID, page and embedding model version together.
- Apply the tenant filter inside the SQL query, before choosing the top-k results.
- Only compare vectors made by the same embedding model and version.
- Return provenance (document, page, chunk) with every passage so the UI can show citations.
- Set a similarity threshold and say clearly when nothing relevant was found.
Key terms
Tap a card to flip it. 0/6 known
Examples
-- <=> is cosine distance in pgvector (0 = same direction)
SELECT c.id, c.document_id, c.page, c.text,
1 - (c.embedding <=> $1) AS similarity
FROM chunks c
WHERE c.tenant_id = $2
AND c.embedding_model = 'embed-v3'
AND c.deleted_at IS NULL
ORDER BY c.embedding <=> $1
LIMIT 5;Tenant and model filters live in the same query as the vector search.
Setting up a chunks table in pgvector
This schema keeps tenant, provenance and model version next to each vector. The HNSW index speeds up cosine search, and the B-tree index supports exact scans and deletes for one tenant or document. pgvector is free and runs in the pgvector/pgvector Docker image for local work.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunks (
id bigserial PRIMARY KEY,
tenant_id uuid NOT NULL,
document_id uuid NOT NULL,
embedding_version text NOT NULL,
chunk_index int NOT NULL,
page int,
text text NOT NULL,
embedding vector(1024) NOT NULL,
UNIQUE (document_id, embedding_version, chunk_index)
);
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX ON chunks (tenant_id, document_id);Answering or declining with a threshold
Tenant A asks about parental leave. The search returns five chunks; the best similarity is 0.82, above the 0.55 threshold tuned on test questions, so the passages go to the model with numbers. Later tenant A asks about the office car park, which no document covers. The best similarity is 0.31, so the API returns a no-source reply without calling the model. Tenant B's car park policy is never considered, because the query only sees tenant A's rows.
hits = await repo.search(tenant_id, query_vec, version=EMBED_VERSION, k=5)
if not hits or hits[0].similarity < MIN_SIMILARITY:
return ChatAnswer(text='I could not find this in your documents.',
citations=[], confidence='low')
passages = [f'[{i}] {h.text}' for i, h in enumerate(hits, start=1)]
answer = await model.answer(question, passages)
cited = [hits[n - 1] for n in answer.cited if 1 <= n <= len(hits)]
return ChatAnswer(text=answer.text, citations=[c.provenance() for c in cited])Quick reference
- CREATE EXTENSION vector; then a column such as embedding vector(1024).
- Operators: <-> L2, <=> cosine distance, <#> negative inner product.
- Index: USING hnsw (embedding vector_cosine_ops) to match <=>.
- Start chunks at 300 to 800 tokens with 10 to 20 percent overlap, then measure.
- WHERE tenant_id = $caller goes in the same query as ORDER BY distance.
- Store embedding_version and never compare vectors across versions.
- Return chunk ID, document ID, page and score for each citation.
- Below the similarity threshold: say no source was found.
Common mistakes
- Fetching the global top-k and filtering by tenant in Python, which can leak data and return too few results.
- Mixing vectors from two embedding models in one search, which gives meaningless distances.
- Deleting a document but leaving its chunks searchable.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a chunk record for one passage of a synthetic handbook with every field you need for tenant filtering, citations and re-embedding.
- Exercise 2medium
Load the same synthetic document for two tenants, then show that a query for tenant A never returns tenant B's chunks, even with a question that matches B's text best.
- Exercise 3hard
Implement document deletion so search results stop including the document immediately and its chunks and file are removed by the worker afterwards.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do I need a separate vector database?
- Not for most apps. pgvector keeps vectors next to your relational data, so tenant filters and deletes are ordinary SQL. Dedicated vector stores help mainly at very large scale.
- How many chunks should I send to the model?
- Three to eight is a common range. More passages cost tokens and can distract the model; measure answer quality with your own test questions.
- What similarity threshold should I use?
- There is no universal number; it depends on the embedding model and your content. Collect questions with known answers and pick the score that separates relevant from irrelevant matches.
- Is reranking required?
- No. It is an optional second pass that often improves the final ordering, at the cost of extra latency and another model call.