Note 12 / RAG / Postgres / Prisma
Hybrid search on Postgres with pgvector: the Prisma migration that dropped the HNSW index and nobody got an error
A hybrid pgvector query that merges vector and full-text hits by rank, the settings that make a filtered HNSW search return enough rows, and the Prisma drift that silently deleted the vector index and sent production to a sequential scan.
- By
- Trần Thế Anh, Software Engineer
- Published
- Work done
- August to October 2026, AI Note Taker backend (NestJS, Prisma, Postgres with pgvector)
- Stack
- NestJS, Prisma, Postgres, pgvector (HNSW), full-text search
- Reading
- 6 min, 1,348 words
Retrieval-augmented generation fails in a way that is easy to miss: the language model is good at covering for bad retrieval, so answers can read well while most of the passages behind them are the wrong ones. This note collects what I took from building search for the notes backend: a hybrid query that does not depend on the vector index alone, the settings that make a filtered vector search return enough rows, and the Prisma behaviour that removed the HNSW index in production without raising anything.
The SQL below is a fresh illustration, not a paste from the project. Table and column names are made up for the example.
One query, two ranked lists
Dense vectors miss exact strings: part numbers, a person’s name, a document number, a slang spelling. Full-text search misses paraphrases. The query below runs both and merges the two ranked lists with reciprocal rank fusion (RRF). Each list contributes 1 / (60 + rank), and a chunk found by both lists rises to the top.
BEGIN;
SET LOCAL hnsw.iterative_scan = relaxed_order;
WITH q AS (
SELECT websearch_to_tsquery('simple', immutable_unaccent($2)) AS tsq
),
fts AS (
SELECT c.id,
row_number() OVER (ORDER BY ts_rank_cd(c.fts, q.tsq, 32) DESC) AS r
FROM chunks c, q
WHERE c.org_id = $1
AND c.fts @@ q.tsq
ORDER BY ts_rank_cd(c.fts, q.tsq, 32) DESC
LIMIT 50
),
vec AS (
SELECT c.id,
row_number() OVER (ORDER BY c.embedding <=> $3::vector) AS r
FROM chunks c
WHERE c.org_id = $1
AND c.embed_model = $4
ORDER BY c.embedding <=> $3::vector
LIMIT 50
)
SELECT coalesce(fts.id, vec.id) AS chunk_id,
coalesce(1.0 / (60 + fts.r), 0) + coalesce(1.0 / (60 + vec.r), 0) AS rrf_score
FROM fts FULL OUTER JOIN vec ON fts.id = vec.id
ORDER BY rrf_score DESC
LIMIT 40;
COMMIT;
A few details in it carry weight.
ORDER BY has to appear inside each branch, before the LIMIT. The row_number() OVER (ORDER BY ...) only numbers rows; it does not sort the branch’s output. Without the inner ORDER BY, LIMIT 50 keeps 50 arbitrary rows, and the ranks you fuse afterwards are ranks of an arbitrary sample. Nothing errors. Search quality just gets worse.
The fusion uses ranks, not scores, because a cosine distance and a ts_rank_cd value are on different scales and cannot be added meaningfully. The constant 60 is the usual RRF default. Moving to weighted fusion only makes sense once a set of labelled queries shows a gain, so I left it at 60.
unaccent() is marked STABLE in Postgres, which rules it out of an expression index, so the query goes through a wrapper called immutable_unaccent. The full-text expression in the query must match the one in the GIN index exactly. A small difference and the planner stops using the index.
Filters and the iterative scan
The tenant filter, org_id = $1, belongs in the database query. It must not be applied after the top results come back, because the top 50 across all tenants may contain none of yours. The id comes from the session, never from the request body.
A filter on top of an approximate vector index has its own trap. An HNSW index scans a fixed number of candidates (hnsw.ef_search, 40 by default) and the filter is applied afterwards. If the filter keeps one row in ten, about four rows survive and you asked for 50. From pgvector 0.8.0 the setting hnsw.iterative_scan makes the index keep scanning until it has enough rows that pass the filter. SET LOCAL limits the change to the transaction, which is why the query starts with BEGIN. My notes ask for 0.8.4 or later because earlier releases had a corruption bug involving HNSW and VACUUM.
The vector space has one model
The embed_model column in the vector branch is there on purpose. Vectors from two embedding models live in different spaces, and comparing them returns plausible-looking nonsense with no error. Every chunk stores the model that produced it, and every vector query filters on it. Changing the model means a backfill: write both, re-embed everything, switch reads with a flag, drop the old column after a week or two.
The index Prisma deleted
Prisma does not understand the hnsw index type, so the HNSW index lives in raw SQL and not in schema.prisma. When the schema and the database are compared, Prisma sees an index it does not know about and treats it as drift. The next prisma migrate dev can write a DROP INDEX for it into a migration, and migrate deploy then runs that migration in production.
That happened on the AI Note Taker backend on 15 August 2026. The index disappeared, the query still returned correct rows, and Postgres answered with a sequential scan over every chunk. Nothing failed. Because nothing fails, this is the kind of problem that gets noticed late.
The fix has three parts:
- Keep every hand-written index in
prisma/sql/*.sql, each file idempotent (CREATE INDEX IF NOT EXISTS ...). - Make the deploy script apply them after the migrations:
{
"scripts": {
"db:indexes": "node scripts/apply-raw-indexes.js",
"db:deploy": "prisma migrate deploy && npm run db:indexes"
}
}
- Add a check to CI that fails when a migration under
prisma/migrationscontains aDROP INDEXnaming one of the hand-made indexes. The point is to catch it in the pull request, before the migration is applied anywhere.
After any of this, EXPLAIN on the hybrid query should show an Index Scan using the HNSW index in the vector branch. If it shows Seq Scan on chunks, the index is missing or the operator class does not match the operator: <=> pairs with vector_cosine_ops, and a mismatch makes the planner ignore a perfectly good index.
A slow embedding call should not slow the answer
On 7 September 2026 the embedding provider took 11.4 seconds to embed one question, and the user got an answer after 13 seconds. The vector branch needs the question’s embedding, so the whole request waited on it.
The rule I kept: give that call a 3 second limit. When it expires, run the full-text branch alone and answer from that. A weaker answer on time is better than a good one after thirteen seconds. The same rule applies to the other stages: the SQL gets 2 seconds through statement_timeout, with a cheaper query as the fallback.
How you implement the limit matters. My lessons log has an entry, BL-267, for a timeout written as Promise.race against a setTimeout. That stops the caller from waiting, but the request to the provider keeps running, still costs money and can write its result later on top of a retry. A limit has to cancel the work: create an AbortController, pass its signal to fetch, and abort when time is up.
async function embedQuestion(text: string, ms = 3000): Promise<number[] | null> {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), ms);
try {
const res = await fetch(EMBED_URL, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ input: text }),
signal: ctrl.signal,
});
if (!res.ok) return null;
const body = await res.json();
return body.data[0].embedding;
} catch {
return null; // timed out or failed: caller runs full-text only
} finally {
clearTimeout(timer);
}
}
A related lesson, BL-730, found that a wrapper library did not pass the signal down to its HTTP call, so the deadline never fired. Pass the signal, then prove it with a test against a server that hangs on purpose.
What I have not verified
The project’s code is not in the repository I was working from while writing this. The dates and timings come from the retrieval notes and lessons log I keep for it: the 15 August index loss, the 11.4 second embedding call, BL-267 and BL-730. I did not re-run the query, the migration or the timeout while writing. The SQL and the TypeScript are new illustrations written to show the pattern, and they have not been run against a database. Check the column names, the immutable_unaccent definition and your pgvector version before borrowing any of it.