tutorials
Full-text email search with SQLite FTS5
November 18, 2026

An inbox you cannot search is a log. You can scroll it, you can grep a single message, but you cannot ask it questions. FTS5 turns a pile of stored mail into something you query.
If you are storing email in SQLite or Cloudflare D1, you eventually need search, and the instinct is to reach for WHERE body LIKE '%invoice%'. That works on a hundred rows and falls over on a hundred thousand: it scans every row, it cannot rank, it has no concept of word stems, and it lights your database CPU on fire. The correct tool has been sitting inside SQLite the whole time. It is FTS5, the full-text search extension, and email is close to its ideal workload: lots of text, read-heavy, and you want relevance plus snippets, not just a boolean hit.
This is a complete FTS5 tutorial that happens to use email as the worked example. By the end you will have a virtual table, triggers that keep it fresh, ranked queries with result snippets, and the same thing running in D1 at the edge. Everything here is close to what Tinbox runs in production, so the code is real, including the parts that are annoying.
Why FTS5, and why does it fit D1?
FTS5 is the right answer because it is built into SQLite, so it needs no external search service, no separate process, and no second datastore to keep in sync over the network. You create a virtual table, you query it with SQL, and the index lives in the same database file (or the same D1 database) as your mail.
That last point is the whole reason it fits Cloudflare. D1 is SQLite, and it ships the FTS5 extension. So a CREATE VIRTUAL TABLE ... USING fts5(...), a MATCH query, bm25() ranking, and snippet() all run inside your D1 database with zero additional infrastructure. Compare that to bolting Elasticsearch, Algolia, or Typesense onto an edge app: you are now paying a second vendor, shipping your mail to them, and accepting a replication lag. FTS5 keeps search on-platform, which is the entire premise of treating your inbox as a queryable database you own. It is also one of the things to know before you put email in Cloudflare D1, where the index, its triggers, and storage cost all land on the same database as your mail.
The honest tradeoff: FTS5 is keyword search, not semantic search. bm25() ranking is good, but it matches words and stems, not meaning. If you ask for "money owed" it will not surface a message that says "outstanding balance" unless the stemmer connects them. That is fine for an inbox search box, where users type words they remember seeing. For meaning-based retrieval you would layer a vector index on top, which is a different article (retrieval-augmented answers over your archive covers that direction, and the things RAG over your email unlocks covers why you would bother). FTS5 is the keyword foundation, and most of the time it is all you need.
How do you model email for full-text search?
Index the columns people search by (subject, sender, body) and store everything else normally. Search runs over message content, so the FTS table mirrors a few text columns from your messages table rather than duplicating the whole row.
A useful distinction: there are columns you index (FTS tokenizes them so they are searchable) and columns you only store alongside (FTS keeps the value but does not tokenize it, marked UNINDEXED). For an inbox you index subject, the sender address and name, and the body text. You store the message_id and inbox_id unindexed so a search can scope to one mailbox and join back to the full message row.
A real-world note on schema: in Tinbox the messages table has no dedicated "label" or "AI category" columns. There is the message content (subject, from, body, preview) plus an extra JSON field for everything else. Search runs over the content columns, not over invented metadata columns. So when you model your own FTS table, index the text that actually exists on the message, and resist the urge to add speculative columns the index has to keep fresh.
How do you create the FTS5 virtual table?
Run CREATE VIRTUAL TABLE ... USING fts5(...) listing the columns to index, and choose a tokenizer. For email, porter unicode61 is the right default: unicode61 case-folds and strips accents, and porter stems words so "invoices" matches "invoice".
There are two shapes, and choosing between them is the one real design decision.
Shape A: external-content table. If your messages table has an integer rowid primary key, point the FTS table at it with content='messages' and content_rowid='id'. FTS5 then stores only the index, not a second copy of the body, and reads the original text from messages when it needs it. This is the textbook, storage-efficient pattern:
CREATE VIRTUAL TABLE messages_fts USING fts5(
subject,
from_addr,
body,
content='messages', -- external content: don't duplicate the body
content_rowid='id', -- requires an INTEGER primary key on messages
tokenize='porter unicode61'
);
Shape B: standalone table. If your primary key is a text id (a ULID, a UUID, anything non-integer), the external-content trick does not fit cleanly: external-content tables key on the integer rowid, and a text id does not map onto that. So you make a standalone FTS table that mirrors the searchable columns plus the id as an UNINDEXED column. This is exactly what Tinbox does, because message ids are text ULIDs:
CREATE VIRTUAL TABLE messages_fts USING fts5(
message_id UNINDEXED, -- text ULID, stored for the join-back
inbox_id UNINDEXED, -- store so we can scope a search to one mailbox
subject,
from_addr,
from_name,
body,
tokenize='porter unicode61'
);
The cost of Shape B is that the body is stored twice (once in messages, once in the index). The benefit is that it works with text primary keys and the triggers are simpler to reason about. Pick A if you have integer ids and care about storage; pick B if you have text ids, which on the edge you very often do.
How do you keep the FTS5 index in sync?
Add three triggers on the source table so every write mirrors into the index: AFTER INSERT adds the row, AFTER DELETE removes it, and AFTER UPDATE deletes then re-inserts. This is the classic FTS5 trigger trio, and without it the index silently goes stale.
For a standalone table (Shape B), the triggers copy the searchable columns explicitly:
CREATE TRIGGER messages_fts_ai AFTER INSERT ON messages BEGIN
INSERT INTO messages_fts (message_id, inbox_id, subject, from_addr, from_name, body)
VALUES (
new.id, new.inbox_id, new.subject, new.from_addr,
COALESCE(new.from_name, ''),
COALESCE(new.body_text, new.body_preview, '')
);
END;
CREATE TRIGGER messages_fts_ad AFTER DELETE ON messages BEGIN
DELETE FROM messages_fts WHERE message_id = old.id;
END;
CREATE TRIGGER messages_fts_au AFTER UPDATE ON messages BEGIN
DELETE FROM messages_fts WHERE message_id = old.id;
INSERT INTO messages_fts (message_id, inbox_id, subject, from_addr, from_name, body)
VALUES (
new.id, new.inbox_id, new.subject, new.from_addr,
COALESCE(new.from_name, ''),
COALESCE(new.body_text, new.body_preview, '')
);
END;
Two details that bite people. First, COALESCE the nullable columns: if from_name or body_text is NULL, inserting NULL into an FTS column is not what you want, so fall back to an empty string (and fall back from body_text to body_preview so a message with only a preview is still searchable). Second, for an external-content table (Shape A) the delete trigger looks different: you do not DELETE FROM messages_fts WHERE ..., you insert a special 'delete' command row, because external-content tables track deletions through FTS5's delete syntax. Standalone tables, by contrast, are just plain DELETE statements, which is part of why they are easier to reason about.
Now backfill anything that existed before the triggers did. On a fresh database this is a no-op; on an existing one it is the line that populates the index:
INSERT INTO messages_fts (message_id, inbox_id, subject, from_addr, from_name, body)
SELECT id, inbox_id, subject, from_addr, COALESCE(from_name, ''),
COALESCE(body_text, body_preview, '')
FROM messages;
How do you query, rank, and show snippets?
Query with MATCH, rank with bm25(), and build result previews with snippet() or highlight(). A complete search query for email looks like this:
SELECT
message_id,
subject,
snippet(messages_fts, 5, '<mark>', '</mark>', '…', 12) AS preview,
bm25(messages_fts, 10.0, 4.0, 1.0) AS score
FROM messages_fts
WHERE messages_fts MATCH ?
ORDER BY score -- bm25: lower (more negative) is better
LIMIT 20;
What each piece does:
MATCH ?runs the full-text query. The bound parameter is the FTS query expression, not a raw user string (more on sanitizing that below).bm25(messages_fts, 10.0, 4.0, 1.0)ranks results. The extra numbers are per-column weights in column order, here makingsubjectcount 10x,from_addr4x, andbody1x. bm25 returns a score where lower is more relevant, so youORDER BY scoreascending.snippet(messages_fts, 5, '<mark>', '</mark>', '…', 12)extracts a preview from column index 5 (body), wraps matched terms in<mark>, uses…as the ellipsis, and aims for about 12 tokens. That gives you the "…your invoice is attached…" preview UX for free.
A few query patterns worth knowing:
-- Prefix / as-you-type search: trailing * matches word stems
WHERE messages_fts MATCH 'invoi*';
-- Phrase search: double quotes match adjacent words in order
WHERE messages_fts MATCH '"past due"';
-- Column-scoped: only match the subject
WHERE messages_fts MATCH 'subject:refund';
-- Boolean: AND is implicit, OR and NOT are explicit
WHERE messages_fts MATCH 'invoice NOT draft';
One important reality for email specifically: relevance is often not what the user wants. When someone searches their inbox, "newest first" usually beats "most relevant". So in practice you may run the MATCH to find the hits but ORDER BY the message date instead of bm25(). Because date typically lives on messages and not on the FTS row, that means joining back to messages to order. Which leads to how this works on D1.
How do you run FTS5 search on D1 specifically?
Apply the FTS DDL as a hand-written migration with wrangler d1 execute, then call the query from a Worker through the D1 binding. The catch is that migration tools cannot generate virtual-table DDL, so you author it by hand.
drizzle-kit, Prisma, and most schema tools have no model for CREATE VIRTUAL TABLE, so the FTS table and its triggers go in a hand-written .sql migration that you apply directly:
wrangler d1 execute tinbox-db --file=./migrations/0001_messages_fts.sql --remote
Then the search itself, from a Worker. Note the two-step shape: D1 (and FTS5 in general) cannot order an FTS-only query by a column that lives on messages, so you run MATCH to get the matching ids in date order via a join, then hydrate the full rows:
// env.DB is the D1 binding from wrangler.jsonc
export async function searchInbox(env: Env, rawQuery: string, inboxId: string) {
const match = toFtsMatch(rawQuery);
if (!match) return [];
// Step 1: matching ids, newest first. Date is on `messages`, not the FTS row,
// so we join and order there.
const { results: idRows } = await env.DB.prepare(
`SELECT m.id AS id
FROM messages_fts f
JOIN messages m ON m.id = f.message_id
WHERE messages_fts MATCH ?1 AND m.inbox_id = ?2
ORDER BY m.date DESC
LIMIT 20`,
)
.bind(match, inboxId)
.all<{ id: string }>();
const ids = idRows.map((r) => r.id);
if (ids.length === 0) return [];
// Step 2: hydrate full rows, preserving the FTS order.
const placeholders = ids.map(() => "?").join(",");
const { results } = await env.DB.prepare(
`SELECT * FROM messages WHERE id IN (${placeholders})`,
)
.bind(...ids)
.all();
const byId = new Map(results.map((r: any) => [r.id, r]));
return ids.map((id) => byId.get(id)).filter(Boolean);
}
And the sanitizer, which is not optional, because raw user input breaks FTS5:
// FTS5 treats " * : ^ ( ) - as operators. An email address or a colon in the
// query becomes a syntax error unless we quote each token as a phrase.
export function toFtsMatch(query: string): string {
const tokens = (query ?? "")
.toLowerCase()
.split(/\s+/)
.map((t) => t.replace(/["'^*:()]/g, "").replace(/[^\p{L}\p{N}@._-]/gu, ""))
.map((t) => t.trim())
.filter(Boolean);
if (tokens.length === 0) return "";
// Quote each token; prefix-match the LAST token for as-you-type search.
return tokens
.map((t, i) => (i === tokens.length - 1 ? `"${t}"*` : `"${t}"`))
.join(" ");
}
D1-specific honesty: FTS5 works in D1, but you bind parameters with D1's ?N positional placeholders and read results through .all(), which lines up with the better-sqlite3 driver people use for local tests, so the same SQL validates in both places. Multi-statement DDL needs to be applied as a file (the --file flag), not as a single prepare().run(), because virtual-table creation plus three triggers is several statements. And there is no "rebuild on schema change" automation: if you change which columns you index, you drop and recreate the FTS table and re-run the backfill yourself.
What are the FTS5 failure modes to watch for?
The four that will actually bite you are a stale index, the wrong tokenizer, unsanitized special characters, and an empty index you forgot to populate. Here is each one, and the fix.
Stale index (missing trigger). You insert a message, search for it, and get nothing. The index never heard about the insert.
sqlite> INSERT INTO messages (id, subject, body_text) VALUES ('m1', 'Invoice 204', 'amount due');
sqlite> SELECT message_id FROM messages_fts WHERE messages_fts MATCH 'invoice';
-- (no rows) <- the body is in `messages` but not in the index
The cause is a missing or broken AFTER INSERT trigger. The fix is to add the trigger (see above) and rebuild the index once to catch the rows that slipped through:
INSERT INTO messages_fts(messages_fts) VALUES('rebuild'); -- external-content tables
-- or, for a standalone table, DELETE all rows and re-run the backfill SELECT.
sqlite> SELECT message_id FROM messages_fts WHERE messages_fts MATCH 'invoice';
m1 -- now it matches
Wrong tokenizer. With the default tokenizer, searching "invoices" will not match a body that says "invoice". The fix is tokenize='porter unicode61' so the Porter stemmer folds plurals and tenses together. Without unicode61, accented text and mixed case also fail to match.
Special characters throw syntax errors. Searching boss@corp.com or Q3:revenue raw makes FTS5 try to parse @, ., and : as operators and the query errors out. The fix is the toFtsMatch sanitizer above: strip operator characters and quote each token as a phrase.
Empty index. Everything is wired correctly, search returns nothing, and you panic. You created the table and triggers but never backfilled existing rows, so the index only covers mail inserted after the triggers existed. The fix is the one-line backfill INSERT INTO messages_fts ... SELECT ... FROM messages.
Where does this plug into Tinbox?
This FTS5 index is the single search engine behind every surface in Tinbox. The inbox UI search box, the AI agent that calls this search under the hood, and the MCP search_messages tool all funnel through one engine function, searchMessages, which runs exactly the two-step MATCH-then-hydrate query shown above against the messages_fts table.
That single-choke-point design is deliberate: there is one place where search lives, so ranking, sanitization, and the inbox-scoping filter are written once and reused everywhere. When an AI assistant connected over MCP asks to "find emails about the Q3 invoice", it is not running a special agent search, it is calling the same FTS5 query a human types into the search box. Keyword search, owned, on your own D1, with no external search vendor in the loop.
If you want this without writing the migration, the sanitizer, and the two-step query yourself, it ships in the box. Deploy your own inbox and the FTS5 index, triggers, and searchMessages engine come with it, ready to import mail into and search (import an existing IMAP mailbox, then search what you imported).
Deploy this yourself: npx tinbox init <domain>. The search engine, schema, and triggers are part of the default deploy, documented alongside the rest of the tinbox/cf query patterns in the docs.
Frequently asked questions
Does FTS5 work in Cloudflare D1?
Yes. D1 is SQLite and ships the FTS5 extension, so CREATE VIRTUAL TABLE ... USING fts5(...), MATCH queries, bm25() ranking, and snippet() all run in D1. The main caveat is that drizzle-kit and most migration tools cannot model a virtual table, so you write the FTS5 DDL as a hand-authored migration and apply it with wrangler d1 execute. The same statements validate under better-sqlite3 locally, so dev and prod behave the same.
How do I keep an FTS5 index in sync with the source table?
Add three triggers on the source table: AFTER INSERT inserts the new row's searchable columns into the FTS table, AFTER DELETE removes them, and AFTER UPDATE deletes then re-inserts. This is the classic FTS5 trigger trio. If you skip the triggers, the index goes stale and a just-inserted message will not show up in search until you rebuild.
How do I rank full-text search results in SQLite?
Order by bm25(your_fts_table). bm25() returns a relevance score where lower (more negative) is better, so ORDER BY bm25(messages_fts) puts the best matches first. You can weight columns, for example bm25(messages_fts, 10.0, 1.0) to make subject matches count ten times more than body matches. For email, ordering by date is often better than relevance, so pick per query.
Should I use an external-content FTS5 table or a standalone one?
Use an external-content table (content='messages') when your source table has an integer rowid primary key: it avoids storing the body twice. Use a standalone FTS5 table when your primary key is a text id like a ULID, because external-content tables key on integer rowid and a text id does not map cleanly. Tinbox uses standalone tables for exactly this reason.
Why does my FTS5 query throw a syntax error on an email address?
FTS5 treats characters like double-quote, asterisk, colon, caret, parenthesis, and hyphen as query operators, so a raw string like user@host.com:8080 parses as operators and errors. Sanitize the input: split on whitespace, strip operator characters, and wrap each token in double quotes so it matches as a phrase. Add a trailing asterisk on the last token for as-you-type prefix search.