SQLite FTS5 Code Search: Trigram Won 40/40
You build a local code index with FTS5, test it on a small repo, and it looks perfect. Then the queries that matter - half-typed identifiers, mid-word fragments - come back empty, and nobody can tell you which tokenizer is at fault.
📜 Table of Contents
- How the test was built
- FastAPI: 1,233 files, 7,398 blocks
- Django: 2,943 files, 43,592 blocks
- What actually moved
- The setup that survived both repos
- Choosing without a test harness
- FAQ
- Does FTS5 need SQLite compiled with special flags?
- Why not just use ripgrep?
- Can I switch tokenizers on an existing table?
- How do I tune ranking inside a block?
📖 Keep reading
If you want symbol search over a codebase without an embedding model, SQLite's FTS5 sits in your Python standard library, needs no server, and answers lookups in under a millisecond. The tokenizer you pick decides whether it works.
The short version: on 7,398 function and class blocks from FastAPI (4.1 MB of source), the trigram tokenizer returned the exact defining block first 40 out of 40 times. unicode61, the default, got 37. porter got 34 and broke four prefix queries outright. Then the same benchmark ran on Django: 43,592 blocks, 28.6 MB. Trigram's accuracy edge disappeared (38 against 39), its index was 2.4x bigger, and its multi-word queries went from 2.4 ms to 10.3 ms. Different repo, different answer.
How the test was built
Every .py file was parsed with ast; every function, async function, and class became one row containing its source segment. Segments over 20,000 characters were skipped. That produced 7,398 rows for FastAPI and 43,592 for Django.
Queries were generated from the corpus itself, so the right answer is a fact rather than a judgement call:
- exact — an identifier of 8+ characters that appears in exactly one block. 40 samples.
- prefix — the first six characters of an identifier, verified unique to one block. 40 samples. This is what you type when you half-remember a name.
- words — a snake_case name split into its words and shuffled.
get_current_userbecomesuser current get. 40 samples.
Scoring is hit@1 (the defining block ranked first) and hit@5. Environment: SQLite 3.42.0, Python 3.11, Linux, one core, warm connection, no HTTP layer. Grep runs are grep -rn --include=*.py -F against the same tree, subprocess time included.
FastAPI: 1,233 files, 7,398 blocks
| Tokenizer | Index | Build | Exact @1 / @5 | Prefix @1 / @5 | Words @1 / @5 | Exact median | Words median |
|---|---|---|---|---|---|---|---|
| unicode61 | 5.33 MB | 0.07 s | 37 / 40 | 27 / 33 | 34 / 40 | 0.19 ms | 0.29 ms |
| porter | 5.31 MB | 0.07 s | 34 / 39 | 22 / 28 | 34 / 40 | 0.16 ms | 0.32 ms |
| trigram | 13.45 MB | 0.47 s | 40 / 40 | 28 / 36 | 31 / 38 | 1.62 ms | 2.37 ms |
Grep baseline for the exact set: 18.9 ms median, 22.7 ms p95, 40 of 40 hits at file level. FTS5 answers roughly 100x faster, before counting the time to parse grep's output.
Django: 2,943 files, 43,592 blocks
| Tokenizer | Index | Build | Exact @1 / @5 | Prefix @1 / @5 | Words @1 / @5 | Exact median | Words median |
|---|---|---|---|---|---|---|---|
| unicode61 | 38.91 MB | 0.71 s | 39 / 39 | 29 / 33 | 30 / 32 | 0.30 ms | 1.25 ms |
| porter | 38.68 MB | 0.65 s | 38 / 39 | 26 / 28 | 29 / 32 | 0.40 ms | 1.50 ms |
| trigram | 93.39 MB | 5.08 s | 38 / 40 | 27 / 31 | 28 / 32 | 2.70 ms | 10.28 ms |
Grep baseline: 65.4 ms median over the 28.6 MB tree. Still two hundred times slower than the fastest FTS5 answer, and that gap is what justifies keeping a local index.
What actually moved
Trigram wins on exact identifiers, and the reason is mechanical. With unicode61, the string get_current_user is indexed as three tokens: get, current, user. A query for it becomes a phrase, and that phrase also matches a docstring sentence like "get the current user from the request". On FastAPI, three queries lost first place to prose. Trigram indexes overlapping three-character sequences, so a quoted query matches only where the literal characters appear in order: 40 of 40.
At 43,592 blocks the advantage evaporates. Trigram exact hit@1 fell to 38. Both misses were rank failures, not tokenizer failures: ORDER BY rank put a shorter block that repeats the symbol above the actual definition. That is the same failure mode unicode61 had, triggered elsewhere. Meanwhile trigram's multi-word queries cost 10.28 ms against unicode61's 1.25 ms, because each of the three substrings scans a long posting list before the intersection.
Porter is a trap for code. Stemming maps dependency and dependencies to one token, which is right for prose and wrong for symbols. The damage shows in prefix queries: four came back empty on FastAPI, three on Django. A query like "skippe"* is stemmed before matching, and the stem no longer prefixes the stored terms. Someone types seven characters of an identifier and gets nothing at all. Not slower. Empty.
Index size is the honest cost. Trigram is 2.52x unicode61 on FastAPI and 2.40x on Django. Build time is 6.7x to 7.1x. For a 4 MB repo that is 13 MB and half a second, which does not matter. For a monorepo with 400 MB of Python it is roughly 1.3 GB of disk and minutes of rebuild, which changes how often you refresh.
One trap earns its own line: running INSERT INTO code(code) VALUES('optimize') on the FastAPI trigram index grew the file from 13.45 MB to 17.35 MB, while the unicode61 index stayed at 5.33 MB. Segment merge is supposed to compact an index; with trigram it rewrote into a larger layout on SQLite 3.42.0. Measure before shipping an optimize step in a build pipeline.
The setup that survived both repos
Use unicode61 as the base table. Add a trigram table only if your queries are symbol-heavy, and route by query shape:
import sqlite3
db = sqlite3.connect("code.db")
db.execute("""CREATE VIRTUAL TABLE IF NOT EXISTS code
USING fts5(path, symbol, body, tokenize='unicode61')""")
db.execute("""CREATE VIRTUAL TABLE IF NOT EXISTS code_sub
USING fts5(path, symbol, tokenize='trigram')""")
def symbol_lookup(name):
"""Literal substring, no token boundaries involved."""
return db.execute(
"SELECT path, symbol, bm25(code_sub) AS s FROM code_sub "
"WHERE code_sub MATCH ? ORDER BY s LIMIT 10", ('"%s"' % name,)).fetchall()
def type_ahead(fragment):
"""Phrase prefix on the unicode61 table."""
return db.execute(
"SELECT path, symbol, bm25(code) AS s FROM code "
"WHERE code MATCH ? ORDER BY s LIMIT 10", ('"%s"*' % fragment,)).fetchall()
def word_search(words):
"""Bare tokens are ANDed, then ranked."""
return db.execute(
"SELECT path, symbol, bm25(code) AS s FROM code "
"WHERE code MATCH ? ORDER BY s LIMIT 10", (" ".join(words),)).fetchall()
Three details that cost an hour each. bm25() takes the table name in FTS5, not a column list or a weight vector, and its sign is inverted: lower is better, so sort ascending. MATCH with an unquoted multi-token string is an implicit AND, which is what word search wants and not what an identifier wants. And trigram requires three characters minimum; a two-letter query returns nothing instead of raising.
Choosing without a test harness
| Your situation | Pick | Why |
|---|---|---|
| Under about 10k code blocks, symbol lookups dominate | trigram | 40/40 exact, index cost is a few MB |
| Over about 40k blocks, mixed prose and code | unicode61 | Same accuracy, 2.4x smaller, 8x faster on multi-word |
| Natural-language search over docs and comments | unicode61 | Stemming adds nothing measurable; porter is not it |
| Need to match inside a long identifier | a second trigram table, queried in parallel | unicode61 cannot match mid-token fragments |
The bigger point: this choice deserves a five-minute benchmark on your own repo, because the winner flipped between two Python projects written in the same language. The script that produced these numbers is 90 lines, builds ground truth from the AST, and finishes in under a minute on either codebase.
FAQ
Does FTS5 need SQLite compiled with special flags?
FTS5 is a compile-time option and nearly every packaged Python build enables it. Check PRAGMA compile_options for ENABLE_FTS5. The trigram tokenizer needs SQLite 3.34 or newer; this test ran 3.42.0.
Why not just use ripgrep?
For one-off searches, do. Grep answered in 18.9 ms on FastAPI and 65.4 ms on Django and is exact by construction. An index earns its keep when you run the same query shape hundreds of times, rank by relevance instead of file order, or want results grouped by function rather than by line.
Can I switch tokenizers on an existing table?
No. The tokenizer is baked into the table definition and its index. Changing it means dropping and rebuilding: 0.47 seconds for FastAPI, 5.08 seconds for Django with trigram.
How do I tune ranking inside a block?
On a single body column, bm25 mostly rewards short blocks. Giving a symbol column a higher weight fixed most of the misses in these runs, and it is the cheapest accuracy lever before reaching for embeddings.
Related: sentence-aligned chunking measured on 3,551 sentences, semantic search against keyword search, and what six codebases cost in tokens.
Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.