Notes on building a search index in SQLite
FTS5 is fast, boring, and embarrassingly capable. A few notes from building local search over tens of thousands of documents.
When I built Sift, I assumed I would need an embedded search engine: an inverted index, a tokenizer, some ranking code. What I actually needed was SQLite’s FTS5 extension and a careful import path.
FTS5 in one screen
A full-text index is a virtual table. You insert rows, you query with MATCH, and SQLite handles the rest.
CREATE VIRTUAL TABLE notes USING fts5(
path,
title,
body,
tokenize = 'porter unicode61'
);
INSERT INTO notes (path, title, body) VALUES (?, ?, ?);
SELECT path, title, bm25(notes) AS rank
FROM notes
WHERE notes MATCH ?
ORDER BY rank
LIMIT 20;
bm25() returns a negative number where lower is better. Prefix matching is term*. Phrases are quoted. Column filters look like title:rust. That is most of a search feature.
Indexing is the hard part
Query latency was never the problem. Keeping the index correct as files change was.
The naive approach — drop and rebuild on every scan — takes seconds on a large vault and rewrites data that did not change. Since SQLite is a single writer anyway, the fix is to batch everything into one transaction:
- Walk the directory and hash each file.
- Compare hashes against a
filestable. - Delete, insert, or update only what changed.
- Commit once.
For 40,000 notes this brought a cold sync from about 20 seconds to under 4. Deleting rows from an FTS5 table is slower than inserting them; if churn is high, it is worth rebuilding the index occasionally instead of patching it forever.
Ranking is a product decision
BM25 is a good baseline and a bad final answer. For notes, I ended up blending three signals:
score = bm25
+ 1.2 × title match boost
+ 0.4 × recency (decayed over 180 days)
The exact weights were tuned by searching for things I remembered writing, not by a benchmark. That is usually the right methodology for personal search: there is exactly one user, and their memory is the ground truth.
Things I would do again
- Store the raw text. The index is derived data. Keeping the source text in a normal table makes reindexing, debugging, and re-tokenizing possible without touching the filesystem.
- Use one file. A single
.dbfile is trivially backed up, copied, and deleted. No daemon, no port, no lock files to explain. - Test with a real corpus. Synthetic documents do not reveal tokenizer problems. Real notes have code blocks, URLs, and headings that break naive assumptions.
Where it stops
FTS5 will not do fuzzy matching, semantic search, or cross-document reasoning. When those requirements arrived, the answer was a separate layer on top of the SQLite index — not a replacement for it. The cheap index stayed, and it still answers most queries in milliseconds.