Hybrid Email Search
Watch what people type into a mail search box and you'll see three different questions wearing the same clothes. One person types iv, because that's how the tax line on their invoices starts, and wants every message that contains those two letters. Another types factura and wants the invoices, best first. A third types something like "the email about renewing the flat" and wants a message that never uses the word renew.
No single index answers all three. In Mailingest, my mail platform, the search runs three of them over the same messages, and each one hands back its own ranked list. That's where the real problem starts. The three lists don't agree on what a score is, so you can't just add them up. This post is about how they're combined anyway, and the small set of rules around that combination that decides what you see first.
Three lists that disagree on what a number is
Each message gets one search row in Postgres: the subject, the addresses and the body, folded to lowercase without accents, so busqueda finds Búsqueda. Three indexes sit on that row.
- BM25: Okapi BM25 through ParadeDB's
pg_searchextension. It scores whole words: rare words weigh more, a word repeated in a short message weighs more than in a long one. The score has no upper bound and no fixed meaning. - Trigrams: a GIN index from pg_trgm. It answers "does this message contain this string", anywhere, even inside a word. It has no score at all, only yes or no.
- Vectors: an embedding of each message from OpenAI's text-embedding-3-small, stored with pgvector. It gives a cosine between the query and the message. This one is optional per account, because every message costs a call to the embedding API.
A BM25 score of 14.2 next to a cosine of 0.41 next to "yes, received on Tuesday" isn't a sum anyone can defend. You could normalise each list to 0 to 1 and add them, but then the result depends on the spread of each list for this particular query: one outlier in BM25 squashes every other message in that list towards zero.
The word list
BM25 is the list that knows about words, so it carries most of the relevance. The index splits text on Unicode word boundaries and folds accents, and it has no stemmer on purpose: mail arrives in every language, and a Spanish stemmer would mangle an English invoice. This is the index as it stands today:
CREATE INDEX idx_email_search_bm25 ON email_search USING bm25
(email_id, ((subject)::pdb.unicode_words('ascii_folding=true')),
((addresses)::pdb.unicode_words('ascii_folding=true')),
((body)::pdb.unicode_words('ascii_folding=true')),
((attachment_names)::pdb.unicode_words('ascii_folding=true')),
organization_id, received_at, level) WITH (key_field = email_id);The account, the date and the search level live inside the index, so the filter "this account, these dates" runs inside the scan instead of after it. The text of attachments has a BM25 index of its own, one copy per file, and a message scores the best of its own row and its files.
Each field has a weight. A word in the subject counts three times, a word in the addresses or an attachment's name twice, a word in the body once:
pub(super) const OWN_FIELDS: &[(&str, &str)] = &[
("s.subject", "3"),
("s.addresses", "2"),
("s.attachment_names", "2"),
("s.body", "1"),
];And every word of the query has to be there, in one of those fields. factura pago is not "invoice or payment", it's both. A word like fac-2026 splits into two tokens, fac and 2026, and both must sit in the same field, which is what pg_search's &&& operator checks.
There's no stopword list and no synonym table. "Word list" here means exactly this: the BM25 list, ranked by how well the words match.
What goes into that body matters as much as how it's scored. Every reply in a thread carries the previous messages quoted underneath, so a word from the first message is also in the second, the third and the tenth. Searching it returned the whole thread, and the index grew with the square of the conversation. The indexed body is now only what the sender wrote: quoted lines, attributions like "On Mon, Ana wrote:", Outlook's history block and the signature are stripped before indexing (forwards are kept whole, since the forwarded message may not be in the account). On a synthetic corpus of 300,000 messages, the indexed body text went from 398 MB to 98 MB, and the table plus its indexes from 756 MB to 356 MB. The stored message doesn't change, only its search row.
Trigrams, the list that only knows "contains"
IMAP, which is what phone mail clients speak, defines SEARCH TEXT and BODY as substring matches (RFC 3501). A two-letter string must match. BM25 can't do that, because it only knows whole words. So the second index is a trigram GIN over the whole document, with the account in front so a search reads only its own account's entries.
It's an obvious question whether one index could do both jobs. pg_search has an ngram tokenizer that would make BM25 answer substrings too, and then the GIN could go. I measured it on the account with 120,471 messages in that corpus:
The ngram index is exact from three letters and about twice as fast, but it's 2.4 times the size and blind to one- and two-letter strings, which IMAP must find. The trigram stayed.
Those numbers come from a CI job that runs only the search benchmarks: the same ParadeDB 18 image as production, 6 CPUs and 11.7 GB of memory, over 300,000 synthetic messages in 100 accounts (one account holds 40% of them). The corpus mixes Spanish and English with Zipf-distributed words, invoice numbers and names, and threads of up to 12 messages quoted the way Gmail, Outlook and Apple Mail quote. Latencies are p50 and p99 of 10 to 30 warm runs. Every database figure in this post comes from that setup unless I say otherwise.
The trigram list has no score, so its order is the one a mail client would use: newest first. That's the detail that makes the fusion below work.
Ranks instead of scores
The answer to "how do you add numbers that mean different things" is: don't. Reciprocal Rank Fusion (Cormack, Clarke and Büttcher, 2009) throws the scores away and keeps only each message's position in each list. A message at rank r in a list gets 1 / (k + r) from it, and its final score is the sum over every list it appears in. With k = 60, the paper's constant, the first place is worth 1/61, the tenth 1/70, the two-hundredth 1/260. Being near the top helps, but not by orders of magnitude, so a message that several lists agree on beats one that a single list loves.
Mailingest uses a weighted version: BM25 counts 1, the trigram list 0.7, the vectors 1. Each list stops at 200. Here's the arithmetic for three made-up messages, to show the shape:
Because the trigram list is ordered by date, its 0.7 is a recency pull: among messages BM25 rates about the same, the newer one wins. Set it to 1 and recency would weigh as much as relevance. Set it to 0 and the order would be BM25's alone, where a newsletter that repeats a word ten times outranks the one-line invoice you were looking for.
The fusion is a few lines of SQL inside the one statement that answers a page:
q.push(
", lists AS (SELECT id, 1.0::float8 AS w, r FROM bm25 \
UNION ALL SELECT id, 0.7, r FROM trgm",
);
if with_meaning {
q.push(" UNION ALL SELECT id, 1.0, r FROM vec");
}
q.push(format!(
"), fused AS (SELECT id, SUM(w / ({RRF_K} + r)) AS score FROM lists GROUP BY id), \
hits AS (SELECT i.email_id AS hit_id, f.score AS hit_score, i.received_at AS hit_at, \
COALESCE(i.thread_id, i.email_id) AS hit_conv, "
));Each list is at most 200 ids, so the fusion joins at most 600 before it reads a single index row, and none of it leaves Postgres: the process only receives the rows of the page.
Meaning gets a vote, not a veto
The vector list has the same weight as BM25, but less power. It can only reorder what the words already found. The SQL keeps a vector hit only if it's in the union of the other two lists:
q.push(
", lexical AS (SELECT id FROM bm25 UNION SELECT id FROM trgm), \
vec AS (SELECT v.id, v.r FROM UNNEST(",
)
.push_bind(meaning)
.push(
"::uuid[]) WITH ORDINALITY AS v(id, r) \
WHERE v.id IN (SELECT id FROM lexical) \
OR (NOT EXISTS (SELECT 1 FROM lexical) AND v.id = ANY(",
)
.push_bind(find.standout.to_vec())
.push("::uuid[])))");The reason is a property of nearest-neighbour search that's easy to forget: there's always a nearest neighbour. Type nonsense and the vector index still returns its 200 closest messages, with confident-looking cosines. If those joined the fusion freely, every search would come back padded with messages that are merely the least far away.
The second branch of that WHERE handles the case the words can't: when BM25 and trigrams find nothing at all. Then the vectors may offer results alone, but only the ones that stand out. A fixed threshold doesn't work for that. The design notes record a short message scoring 0.36 against a related query and 0.33 against an unrelated one, too close to draw a line between. So the cut is relative to the account's own candidates: a cosine at least two standard deviations above their mean, with at least 20 candidates to measure the spread from.
pub const STANDOUT_SIGMAS: f32 = 2.0;
pub const MIN_FOR_STANDOUT: u32 = 20;
// in Best::into_neighbours
let bar = (self.seen >= MIN_FOR_STANDOUT).then(|| {
let sigma = (self.m2 / f64::from(self.seen)).sqrt();
self.mean + f64::from(STANDOUT_SIGMAS) * sigma
});The mean and the spread are kept with Welford's running variance while the candidates stream in, so nothing holds all of them in memory. The candidates themselves come from the trick in Vector Search on S3: one sign bit per dimension, nearest by Hamming distance in an HNSW graph, then a rerank by cosine with one byte per dimension. That's 1,728 bytes per message.
I also tried shrinking the vectors to 256 dimensions. It couldn't be tested with the production model (there's no embeddings key locally), so it used an open model with the same nesting property, nomic-embed-text-v1.5, on 999 labelled messages and 199 paraphrased queries, through the same bits-then-int8 pipeline. Recall@10 went from 89.9% at the full 768 dimensions to 83.4% at 256. The bar was losing at most 2 points, so the vectors stayed full size.
Newest first, then relevant
RRF orders messages that are about equally recent. It doesn't decide the page on its own. People search mail mostly for something recent, so the hits are first sorted into time buckets counted back from the moment the search started, and RRF only orders within a bucket:
This is a real trade, and it cuts the other way sometimes. The best match for contrato alquiler might be the lease signed two years ago, and it will sit below a passing mention of the word in last week's mail. I took that side because a mail search that surfaces old mail first feels broken in daily use, and an old message is one before: away (the query language is Gmail's, with from:, before:, has:attachment and the rest).
It's also one statement per page over the whole history. A first version read one block of time per statement and widened it when the block came up short, and on narrow searches it was up to 30 times slower: factura -pago took 2,995 ms, against 199 ms for the single-statement search before the change. With the buckets inside one statement it takes 38 ms. Those runs used the end-to-end benchmark, a smaller setup on the same CI job: 120,000 messages in the real migrated tables, 100 accounts, the big one holding 40%, p50 of 10 runs with pages of 20.
Typos only when nothing matches
The typo story started with a real complaint. A PDF said "Local Comercial", and Gmail on an iPhone searched over IMAP for TEXT "Local Comercil". Nothing came back.
Fuzzy matching inside the normal search would fix that and break everything else: a search for casa would also return caso, and nobody asked for that. So typos are a fallback with one rule, shared by IMAP and the API: search exactly first, and only if that finds nothing, search once more with typos.
In the API the retry loosens both lists. In BM25, a word of five letters or more may be one edit away, a word of eight or more two, and two swapped letters count as one edit. A word with digits never gets BM25 typos:
fn typo_distance(word: &str) -> Option<u8> {
let chars = word.chars().count();
(chars >= 5 && word.chars().all(char::is_alphabetic)).then_some(if chars >= 8 { 2 } else { 1 })
}In the trigram list (and in IMAP's TEXT and BODY), each word of four letters or more is matched against whole words by pg_trgm's strict word similarity, with the threshold pinned at 0.5. That number came from real pairs. A missing or extra letter in a word of seven or more letters passes: comercil against comercial scores 0.58, alquier 0.55, facturra 0.70. Short different words stay apart: para and pero score 0.11, casa and caso 0.43. Below 0.5, distinct words started to mix (este and esta, 0.43). Swapped letters mostly fail here (0.33 to 0.43), which is exactly the case BM25's edit distance covers, so the two lists catch different typos.
The bug that waited for the sixth search
One failure only appeared in the benchmark, on the sixth repetition of the same query. Postgres plans a prepared statement with its real values for the first five executions, and after that may switch to a generic plan that works for any value. With a generic plan, the right-hand side of &&& is a parameter instead of text, and pg_search refuses the query: "The right-hand side of the &&& operator must be a text or text array value". Production kept its statements prepared, so a search repeated on the same connection could start failing for no visible reason.
The fix is one call, and the comment explains it better than I can:
// Not kept prepared: after five runs of one shape Postgres may plan it once
// for any values, and pg_search then refuses `&&&` with a parameter for its
// right side ("must be a text or text array value"). Planned each time with
// its words, it is answered inside the index.
let mut hits: Vec<T> = q
.build_query_as::<T>()
.persistent(false)
.fetch_all(pool)
.await?;persistent(false) tells sqlx not to cache the statement, so every search is planned with its own words. Planning each time costs a little. A search that fails on its sixth run costs more.
What the fusion buys
All of this is on Mailingest's main branch: the RRF fusion since October 26, the time buckets and the prepared-statement fix since October 29. In the end-to-end benchmark (120,000 messages), the full search for factura returns a page in 40 ms at p50 and 55 ms at p99. On the 120,471-message account of the larger corpus, the BM25 list alone answers in 10 ms at p50.
So the trade is this. Each index does the one thing it's good at: BM25 judges words, trigrams answer "contains" and keep the newest close, and vectors notice when two messages mean the same thing. Mailingest never asks them to agree on what a score means. It asks only where each one would put a message, and lets agreement win. What that gives up is any idea of how much better the first result is than the second. RRF knows the order, not the distance, and for a mail search, where you scan a short page and click, the order turned out to be the part that matters.
References
Related articles
Type a sentence into a table's search box and get its filters back as chips, the first in a third of a second, from a model that only picks real values.
Virtualizing 350,000 rows is the easy part. The counts and filter lists around them took seconds, until Postgres started saying which columns changed.