Ask a document Q&A system "What does error code E-17 mean?" and you want the page that literally says E-17. Ask it "How long is the warranty?" and you want the warranty page, even if the word "long" appears nowhere on it.
Those two questions pull in opposite directions. Lexical search (full-text and trigrams) is great at exact words, codes and names, and bad at paraphrases. Vector search finds passages with similar meaning, but it can miss an exact code or name. So in my book I don't pick one. The retrieval step runs three searches in PostgreSQL, merges the candidates and ranks them with one formula you can read.
This post walks through that step: the three queries, the merge, the weighted score, and the per-document cap at the end.
Three searches, one transaction
Each search only has to produce candidate IDs. Scoring happens later.
VEC_SQL = """SELECT id FROM chunks ORDER BY embedding <=> %(qv)s::vector LIMIT %(n)s""" FTS_SQL = """SELECT id FROM chunks WHERE tsv @@ websearch_to_tsquery('english', %(terms)s) ORDER BY ts_rank_cd( tsv, websearch_to_tsquery('english', %(terms)s), 32 ) DESC LIMIT %(n)s""" # %% is the pg_trgm % operator: in psycopg, % starts a placeholder. TRGM_SQL = """SELECT id FROM chunks WHERE chunk_text %% %(q)s ORDER BY similarity(chunk_text, %(q)s) DESC LIMIT %(n)s""" The limits are 30 for vector, 30 for full-text and 20 for trigrams, all configurable. A few details in there are easy to get wrong, so here they are.
Vector: <=> is cosine distance. The project this book is based on used <-> (L2 distance) while its index was declared with vector_cosine_ops. That index is built for <=>, so it shouldn't be expected to help an <-> query. In the book I switched to cosine on both sides so the operator and the index match.
Full-text: the keywords are joined with spaces, and websearch_to_tsquery treats spaces as AND. That's strict on purpose. A chunk that misses one keyword can still get in through the vector or trigram query, and that's the whole reason to combine them.
Trigrams: I filter with the % operator, not with similarity(chunk_text, q) >= 0.10. A GIN trigram index supports %. It doesn't support a function call in WHERE. My first version used the function call and stayed a sequential scan even with sequential scans disabled. The % operator uses pg_trgm.similarity_threshold, whose default is 0.3, so I set it to 0.10 for the current transaction only:
with conn.transaction(): conn.execute( "SELECT set_config(" "'pg_trgm.similarity_threshold', %s, true)", (str(TRGM_MIN),), ) for sql, n in ((VEC_SQL, VEC_LIMIT), (FTS_SQL, FTS_LIMIT), (TRGM_SQL, TRGM_LIMIT)): ids.update(row[0] for row in conn.execute(sql, {**params, "n": n})) The true in set_config is what limits it to the transaction, which means the setting and the queries have to run in the same transaction on the same connection. Even then, the planner decides. In the tested environment it used the index for a selective query and picked a full scan when most rows matched. Writing % makes the index usable. It doesn't force it.
The indexes behind the lexical side are plain GIN:
CREATE INDEX IF NOT EXISTS chunks_tsv_gin ON chunks USING gin (tsv); CREATE INDEX IF NOT EXISTS chunks_text_trgm ON chunks USING gin (chunk_text gin_trgm_ops); Give every candidate all three signals
After the three queries you have up to 80 distinct chunk IDs. The original implementation scored each candidate only with the signals from the queries that returned it. A chunk found only by full-text got a vector score of zero, even though its embedding was sitting right there in the table.
I didn't like that, so the teaching version runs one more query that computes all three scores for every candidate:
SELECT c.id, d.filename, c.page_number, c.chunk_text, 1 - (c.embedding <=> %(qv)s::vector) AS vec, ts_rank_cd( c.tsv, websearch_to_tsquery('english', %(terms)s), 32 ) AS fts, similarity(c.chunk_text, %(q)s) AS trgm FROM chunks c JOIN documents d ON d.id = c.document_id WHERE c.id = ANY(%(ids)s) It only touches the candidates, and it removes a source of weird rankings that depend on which query happened to find a chunk first.
The weighted score
This is a weighted sum, not reciprocal rank fusion:
final = ( 1.00 * vec + 0.85 * fts + 0.35 * trgm + 1.20 * bonus - 0.80 * penalty ) The weights are the real project's defaults. I kept them as a starting point, not as a recommendation. The vector score and the lexical rules in the book differ from the original, so the weights need to be checked against an evaluation set. And the result isn't a probability. It's only useful for ordering and for comparing against a threshold you calibrated yourself.
The bonus and penalty come from a small Python function that looks at the chunk text:
def lexical_signals(text, question): body = text.lower() kws = keywords(question) found = [k for k in kws if re.search(rf"\b{re.escape(k)}\b", body)] strong = strong_signals(question) strong_found = any(s in body for s in strong) matched_any = bool(found) or strong_found bonus = (len(found) / len(kws) if kws else 0.0) + ( 0.5 if strong_found else 0.0 ) if matched_any: penalty = 0.0 else: penalty = 1.0 if strong else 0.5 return bonus, penalty, matched_any The bonus is the share of keywords found, plus 0.5 when a "strong signal" shows up in the chunk. A strong signal is a quoted phrase or a token with a digit in it, like E-17 or INV-2041. The penalty is 1.0 when the question has a strong signal and the chunk has no lexical match at all, and 0.5 when there's no strong signal and still no match. The original project had many more categories (menu paths, acronyms, identifiers, caps per category). I kept two rules because I wanted readers to be able to hold the whole formula in their head.
Reading a result
Since each result carries every part of its score, you can see why it ranked where it did. Here's "How long is the warranty?" from the book's test run:
| Chunk | vec | fts | trgm | bonus | penalty | final |
|---|---|---|---|---|---|---|
| policy.pdf, page 2 (warranty) | 0.41 | 0.00 | 0.15 | 0.50 | 0.0 | 1.06 |
| policy.pdf, page 3 (returns) | 0.12 | 0.00 | 0.05 | 0.00 | 0.5 | −0.26 |
Full-text gave nothing to either chunk, because "long" isn't in the text and the terms are ANDed. The right page still came first from the other signals, and the page with no matching words got pushed below zero by the penalty.
One caveat: that test used a stand-in embedding function (a deterministic word-hashing vector with no semantic understanding), so the vec column shows the structure of the score, not what real embeddings would produce.
The per-document cap
The last step keeps one long document from filling the whole context:
selected, per_doc = [], {} for r in results: # already sorted by final, descending if per_doc.get(r["filename"], 0) < MAX_PER_DOC: selected.append(r) per_doc[r["filename"]] = per_doc.get(r["filename"], 0) + 1 if len(selected) == MAX_RESULTS: break Up to 12 results, at most 4 per document. Without it, one long manual with many similar pages could take every slot and push out a shorter document that answers the question better.
Limitations
- The threshold isn't calibrated. The gate that runs after this step uses
HYBRID_MIN_SCOREwith a default of 0.9, and that number is a placeholder. The book hasn't run the evaluation with real OpenAI embeddings, so there's no calibrated value to give you. The original project's 0.45 doesn't carry over either, because the formula is different. - Every search costs an embedding call. The question is embedded before any query runs, so even a question the gate later rejects has already paid for one.
- Word boundaries bite. In the test run, "How many days do I have to return an item?" found the right page but scored too low to pass the gate. The keyword "return" doesn't match "Returns" as a whole word, and full-text needed every keyword. The fix belongs in the lexical rules, not in lowering the threshold until that one case passes.
- Language matters on both sides. The stored
tsvand every query must use the same text-search configuration. If one side saysenglishand the otherportuguese, words get normalized differently and stop matching.
What I'd take from this
- Run lexical and vector search together and let one explicit formula decide. When a ranking looks wrong, you can read the columns and see which part caused it.
- After merging, compute every signal for every candidate.
- Write trigram filters with
%and a transaction-local threshold if you want the GIN index to be usable at all. - Treat borrowed weights and thresholds as placeholders until a small evaluation set with real questions says otherwise.
- Cap results per document before they go to the model.
I'm Daniel Basseda. I work in database administration and technical support. This post comes from my book RAG on Postgres: Building a Document Q&A System That Survives Real-World PDFs, which builds a small document Q&A system on PostgreSQL: OCR for scanned PDFs, pgvector, full-text and trigram search, hybrid retrieval and cited answers. There's also an e-book + code bundle with the ready-to-run project and its tests.


