Reading history

Full-Text Search in SQL With SQLite FTS5

6 min read 0 views

Learn full-text search in SQL with SQLite FTS5: MATCH with AND, OR, NOT, phrases and prefixes, bm25 ranking, snippets and porter stemming.

LIKE '%join%' works for small tables, but it reads every row, cannot rank results and matches “joint” and “rejoin” too. Full-text search builds a word index over your text, much like the index at the back of a book. Searches become fast, results can be ranked by relevance, and you can search for phrases, prefixes and combinations of words. This lesson uses SQLite’s built-in FTS5 engine.

In this lesson you will learn

  • Creating a full-text table with FTS5
  • Searching with MATCH: words, AND, OR, phrases and prefixes
  • Ranking results with bm25
  • Searching one column and showing a snippet
  • Matching word forms with the porter tokenizer

You should know WHERE and LIKE, and how indexes speed up searches.

Creating and Searching an FTS5 Table

-- A full-text index over short lesson summaries
CREATE VIRTUAL TABLE notes USING fts5(title, body);
INSERT INTO notes (title, body) VALUES
 ('SQL joins', 'An inner join returns rows that match in both tables. A left join keeps every row from the left table.'),
 ('Indexes', 'An index makes searching a large table fast, like the index at the back of a book.'),
 ('Window functions', 'Window functions such as ROW_NUMBER and RANK calculate across rows without grouping them.'),
 ('Transactions', 'A transaction groups statements so they all succeed or all fail together.'),
 ('Searching text', 'Full-text search finds documents by words, not by exact column values like LIKE does.');

-- Find notes containing a word
SELECT title FROM notes WHERE notes MATCH 'join';

-- Several words (both must appear), a phrase, and OR
SELECT title FROM notes WHERE notes MATCH 'rows AND table';
SELECT title FROM notes WHERE notes MATCH '"left join"';
SELECT title FROM notes WHERE notes MATCH 'index OR transaction';

Output

+-----------+
| title     |
+-----------+
| SQL joins |
+-----------+
(1 row)

+-----------+
| title     |
+-----------+
| SQL joins |
+-----------+
(1 row)

+-----------+
| title     |
+-----------+
| SQL joins |
+-----------+
(1 row)

+--------------+
| title        |
+--------------+
| Indexes      |
| Transactions |
+--------------+
(2 rows)
  • CREATE VIRTUAL TABLE ... USING fts5(title, body) creates a table whose text columns are split into words and indexed. You insert and select rows like any other table.
  • WHERE notes MATCH 'join' searches every column. It matches the whole word “join” in the SQL joins note, but would not match “joint” the way LIKE '%join%' does.
  • Words separated by AND must all appear. “rows AND table” matches only the joins note; the window functions note has “rows” but not “table”.
  • Double quotes search for an exact phrase: '"left join"'.
  • OR matches either word: the Indexes note contains “index” and the Transactions note contains “transaction”. Matching ignores upper and lower case.

Ranking, Snippets and Stemming

CREATE VIRTUAL TABLE notes USING fts5(title, body);
INSERT INTO notes (title, body) VALUES
 ('SQL joins', 'An inner join returns rows that match in both tables. A left join keeps every row from the left table.'),
 ('Indexes', 'An index makes searching a large table fast, like the index at the back of a book.'),
 ('Window functions', 'Window functions such as ROW_NUMBER and RANK calculate across rows without grouping them.'),
 ('Transactions', 'A transaction groups statements so they all succeed or all fail together.'),
 ('Searching text', 'Full-text search finds documents by words, not by exact column values like LIKE does.');

-- Prefix search and ranking: best matches first
SELECT title, ROUND(bm25(notes), 3) AS score
FROM notes
WHERE notes MATCH 'search*'
ORDER BY bm25(notes);

-- Search one column only, and show a short snippet with the match marked
SELECT title, snippet(notes, 1, '[', ']', '...', 6) AS snippet
FROM notes
WHERE notes MATCH 'body: rows';

-- Stemming: with the porter tokenizer, 'grouping' also matches 'groups'
CREATE VIRTUAL TABLE notes2 USING fts5(body, tokenize = 'porter');
INSERT INTO notes2 SELECT body FROM notes;
SELECT COUNT(*) AS plain_matches FROM notes WHERE notes MATCH 'grouping';
SELECT COUNT(*) AS porter_matches FROM notes2 WHERE notes2 MATCH 'grouping';

Output

+----------------+--------+
| title          | score  |
+----------------+--------+
| Searching text | -0.464 |
| Indexes        | -0.33  |
+----------------+--------+
(2 rows)

+------------------+---------------------------------------------------+
| title            | snippet                                           |
+------------------+---------------------------------------------------+
| SQL joins        | An inner join returns [rows] that...              |
| Window functions | ...calculate across [rows] without grouping them. |
+------------------+---------------------------------------------------+
(2 rows)

+---------------+
| plain_matches |
+---------------+
| 1             |
+---------------+
(1 row)

+----------------+
| porter_matches |
+----------------+
| 2              |
+----------------+
(1 row)
  • search* is a prefix search: it matches “search”, “searching” and “searches”.
  • bm25(notes) scores how well each row matches. In FTS5 a lower (more negative) score is a better match, so sort in ascending order. “Searching text” ranks first because the search words are a bigger part of a shorter text.
  • body: rows searches only the body column. snippet() returns a short piece of text around the match, with the matched word wrapped in the markers you choose, such as [ ] or HTML <b> tags.
  • By default, words must match exactly: “grouping” finds only the window functions note. With tokenize = 'porter', words are cut back to their stem, so “grouping” also matches “groups” in the transactions note.

LIKE or Full-Text Search?

LIKE '%word%'FTS5 MATCH
Speed on large textReads every rowUses a word index
Matches inside wordsYes (“join” in “rejoin”)No, whole words (or prefixes with *)
RankingNoYes, with bm25
Phrases and AND/ORAwkwardBuilt in
Best forShort codes, small tablesArticles, descriptions, messages

Other databases have their own versions: tsvector and to_tsquery in PostgreSQL, FULLTEXT indexes with MATCH ... AGAINST in MySQL, and Full-Text Search in SQL Server.

Common Mistakes

  1. Sorting bm25 descending. In SQLite the best match has the lowest score.
  2. Passing user input straight into MATCH. Characters such as quotes, * and - have special meaning. Wrap user text in double quotes as a phrase, or clean it first.
  3. Expecting “run” to find “running” without the porter tokenizer or a prefix search.
  4. Keeping two copies out of sync. If the FTS table copies text from a normal table, use triggers or an external-content table so updates reach the index.

Practice Exercises

Exercise 1. Find notes whose title contains a word starting with “trans”.

Show answer
SELECT title FROM notes WHERE notes MATCH 'title: trans*';

This returns the Transactions note.

Exercise 2. Find notes that mention “table” but not “join”.

Show answer
SELECT title FROM notes WHERE notes MATCH 'table NOT join';

This returns the Indexes note.

Frequently Asked Questions

Does FTS5 work with Bangla text?

Yes, with one setting. The default unicode61 tokenizer treats Bangla vowel signs as separators, so a word like “বাংলায়” is stored as several broken pieces. Add the mark categories when you create the table: tokenize = "unicode61 categories 'L* N* Co M*'". Bangla words are then indexed whole. Stemming with porter works only for English.

Is FTS5 always available in SQLite?

It is included in most builds, including Python’s sqlite3 module and the official command-line tool. If CREATE VIRTUAL TABLE ... USING fts5 fails, your build was compiled without it.

Summary

  • FTS5 builds a word index for fast text search.
  • MATCH supports AND, OR, NOT, phrases, prefixes and column filters.
  • bm25() ranks results; lower is better in SQLite.
  • Use snippet() for previews and the porter tokenizer for English word forms.

Next: SQL Injection and Parameterized Queries.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *