RAG with PostgreSQL and pgvector: embeddings, HNSW indexes and permission filtering
Answering from internal documents without leaking rows the user may not see: embeddings and chunks, pgvector's HNSW index, why filtering after the index loses results, why permissions belong in the SQL rather than the prompt, and how to review RAG code written by AI.
On this page
1. The problem
An internal Q&A bot holds 40,000 documents from 12 branches. An employee in Da Nang asks about "the Tet bonus policy" and gets the Hanoi branch's salary and bonus table. The prompt says "answer only according to the user's permissions".
2. Key idea
RAG (retrieval-augmented generation) has two paths. Ingestion splits documents into chunks, turns each into a vector with an embedding model, and stores permission metadata alongside. Querying embeds the question, fetches the k nearest chunks and puts them in the prompt.
An LLM has no notion of permissions; it uses every word in the prompt. The leak happens at retrieval: a SELECT missing WHERE tenant_id = ?. Treat vector search as SQL with an ORDER BY distance; permission rules, indexes and query plans all still apply. Take tenant_id from the authenticated principal.
| Failure point | Symptom | Root cause |
|---|---|---|
| Filtering permissions in the prompt | other branches' data leaks | the model doesn't enforce permissions |
| Filtering after an approximate index | "not found" though the document exists | HNSW applies WHERE after scanning |
| Changing the embedding model | meaningless results | vectors from two models aren't comparable |
2.1 Where should the vectors live?
| Choice | Use when | Don't use when |
|---|---|---|
| pgvector, no index | < 50,000 chunks per tenant, need 100% recall | millions of rows with loose filters |
| pgvector + HNSW | 100,000 to a few million chunks, data already in PostgreSQL | the index doesn't fit in RAM |
| A dedicated vector DB | hundreds of millions of vectors, you can run another system | you need joins with permission tables in one transaction |
3. In Java
record Chunk(long id, String text, String source) {}
List<Chunk> search(Principal user, float[] q) {
return jdbc.sql("""
SELECT id, text, source FROM chunk
WHERE tenant_id = :tenant
AND acl_groups && CAST(:groups AS text[]) -- overlaps the user's groups
AND embedding_model = 'text-embedding-3-small'
ORDER BY embedding <=> CAST(:q AS vector) -- cosine distance
LIMIT 5
""")
.param("tenant", user.tenantId()) // from the token, not the request
.param("groups", user.groups().toArray(String[]::new))
.param("q", Arrays.toString(q)) // "[0.1, 0.2, ...]"
.query(Chunk.class)
.list();
}An index USING hnsw (embedding vector_cosine_ops) only serves <=>; writing <-> scans the whole table. Spring AI wraps this as PgVectorStore; build filters with FilterExpressionBuilder, never by concatenating strings.
Post-index filtering, HNSW parameters and changing the embedding model
- Why 5 results become 1: HNSW returns the
ef_search(default 40) nearest candidates across the whole table, then appliesWHERE. A condition matching 10% of rows leaves about 4; a tenant holding 1% often gets 0. - Fixes:
SET hnsw.iterative_scan = relaxed_order(pgvector 0.8+) keeps scanning up tohnsw.max_scan_tuples; partial indexes or partitions for a few large tenants; for small tenants, filter by B-tree then scan exactly (20,000 vectors of 1,536 dimensions take tens of ms). - Limits: HNSW supports up to 2,000 dimensions with
vector, 4,000 withhalfvec.<=>returns a distance (1 − similarity): Spring AI'ssimilarityThreshold(0.8)means distance ≤ 0.2. - Chunking: 200–800 tokens, 10–20% overlap, split on headings. Store
sourcefor citations. - When a document's permissions change, update every chunk's
acl_groupsin the same transaction: the biggest reason to keep vectors next to the source data. - Changing embedding models: a new column or table, re-embed in the background, switch queries when done. Never mix two models' vectors.
- Questions with exact codes ("error E1042") search poorly with vectors; combine with full-text.
4. Working with AI
Delegate to AI: chunking and ingestion code, schema migrations, 50 question–correct-chunk pairs for measuring recall.
Check yourself:
- Every vector query has tenant and group conditions taken from the authenticated principal.
- No filter strings built from user input.
- The
ORDER BYoperator matches the index ops class;EXPLAINshows an index scan. - A test proves a tenant A user never gets tenant B chunks, even when asking about B's exact content.
5. Exercises
Exercise 1: Review an endpoint "filtered by department"
Find the bugs and write a test that proves them.
@GetMapping("/ask")
String ask(@RequestParam String q, @RequestParam String dept) {
var docs = vectorStore.similaritySearch(SearchRequest.builder()
.query(q).topK(5)
.filterExpression("dept == '" + dept + "'").build());
return chat.prompt().user(q + "\n\n" + join(docs)).call().content();
}Solution to Exercise 1
deptcomes from a query parameter: anyone can senddept=hr. The department must come from the principal (@AuthenticationPrincipal).- String concatenation:
dept=x' || dept != 'xturns the filter into always-true, reading every department. - Test: a
salesuser calls/ask?dept=hrand/ask?dept=x' || dept != 'x; capture the prompt with a fakeChatModeland assert no chunk hasdept != sales. - Fix:
b.eq("dept", principal.dept())withFilterExpressionBuilder.
Exercise 2: Read a recall incident
After adding the tenant_id condition, "no information" answers rise from 4% to 31%, almost all for small tenants; large tenants are fine. EXPLAIN shows Index Scan using chunk_embedding_idx. AI suggests "raise topK to 50". Diagnose and fix.
Solution to Exercise 2
- HNSW takes the 40 nearest candidates across the whole table before filtering on
tenant_id; small tenants rarely have a chunk among those 40. RaisingtopKdoesn't change how many candidates HNSW scans (ef_searchdoes) and stuffs irrelevant chunks into the prompt. - Quick fix:
SET hnsw.iterative_scan = relaxed_orderper session or viaALTER DATABASE. - Root fix: small tenants filter by B-tree then scan exactly; large tenants get their own partial index. Re-measure recall with a standard question set per tenant group.
Summary
- RAG: ingestion (chunk, embed, store permissions) and querying (embed, fetch k chunks, prompt).
- Permissions live in the query, taken from the principal; not in the prompt.
- pgvector + HNSW handles a few million chunks when data is already in PostgreSQL.
- HNSW filters after scanning: enable iterative scan or split indexes for small tenants.
- Match the operator to the ops class; a new embedding model means re-embedding everything.
Comments
Community rules