---
title: Hybrid Email Search
date: '2026-11-08'
description: 'BM25 scores words, trigrams only say yes or no, vectors give a cosine. Mailingest throws the numbers away and fuses the three lists by rank.'
author: Pablo Fernandez
tags:
  - Search
  - BM25
  - Postgres
  - RRF
  - Mailingest
source: 'https://www.pablofr.com/blog/three-indexes-one-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](/blog/giving-an-inbox-to-each-agent), 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](https://en.wikipedia.org/wiki/Okapi_BM25) through [ParadeDB](https://www.paradedb.com/docs/start/introduction)'s `pg_search` extension. 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](https://www.postgresql.org/docs/current/pgtrgm.html). 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](https://developers.openai.com/api/docs/guides/embeddings), stored with [pgvector](https://github.com/pgvector/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.

```
                       ┌──▶  BM25     ──▶  score 0 … ∞, by relevance
                       │
   q = "factura"  ─────┼──▶  trigram  ──▶  no score, newest first
                       │
                       └──▶  vectors  ──▶  cosine -1 … 1, by meaning
```

*One query, three indexes, three ranked lists whose numbers can't be compared.*

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:

```sql:migrations/601_tenant_organization_id.sql
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:

```rust:crates/db/src/search/find.rs
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](https://datatracker.ietf.org/doc/html/rfc3501)). A two-letter string must match. BM25 can't do that, because it only knows whole words. So the second index is a [trigram](https://en.wikipedia.org/wiki/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:

| | Trigram GIN | BM25 ngram(3,3) |
|---|---|---|
| `factura`, matches | 11,370 | 11,370 |
| `ncia` (inside a word), matches | 18,011 | 18,011 |
| `iv` (two letters), matches | 37,747 | 0 |
| `factura`, p50 / p99 | 66 / 102 ms | 26 / 48 ms |
| Index size, 300,000 messages | 118.8 MB | 284.1 MB |

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](https://cormack.uwaterloo.ca/cormacksigir09-rrf.pdf) (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:

```
               BM25 (1)    trigram (0.7)   fused score
   message A   rank 1      not found       1/61           = 0.0164
   message B   rank 5      rank 2          1/65 + 0.7/62  = 0.0267
   message C   not found   rank 1          0.7/61         = 0.0115
```

*Weighted RRF with k = 60: the message both lists found beats the top of either list alone.*

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:

```rust:crates/db/src/search/find.rs /RRF_K/
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:

```rust:crates/db/src/search/find.rs
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.

```rust:crates/db/src/embeddings.rs
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](https://en.wikipedia.org/wiki/Algorithms_for_calculating_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](/blog/vector-search-on-object-storage): one sign bit per dimension, nearest by [Hamming distance](https://en.wikipedia.org/wiki/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](https://huggingface.co/nomic-ai/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:

```
   now ◀─────────────────────────────────────────────────────────── past
   │  7 days  │ 30 days  │ 90 days  │  1 year  │ 3 years  │  the rest  │
   │ bucket 0 │ bucket 1 │ bucket 2 │ bucket 3 │ bucket 4 │  bucket 5  │

   ORDER BY bucket, fused score DESC, received_at DESC
```

*A page is sorted by bucket first and by fused score second: a weak match from this week comes before a strong one from last year.*

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.

```
   query ──▶ exact search ──▶ hits? ── yes ──▶ page
                                │
                                no
                                ▼
                       search with typos ──▶ page
```

*The typo pass runs only on an empty result, so an exact hit never comes with near ones.*

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:

```rust:crates/db/src/search/find.rs
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](https://www.postgresql.org/docs/current/sql-prepare.html) 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:

```rust:crates/db/src/search/find.rs
// 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)`](https://docs.rs/sqlx/latest/sqlx/query/struct.Query.html) 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

- [Cormack, Clarke, Büttcher: Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods (2009)](https://cormack.uwaterloo.ca/cormacksigir09-rrf.pdf)
- [Wikipedia: Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25)
- [ParadeDB documentation](https://www.paradedb.com/docs/start/introduction)
- [PostgreSQL: pg_trgm](https://www.postgresql.org/docs/current/pgtrgm.html)
- [PostgreSQL: PREPARE (custom and generic plans)](https://www.postgresql.org/docs/current/sql-prepare.html)
- [pgvector](https://github.com/pgvector/pgvector)
- [OpenAI: vector embeddings](https://developers.openai.com/api/docs/guides/embeddings)
- [RFC 3501: IMAP4rev1](https://datatracker.ietf.org/doc/html/rfc3501)
