---
name: sqlite-fts
description: 'Design and query SQLite FTS5 full-text indexes: create virtual tables (external content + triggers), rank with bm25, highlight and snippet, prefix queries, phrase and NEAR, trigram substring search, tokenizer options, Arabic text normalization, rebuild/optimize. Works on SQLite 3.45+ and Cloudflare D1. Use when the user needs a search box over documents, notes or a library, or a slow LIKE ''%x%'' query to be replaced. Triggers: fts5، بحث نصي كامل، bm25، sqlite full text search، d1 search.'
---

# 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 --version
```

## Workflow

1. Keep the real data in a normal table; index it with an external-content FTS5 table.
2. Add triggers so the index follows inserts, updates and deletes.
3. Normalize text (especially Arabic) before indexing and before querying, using the same function.
4. Query with `MATCH`, order by `bm25()` or `rank`, and show `snippet()`.
5. 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 segments
```

## Queries

```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 index
```

Trigram 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

- `unicode61` splits 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. Run `INSERT INTO docs_fts(docs_fts) VALUES ('integrity-check')` when in doubt.
- `ORDER BY rank` is shorthand for `bm25()` 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
```
