SQLite project: a tested notes repository · 4 MIN READ

Full-text search with FTS5: an external-content index, ranking and safe queries

Index a table with an external-content FTS5 table kept in sync by triggers, query it with prefixes, phrases, operators and column filters, rank with bm25, and quote user input.

LIKE '%word%' reads every row and knows nothing about words, prefixes or relevance. FTS5 is SQLite's full-text engine: a virtual table that maintains an inverted index of tokens and answers MATCH queries with a bm25 rank. modernc.org/sqlite ships with FTS5 compiled in. The index can store its own copy of the text or point at an ordinary table you already have; the second option, external content, keeps one source of truth but makes keeping the index in sync your job.

sqlite · A MAP OF THE IDEA

  1. Content table + fts5
  2. Triggers keep in sync
  3. MATCH quoted terms
  4. ORDER BY rank

Useful when

  • Ranked word search without a separate search server.
  • External content keeps the text in one place.

Watch out

  • The index can be as large as the text.
  • Raw user input is parsed as query syntax.

Implementation & operation cost: One virtual table, three triggers, a quoting function and extra write work on every change to the content table.

01

Content table plus index

CREATE VIRTUAL TABLE docs_fts USING fts5(title, body, content='docs', content_rowid='id') creates an index whose rowid is docs.id and whose column values are read from docs when FTS5 needs them, for highlight and snippet. The index does not watch docs: three triggers do the work. After INSERT they add the new row; after DELETE they insert the special 'delete' command with the old values; after UPDATE they do both. The delete command must receive exactly the values that were indexed, which is why the triggers use old.title and old.body. If the two ever drift, INSERT INTO docs_fts(docs_fts) VALUES('rebuild') regenerates the index from the content table.

02

Querying, ranking and highlighting

The program indexes five short documents and runs a series of MATCH queries through one search function that joins the index back to docs and orders by rank, FTS5's hidden column that equals bm25() and sorts best matches first. highlight(docs_fts, 0, '[', ']') marks matched tokens in the title column; snippet picks the best short fragment of the body. It then updates a row, tries raw user input that is not valid FTS5 syntax, and finishes with the integrity-check command.

go
package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"

	_ "modernc.org/sqlite"
)

const schema = `
CREATE TABLE docs (
	id    INTEGER PRIMARY KEY,
	title TEXT NOT NULL,
	body  TEXT NOT NULL
);
-- External content: the index stores tokens, docs stores the text.
CREATE VIRTUAL TABLE docs_fts USING fts5(
	title, body,
	content='docs', content_rowid='id',
	tokenize='unicode61'
);
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;`

var docs = [][2]string{
	{"Goroutines and channels", "A goroutine is a lightweight thread; channels connect goroutines."},
	{"Context cancellation", "Pass a context to stop goroutines when a request is cancelled."},
	{"SQLite in Go", "Use database/sql with a SQLite driver; SQLite stores the database in one file."},
	{"Error handling", "Wrap errors with context and check them with errors.Is."},
	{"Building C++ bindings", "cgo lets Go call C and C++ code, at the cost of cross-compilation."},
}

func search(ctx context.Context, db *sql.DB, query string) ([]string, error) {
	rows, err := db.QueryContext(ctx, `
		SELECT d.id, highlight(docs_fts, 0, '[', ']')
		FROM docs_fts JOIN docs d ON d.id = docs_fts.rowid
		WHERE docs_fts MATCH ?
		ORDER BY rank`, query)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []string
	for rows.Next() {
		var id int
		var title string
		if err := rows.Scan(&id, &title); err != nil {
			return nil, err
		}
		out = append(out, fmt.Sprintf("%d %s", id, title))
	}
	return out, rows.Err()
}

// phrase turns arbitrary user input into FTS5 string tokens: each word is
// wrapped in double quotes, with embedded quotes doubled, so operators and
// punctuation lose their meaning. Adjacent quoted words are ANDed together.
func phrase(input string) string {
	var parts []string
	for _, w := range strings.Fields(input) {
		parts = append(parts, `"`+strings.ReplaceAll(w, `"`, `""`)+`"`)
	}
	return strings.Join(parts, " ")
}

func main() {
	ctx := context.Background()
	dir, err := os.MkdirTemp("", "fts5")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)
	db, err := sql.Open("sqlite", filepath.Join(dir, "app.db"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	if _, err := db.ExecContext(ctx, schema); err != nil {
		log.Fatal(err)
	}
	for _, d := range docs {
		if _, err := db.ExecContext(ctx, "INSERT INTO docs (title, body) VALUES (?, ?)", d[0], d[1]); err != nil {
			log.Fatal(err)
		}
	}

	for _, q := range []string{
		"goroutine*",             // prefix
		`"one file"`,             // phrase
		"goroutines NOT context", // boolean operators are upper case
		"errors OR cgo",
		"title:sqlite", // column filter
		"context",      // ranked by bm25, best match first
	} {
		hits, err := search(ctx, db, q)
		fmt.Printf("%-26s -> %v %v\n", q, hits, err)
	}

	var snippet string
	if err := db.QueryRowContext(ctx, `
		SELECT snippet(docs_fts, 1, '<b>', '</b>', '...', 6)
		FROM docs_fts WHERE docs_fts MATCH 'driver'`).Scan(&snippet); err != nil {
		log.Fatal(err)
	}
	fmt.Println("snippet:", snippet)

	// The trigger keeps the index in step with an UPDATE.
	if _, err := db.ExecContext(ctx, "UPDATE docs SET title = 'Errors and panics' WHERE id = 4"); err != nil {
		log.Fatal(err)
	}
	hits, _ := search(ctx, db, "panics")
	fmt.Println("after update, panics ->", hits)

	for _, raw := range []string{"c++", `"unbalanced`, "AND"} {
		_, err := search(ctx, db, raw)
		fmt.Printf("raw %-12q -> %v\n", raw, err)
		hits, err := search(ctx, db, phrase(raw))
		fmt.Printf("quoted %-9s -> %v %v\n", phrase(raw), hits, err)
	}

	// rank = 1 also compares the index with the external content table.
	integrity := "ok"
	if _, err := db.ExecContext(ctx, "INSERT INTO docs_fts (docs_fts, rank) VALUES ('integrity-check', 1)"); err != nil {
		integrity = err.Error()
	}
	fmt.Println("index integrity-check:", integrity)
}
Read the code

goroutine* is a prefix query and finds documents 1 and 2, the second only through goroutines in its body, so its title has no marks. "one file" is a phrase and finds document 3. NOT, OR and title: work as operators and a column filter. The snippet line shows six tokens around driver with an ellipsis. After the UPDATE the trigger has reindexed document 4, so panics finds it. Raw c++, an unbalanced quote and a bare AND are syntax errors; quoted, they search for c, unbalanced and and. integrity-check reports ok.

03

User input is a query language

The string passed to MATCH is parsed as FTS5 query syntax: double quotes delimit strings, * is a prefix, : selects a column, parentheses group, and the upper-case words AND, OR, NOT and NEAR are operators. A search box that passes text straight through turns c++ into an error, AND into a syntax error and title:secret into a column query. Binding with ? prevents SQL injection, not FTS5 syntax errors. The phrase helper wraps each whitespace-separated word in double quotes and doubles embedded quotes, so every word becomes a literal string and the words are implicitly ANDed. Offer operators only through explicit controls in your UI.

go
func phrase(input string) string {
	var parts []string
	for _, w := range strings.Fields(input) {
		parts = append(parts, `"`+strings.ReplaceAll(w, `"`, `""`)+`"`)
	}
	return strings.Join(parts, " ")
}
Read the code

Quoted, c++ becomes the string "c++", which the unicode61 tokenizer splits on punctuation into the single token c; that is why it matches document 5 by its C. An empty input produces an empty string, which you should treat as no search rather than pass to MATCH.

04

Tokenizers decide what a word is

The default unicode61 tokenizer folds case, removes diacritics, and treats every character that is not a letter or digit as a separator, so c++, C and c are the same token. It does not stem: writer does not match writers unless you search writer*. tokenize='porter unicode61' adds English stemming, and the trigram tokenizer supports substring matching and LIKE acceleration at the cost of a much larger index. The tokenizer is fixed when the table is created; changing it means dropping and rebuilding the index in a migration.

05

Costs and operational notes

An FTS5 index is often as large as the text it indexes, and every write to the content table now also writes index segments through the triggers. FTS5 merges segments automatically; after a bulk load, INSERT INTO docs_fts(docs_fts) VALUES('optimize') merges them into one. bm25 weights every column equally unless you pass weights, as in ORDER BY bm25(docs_fts, 10.0, 1.0) to favour titles. Keep the triggers, the FTS table and the content table in the same migration, and run the integrity-check with rank 1 in tests: it compares the index with the content table and reports drift.

TAKE THIS WITH YOU

Use an external-content FTS5 table with insert, delete and update triggers so the text lives once. Order by rank, decorate with highlight and snippet, and quote every user word as an FTS5 string, because MATCH input is a query language of its own.

Check your understanding

A search box binds the user text to WHERE docs_fts MATCH ?. A user types c++ and the query fails. Why?

Go to the source

Progress stays in this browser. No account needed.