Module 2 · Vector databases
Metadata filtering and multi-tenant architecture
5 min read
A real RAG almost never searches "all documents": it searches those of one customer, one category, one period, or those the user is allowed to read. Combining vector similarity with metadata filters looks simple — one more WHERE — but with an approximate index, it is one of the most insidious sources of errors. And when filters are used to isolate customers, an error becomes a data leak.
Pre-filtering and post-filtering
Two naive strategies compete:
| Post-filtering | Pre-filtering | |
|---|---|---|
| Principle | Find the k nearest, then filter | Filter, then search among the survivors |
| Risk | If the filter is selective, almost nothing remains of the k results | With an ANN index, the graph gets "disconnected" and the search gets lost |
| Example | 5 nearest, none in the "warranty" category: 0 results | Allowed nodes are too rare for navigation to reach them |
With exact search, pre-filtering is perfect. Prism does it this way: the filter removes passages before ranking.
scores = self._raw_scores(query)
if where is not None:
mask = np.array([where(c) for c in self.chunks])
scores = np.where(mask, scores, -np.inf)
With an HNSW index, it is trickier: the index walks a graph of neighbors, and if the filter only allows 1% of the vectors, the search explores its ef_search candidates without finding enough that pass the filter.
How databases cope
Modern databases each have their workaround:
- pgvector ≥ 0.8 offers iterative scans: if the filter eliminates too many candidates, the index keeps exploring instead of stopping.
SET hnsw.ef_search = 100; -- candidats explorés : plus = meilleur rappel, plus lent
-- pgvector ≥ 0.8 : continue l'exploration si le filtre élimine trop de candidats
SET hnsw.iterative_scan = relaxed_order;
SELECT id, article_id, 1 - (embedding <=> $1) AS similarity
FROM chunks
WHERE category = 'garantie'
ORDER BY embedding <=> $1
LIMIT 5;
relaxed_order may return results in a slightly inexact order; strict_order guarantees the order at the price of more work. The planner may also choose not to use the vector index and to run an exact search over the rows filtered by a B-tree index: that is often the best choice when the filter is very selective.
- Qdrant integrates filtering into the HNSW graph construction (payload indexes) and automatically chooses between filtered traversal and exact search based on estimated selectivity.
- Other databases build per-partition indexes or combine both strategies.
The practical rule: test your most selective filters. Measure the recall of a filtered search against the filtered exact search, exactly as in lesson 2.1.
Multi-tenancy: three architectures
When the same service serves several customers (tenants), you must guarantee that none sees another's documents.
| Architecture | Isolation | Cost | Suited to |
|---|---|---|---|
| One database or collection per customer | Maximum | High (one index per customer) | Few large customers, regulatory requirements |
| One partition per customer in a collection | Strong | Medium | Many customers of varying sizes |
Shared collection + tenant_id filter | Depends on the code | Low | Many small customers |
The third option is the most common and the most dangerous: a single forgotten WHERE tenant_id = … in one query, and one customer reads another's documents. In a RAG, the leak is all the more serious because the LLM summarizes and rephrases what it finds.
Isolation by the database: Row Level Security
PostgreSQL lets you move that responsibility from the code to the database, with Row Level Security:
ALTER TABLE chunks ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON chunks
USING (tenant_id = current_setting('app.tenant_id', true));
The application sets the customer at the start of each transaction (SET LOCAL app.tenant_id = 'nimbus'), and every query is filtered by the database, even those that forget the WHERE. In Prism's test, the corpus is loaded for two customers (134 passages): a search with no filter at all only sees the current customer's 67 passages.
Two precautions:
- RLS does not apply to the table owner or to roles that bypass it (superuser,
BYPASSRLS). The application must connect with an ordinary role. - With a connection pool, use
SET LOCALinside a transaction, so the setting does not outlive the request and leak to the next customer that reuses the connection.
Document-level permissions
Beyond the customer, documents often have individual permissions (an HR file, a management memo). Two approaches:
- Filter at search time: store the allowed groups in the metadata and filter on them. Fast, but permissions must be synchronized on every change.
- Check after the search: query the permission system for each result. Always up to date, but slower, and you must search more broadly to compensate for rejected results.
In both cases, the check happens before the passage reaches the LLM. A prompt that asks the model to "ignore confidential documents" is not access control.
Key takeaways
- Post-filtering: risk of empty results; pre-filtering with an ANN index: risk of a search that gets lost.
- Databases have workarounds (pgvector 0.8 iterative scans, Qdrant's integrated filtering): measure the recall of your selective filters.
- Multi-tenancy: a collection per customer, partitions, or a filtered shared collection — the last one is the riskiest.
- Row Level Security enforces isolation in the database, even if the code forgets the filter.
- Permissions are checked before the LLM, never delegated to the prompt.
Practice
- With
VectorIndex.search(where=...), search « combien de temps pour renvoyer ? » (how long to send back?) restricted to the "garantie" (warranty) category: what does the index return? - In PostgreSQL, load two customers, enable RLS and check that a query without
WHEREonly sees one customer. - Write an automated test that fails if a search query returns a passage belonging to another customer.