SQLite FTS5 Code Search: Trigram Won 40/40

🔧 AI Tools 2026-11-29 7 min read
SQLite FTS5 Code Search: Trigram Won 40/40, Then Lost at 43k Chunks

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

📖 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:

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

TokenizerIndexBuildExact @1 / @5Prefix @1 / @5Words @1 / @5Exact medianWords median
unicode615.33 MB0.07 s37 / 4027 / 3334 / 400.19 ms0.29 ms
porter5.31 MB0.07 s34 / 3922 / 2834 / 400.16 ms0.32 ms
trigram13.45 MB0.47 s40 / 4028 / 3631 / 381.62 ms2.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

TokenizerIndexBuildExact @1 / @5Prefix @1 / @5Words @1 / @5Exact medianWords median
unicode6138.91 MB0.71 s39 / 3929 / 3330 / 320.30 ms1.25 ms
porter38.68 MB0.65 s38 / 3926 / 2829 / 320.40 ms1.50 ms
trigram93.39 MB5.08 s38 / 4027 / 3128 / 322.70 ms10.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 situationPickWhy
Under about 10k code blocks, symbol lookups dominatetrigram40/40 exact, index cost is a few MB
Over about 40k blocks, mixed prose and codeunicode61Same accuracy, 2.4x smaller, 8x faster on multi-word
Natural-language search over docs and commentsunicode61Stemming adds nothing measurable; porter is not it
Need to match inside a long identifiera second trigram table, queried in parallelunicode61 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.

Related Articles
2026-08-02
AI Podcast Generator 2026: Turn Articles Into Audio With NotebookLM and Open Tools
2026-08-16
Best AI Video Editor in San Francisco 2026: 7 Tools for Creators and Startups
2026-08-14
AI PDF Chatbot GitHub 2026: 7 Open Source Projects to Self-Host
2026-08-22
Best AI Tax Assistant in Luxembourg 2026: 6 Tools for Expats, Freelancers and Fund Professionals
2026-08-03
AI Language Learning 2026: LibreLingo (2.6k Stars) + LLM Tutors - Free Alternatives to Duolingo
2026-07-24
Best Free AI Video Editors Online 2026 Tested

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.

💬 Comments (0)

No comments yet. Be the first!

Login to comment