Keeping a search index in sync in SQL
The index should not be a second copy of the truth, so point it at the table and keep it fed.
CREATE VIRTUAL TABLE posts_fts USING fts5(
title,
body,
content = 'posts',
content_rowid = 'id'
);
CREATE TRIGGER posts_fts_insert
AFTER INSERT ON posts
BEGIN
INSERT INTO posts_fts (rowid, title, body)
VALUES (NEW.id, NEW.title, NEW.body);
END;
CREATE TRIGGER posts_fts_delete
AFTER DELETE ON posts
BEGIN
INSERT INTO posts_fts (posts_fts, rowid, title, body)
VALUES ('delete', OLD.id, OLD.title, OLD.body);
END;
How it works
content=makes the table the content source; the index stores only terms.- Three triggers keep it current: insert, delete, and update as delete plus insert.
- A delete is spelled as an insert of the special
'delete'command row.
Keywords and builtins used here
AFTERBEGINCREATEDELETEENDINSERTINTONEWOLDONTABLETRIGGERUSINGVALUES
The run, in numbers
- Lines
- 20
- Characters to type
- 413
- Tokens
- 94
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 59 seconds.
Step 4 of 4 in Full-text search, step 12 of 14 in JSON & search.