How do you add ranked full-text search with SQLite's FTS5 over a chat history table, and keep that index in step with the messages?
answer
- a virtual table beside the real one
- content= and content_rowid=
- triggers send 'delete' rows
- MATCH, then ORDER BY rank
- a smaller bm25 is better
basics
~20 sCreate an FTS5 virtual table over the message columns, usually as an external-content table pointing at the messages table, keep it current with insert, delete and update triggers, and query it with MATCH ordered by rank.
solid answer
~50 sFTS5 is SQLite's full-text extension. `CREATE VIRTUAL TABLE message_fts USING fts5(sender, body, content='message', content_rowid='id')` builds a full-text index whose column values are read back from the `message` table, so the text is not stored twice. FTS5 does not watch that table, so you add `AFTER INSERT`, `AFTER DELETE` and `AFTER UPDATE` triggers; a removal is written as a special insert carrying the old values, `INSERT INTO message_fts(message_fts, rowid, sender, body) VALUES('delete', old.id, old.sender, old.body)`. Rows that existed before the triggers need `INSERT INTO message_fts(message_fts) VALUES('rebuild')`. Queries use `WHERE message_fts MATCH 'harb* AND friday'` with `ORDER BY rank`, which defaults to `bm25()` and puts the best match first because a better match scores lower; `snippet()` and `highlight()` mark the hits. FTS5 exists only if the library was built with it, so check `PRAGMA compile_options` for `ENABLE_FTS5`.
code
sql · 32 linesCREATE TABLE message(
id INTEGER PRIMARY KEY,
chat_id INTEGER NOT NULL,
sender TEXT NOT NULL,
body TEXT NOT NULL
);
CREATE VIRTUAL TABLE message_fts USING fts5(
sender, body,
content='message', content_rowid='id'
);
CREATE TRIGGER message_ai AFTER INSERT ON message BEGIN
INSERT INTO message_fts(rowid, sender, body) VALUES (new.id, new.sender, new.body);
END;
CREATE TRIGGER message_ad AFTER DELETE ON message BEGIN
INSERT INTO message_fts(message_fts, rowid, sender, body)
VALUES ('delete', old.id, old.sender, old.body);
END;
CREATE TRIGGER message_au AFTER UPDATE ON message BEGIN
INSERT INTO message_fts(message_fts, rowid, sender, body)
VALUES ('delete', old.id, old.sender, old.body);
INSERT INTO message_fts(rowid, sender, body) VALUES (new.id, new.sender, new.body);
END;
-- index rows that existed before the triggers
INSERT INTO message_fts(message_fts) VALUES ('rebuild');
SELECT m.id, m.chat_id, snippet(message_fts, 1, '[', ']', '...', 8) AS hit
FROM message_fts
JOIN message AS m ON m.id = message_fts.rowid
WHERE message_fts MATCH 'harb* AND friday'
ORDER BY rank
LIMIT 20;go deeper
Recall that FTS5 is a virtual table you search with MATCH, and that ORDER BY rank sorts the results from best to worst match.
Explain external-content tables, the three triggers with the special 'delete' insert, the one-off 'rebuild', and why a better bm25 score is a smaller number.
Show the operational care: check the build includes FTS5, keep the 'delete' values identical to what was indexed, pick a tokenizer for the language and substring needs, and optimize after bulk imports.
Weigh the index's cost against the feature: external content saves space but makes consistency your code's job, and a trigram tokenizer buys substring search with a much larger file.
## What FTS5 is **FTS5** is SQLite's full-text search extension, shipped in the amalgamation source since 3.9.0. It is a **virtual table** module: you create a table with `CREATE VIRTUAL TABLE ... USING fts5(...)`, and behind it FTS5 maintains a full-text index in ordinary SQLite tables, called shadow tables, in the same file. A query names the virtual table on the left of `MATCH` and an FTS5 query string on the right. Searching a chat history with `body LIKE '%harbour%'` instead reads every row, because an ordinary B-tree index cannot help a pattern with a leading wildcard. (How an inverted index works and how relevance models compare is covered with the general material on search.) ## Choosing the table shape | Shape | How it is declared | What is stored | Good for | |---|---|---|---| | Default | `fts5(sender, body)` | FTS5 keeps its own copy of every column value plus the index | a search table that is the only home of the text | | External content | `fts5(sender, body, content='message', content_rowid='id')` | only the index; values are read from `message` by `id` | a chat app whose messages already live in a normal table | | Contentless | `fts5(sender, body, content='')` | only the index; indexed column values cannot be read back | very large corpora where you only need matching rowids | For chat history, **external content** is the usual choice: one copy of each message, ordinary columns such as `chat_id` and timestamps in the real table, and an index beside it. The price is that keeping the two consistent is your job. ## Keeping an external-content index consistent FTS5 never reads the content table to discover changes. The documented pattern is three triggers: 1. `AFTER INSERT` inserts the new row's `rowid` and indexed columns into the FTS5 table. 2. `AFTER DELETE` inserts a row whose first, hidden column (named after the table) holds the text `'delete'`, plus the **old** rowid and values. That special insert removes those tokens from the index. 3. `AFTER UPDATE` does both: a `'delete'` with the old values, then an insert with the new ones. Three rules keep it correct: - The `'delete'` must carry exactly the values that were indexed. If they differ, the index ends up inconsistent with the content table and queries return wrong rows. - Creating triggers does not index rows already in the table. Run `INSERT INTO message_fts(message_fts) VALUES('rebuild')` once, which deletes the whole index and rebuilds it from the content table. Rebuild is not available for contentless tables. - External-content tables do not support `REPLACE` conflict handling, so write upserts on the real table, not on the FTS5 table. FTS5 also accepts maintenance commands written the same way: `'integrity-check'` verifies the index, and `'optimize'` merges its internal B-trees into one for the smallest, fastest form. ## Querying and ranking - **Terms and operators.** `MATCH 'harbour friday'` needs both terms; `AND`, `OR` and `NOT` combine them explicitly. - **Prefixes.** `harb*` matches any token starting with `harb`. - **Phrases and proximity.** `"harbour restaurant"` needs the tokens in sequence; `NEAR(harbour friday, 5)` needs them within five tokens. - **Column filters.** `sender : ana` restricts a phrase to one column. - **Case.** Searches are case-independent by default. - **Ranking.** The hidden `rank` column holds, by default, the value of the built-in `bm25()` function. FTS5 multiplies the standard BM25 score by -1, so a better match is numerically smaller and plain `ORDER BY rank` returns the best first. Sorting by `rank` can be faster than calling `bm25()` yourself, especially with a `LIMIT`. Column weights go in the call, for example `rank MATCH 'bm25(10.0, 5.0)'` to weigh `sender` above `body`. - **Display.** `highlight()` returns a column with matches wrapped in markers; `snippet()` returns a short fragment around them. ## Tokenizers The tokenizer decides what a term is. `unicode61`, the default, splits on Unicode separators and folds case. `porter` wraps another tokenizer and stems English words, so `walking` matches `walk`. `ascii` treats every non-ASCII character as part of a token. `trigram` indexes every three-character sequence, so a query can match a substring such as `arbo` inside `harbour`; substrings shorter than three characters match nothing, and the index grows considerably. ## Before you ship - **Check availability.** FTS5 is compiled in only when `SQLITE_ENABLE_FTS5` is defined, or loaded as an extension. `PRAGMA compile_options` lists `ENABLE_FTS5` when it is built in; the final test is whether `CREATE VIRTUAL TABLE ... USING fts5` succeeds on the library you actually ship with. - **Filter in the join.** Keep `chat_id` in the real table and join on `rowid` to restrict a search to one conversation. - **Run `'optimize'` occasionally** after large imports, not after every message.
- Why does ORDER BY bm25(message_fts) DESC return the worst matches first in SQLite FTS5?FTS5's `bm25()` multiplies the usual BM25 score by -1, so a better match is numerically smaller. Ascending order, the default, already puts the best match first, and `DESC` reverses it. Prefer `ORDER BY rank`, which by default carries the same value and can sort faster, especially when the query has a `LIMIT`.
- How would you let a SQLite chat search find 'arbo' inside 'harbour'?The default `unicode61` tokenizer matches whole tokens and prefixes such as `harb*`, not substrings. Create the FTS5 table with `tokenize='trigram'`, which indexes every three-character sequence so any substring of at least three characters can match, at the cost of a much larger index. `LIKE '%arbo%'` on the base table also works but reads every row.
- FTS5 notices new rows in its content table automatically.
- Creating the triggers also indexes the messages already in the table.
- Use ORDER BY bm25(ft) DESC to get the best FTS5 matches first.
- A B-tree index on body makes LIKE '%term%' fast.
- Every SQLite build since 3.9.0 includes FTS5.
- The default FTS5 tokenizer matches substrings inside words.