SQLite full-text search with FTS5: bm25, trigram and prefix queries
Build fast full-text search in SQLite or Cloudflare D1 with FTS5: external-content tables, triggers, bm25 ranking, snippets, prefix and trigram search, and Arabic normalization.
التثبيت في Claude Code
ضع الملف في مجلد باسم المهارة داخل مجلد skills الخاص بـ Claude Code، ثم ابدأ جلسة جديدة. الأمر التالي يفعل ذلك:
bash
mkdir -p ~/.claude/skills/sqlite-fts && \
curl -fsSL https://md2.dev/library/raw/sqlite-fts.md \
-o ~/.claude/skills/sqlite-fts/SKILL.md المعاينة
SQLite full-text search (FTS5)
When to use
A search feature over a few thousand to millions of text rows, or replacing LIKE '%term%' scans. Works in the sqlite3 shell, in apps, and in Cloudflare D1 (see wrangler-d1 for D1 export caveats).
BASH
sqlite3 :memory: "PRAGMA compile_options" | grep -i fts5 # ENABLE_FTS5
sqlite3 --versionWorkflow
- Keep the real data in a normal table; index it with an external-content FTS5 table.
- Add triggers so the index follows inserts, updates and deletes.
- Normalize text (especially Arabic) before indexing and before querying, using the same function.
- Query with
MATCH, order bybm25()orrank, and showsnippet(). - Escape user input; never paste raw text into
MATCH.
Schema
SQL
CREATE TABLE docs(id INTEGER PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL);
CREATE VIRTUAL TABLE docs_fts USING fts5(
title, body,
content='docs', content_rowid='id',
tokenize='unicode61 remove_diacritics 2'
);
CREATE TRIGGER docs_ai AFTER INSERT ON docs BEGIN
INSERT INTO docs_fts(rowid, title, body) VALUES (new.id, new.title, new.body);
END;
CREATE TRIGGER docs_ad AFTER DELETE ON docs BEGIN
INSERT INTO docs_fts(docs_fts, rowid, title, body) VALUES ('delete', old.id, old.title, old.body);
END;
CREATE TRIGGER docs_au AFTER UPDATE ON docs BEGIN
INSERT INTO docs_fts(docs_fts, rowid, title, body) VALUES ('delete', old.id, old.title, old.body);
INSERT INTO docs_fts(rowid, title, body) VALUES (new.id, new.title, new.body);
END;
INSERT INTO docs_fts(docs_fts) VALUES ('rebuild'); -- after bulk loads
INSERT INTO docs_fts(docs_fts) VALUES ('optimize'); -- merge segmentsQueries
SQL
-- ranked results: bm25 is NEGATIVE, lower = better; weights are per column
SELECT d.id, d.title, bm25(docs_fts, 10.0, 1.0) AS score,
snippet(docs_fts, 1, '<mark>', '</mark>', '…', 12) AS excerpt
FROM docs_fts JOIN docs d ON d.id = docs_fts.rowid
WHERE docs_fts MATCH 'sales report'
ORDER BY score LIMIT 20;
-- operators
... MATCH 'quarterly sales' -- AND (implicit)
... MATCH 'sales OR revenue'
... MATCH 'sales NOT draft'
... MATCH '"sales report"' -- phrase
... MATCH 'NEAR(sales growth, 5)' -- within 5 tokens
... MATCH 'title:report' -- one column
... MATCH '{title body}: report' -- column filter group
... MATCH 'repo*' -- prefix (add prefix='2 3' to the table for speed)Trigram (substring search, no tokenization by words)
SQL
CREATE VIRTUAL TABLE docs_tri USING fts5(body, tokenize='trigram');
SELECT rowid FROM docs_tri WHERE docs_tri MATCH 'port'; -- finds "report", "support"
SELECT rowid FROM docs_tri WHERE body LIKE '%port%'; -- LIKE/GLOB also use the indexTrigram needs queries of at least 3 characters and makes a larger index. It suits Arabic when you want matching inside words (prefixes like the definite article) without stemming.
Arabic and mixed text
unicode61splits on spaces and punctuation, but it does not remove Arabic diacritics, unify alef forms, or strip the prefix "ال". Searchingمحمدwill not findمُحَمَّد, andاحمدwill not findأحمد.- Normalize in application code, on both the indexed text and the query: remove U+064B to U+065F, U+0670 and tatweel U+0640; map U+0622, U+0623, U+0625, U+0671 to U+0627; optionally map U+0649 to U+064A (see regex-arabic).
- Keep the original text in the base table and index a normalized copy (a generated or shadow column), so display text stays intact.
- For substring behavior use the trigram tokenizer or prefix queries on normalized tokens.
Safe user input
TS
// turn arbitrary text into an AND of quoted terms
const toMatch = (q: string) =>
q.normalize("NFKC").split(/\s+/).filter(Boolean)
.map((t) => `"${t.replace(/"/g, '""')}"`).join(" ");
// last term as prefix: `${terms.slice(0, -1).join(" ")} "${last}"*`Gotchas
- With
content=tables you must delete using the exact old values; a mismatch corrupts the index. RunINSERT INTO docs_fts(docs_fts) VALUES ('integrity-check')when in doubt. ORDER BY rankis shorthand forbm25()with default weights; use it unless you need column weights.- Column filters and
snippet()use column numbers starting at 0. - Queries with bare
-,:,"or*raise syntax errors; quote terms as above. - FTS5 virtual tables are not included in
wrangler d1 export.
Verify
SQL
SELECT count(*) FROM docs_fts; -- equals the base table
SELECT rowid FROM docs_fts WHERE docs_fts MATCH 'known-term'; -- a term you know exists
INSERT INTO docs_fts(docs_fts) VALUES ('integrity-check'); -- no error = healthy