Database Programming Features · Lesson 83 of 112

Database Full-text Search

What you will learn

  • Why LIKE '%word%' is a weak search tool
  • What full-text search does: it indexes words
  • How to search with AND, NOT, phrases, prefixes and columns
  • How results are ranked and highlighted
  • What stemming is

1. The problem with LIKE

To find articles about "tea", you could write WHERE body LIKE '%tea%'. It works for a tiny table, but it has three problems:

  • It scans every row and every character (an index cannot help a pattern that starts with %, lesson 7.4).
  • It matches parts of words (searching tea also finds "steam" and "instead").
  • It has no ranking: you cannot put the best match first.

A full-text index solves this. It breaks each text into words (tokens) and stores a list from each word to the rows containing it, like the index at the back of a book (lesson 7.1).

2. Searching with FTS5

SQLite includes a full-text module called FTS5. You create a special "virtual table" and then search it with MATCH. The browser's SQLite has it too (checked with the 3.39 engine the SQL cells use). Availability can depend on how SQLite was built, so a one-line test is worth doing on your machine.

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It adds small tables of its own to your browser's copy; run the examples from top to bottom, and Reset data starts again.

CREATE VIRTUAL TABLE articles USING fts5(title, body);
INSERT INTO articles VALUES
  ('Tea in Sylhet', 'The tea gardens of Sylhet grow green tea and black tea.'),
  ('Rice farming', 'Farmers plant rice in the rainy season. Rice needs water.'),
  ('Running a tea shop', 'A small shop sells tea, biscuits and rice cakes.');
SELECT title FROM articles WHERE articles MATCH 'tea' ORDER BY rowid;
SELECT title FROM articles WHERE articles MATCH 'tea AND rice' ORDER BY rowid;
SELECT title FROM articles WHERE articles MATCH 'tea NOT sylhet' ORDER BY rowid;
title
------------------
Tea in Sylhet
Running a tea shop
(2 rows)

title
------------------
Running a tea shop
(1 row)

title
------------------
Running a tea shop
(1 row)
CREATE VIRTUAL TABLE articles USING fts5(title, body);
INSERT INTO articles VALUES
  ('Tea in Sylhet', 'The tea gardens of Sylhet grow green tea and black tea.'),
  ('Rice farming', 'Farmers plant rice in the rainy season. Rice needs water.'),
  ('Running a tea shop', 'A small shop sells tea, biscuits and rice cakes.');
SELECT title FROM articles WHERE articles MATCH 'tea' ORDER BY rowid;
SELECT title FROM articles WHERE articles MATCH 'tea AND rice' ORDER BY rowid;
SELECT title FROM articles WHERE articles MATCH 'tea NOT sylhet' ORDER BY rowid;
title
------------------
Tea in Sylhet
Running a tea shop
(2 rows)

title
------------------
Running a tea shop
(1 row)

title
------------------
Running a tea shop
(1 row)
CREATE VIRTUAL TABLE articles USING fts5(title, body);
INSERT INTO articles VALUES
  ('Tea in Sylhet', 'The tea gardens of Sylhet grow green tea and black tea.'),
  ('Rice farming', 'Farmers plant rice in the rainy season. Rice needs water.'),
  ('Running a tea shop', 'A small shop sells tea, biscuits and rice cakes.');
SELECT title FROM articles WHERE articles MATCH 'tea' ORDER BY rowid;
SELECT title FROM articles WHERE articles MATCH 'tea AND rice' ORDER BY rowid;
SELECT title FROM articles WHERE articles MATCH 'tea NOT sylhet' ORDER BY rowid;
title
------------------
Tea in Sylhet
Running a tea shop
(2 rows)

title
------------------
Running a tea shop
(1 row)

title
------------------
Running a tea shop
(1 row)
  • 'tea' finds the two articles containing the word tea.
  • 'tea AND rice' needs both words.
  • 'tea NOT sylhet' needs tea but not Sylhet. Searches ignore upper and lower case.

More search forms:

SELECT title FROM articles WHERE articles MATCH 'farm*';
SELECT title FROM articles WHERE articles MATCH '"green tea"';
SELECT title FROM articles WHERE articles MATCH 'title:shop';
title
------------
Rice farming
(1 row)

title
-------------
Tea in Sylhet
(1 row)

title
------------------
Running a tea shop
(1 row)
SELECT title FROM articles WHERE articles MATCH 'farm*';
SELECT title FROM articles WHERE articles MATCH '"green tea"';
SELECT title FROM articles WHERE articles MATCH 'title:shop';
title
------------
Rice farming
(1 row)

title
-------------
Tea in Sylhet
(1 row)

title
------------------
Running a tea shop
(1 row)
SELECT title FROM articles WHERE articles MATCH 'farm*';
SELECT title FROM articles WHERE articles MATCH '"green tea"';
SELECT title FROM articles WHERE articles MATCH 'title:shop';
title
------------
Rice farming
(1 row)

title
-------------
Tea in Sylhet
(1 row)

title
------------------
Running a tea shop
(1 row)
  • 'farm*' is a prefix search: words starting with farm ("farming", "farmers").
  • '"green tea"' is a phrase: the two words next to each other, in that order.
  • 'title:shop' limits the search to the title column.

The sample data can be searched too. A full-text table is filled from a real table with INSERT ... SELECT:

CREATE VIRTUAL TABLE product_search USING fts5(name);
INSERT INTO product_search (rowid, name) SELECT product_id, name FROM products;
SELECT rowid, name FROM product_search WHERE product_search MATCH 'tea OR garden' ORDER BY rowid;
rowid  name
-----  -------------
    6  Tea kettle
   11  Garden gloves
(2 rows)
CREATE VIRTUAL TABLE txn_search USING fts5(description);
INSERT INTO txn_search (rowid, description) SELECT txn_id, description FROM transactions;
SELECT COUNT(*) AS card_or_atm FROM txn_search WHERE txn_search MATCH 'card OR atm';
SELECT rowid, description FROM txn_search WHERE txn_search MATCH 'card' ORDER BY rowid LIMIT 3;
card_or_atm
-----------
        987
(1 row)

rowid  description
-----  ------------
    4  Card payment
    6  Card payment
   23  Card payment
(3 rows)
CREATE VIRTUAL TABLE course_search USING fts5(title);
INSERT INTO course_search (rowid, title) SELECT course_id, title FROM courses;
SELECT rowid, title FROM course_search WHERE course_search MATCH 'science OR writing OR physics' ORDER BY rowid;
rowid  title
-----  ---------------
    4  General Science
    6  Physics
    8  Writing Skills
(3 rows)

3. Ranking and highlighting

Full-text engines can score how well each row matches. FTS5's bm25() function gives a score, where a lower (more negative) number means a better match. Sorting by it puts the best first:

SELECT title, round(bm25(articles), 3) AS score FROM articles WHERE articles MATCH 'rice' ORDER BY bm25(articles), rowid;
SELECT highlight(articles, 1, '[', ']') AS body FROM articles WHERE articles MATCH 'rice' ORDER BY rowid;
title               score
------------------  -----
Rice farming         -0.0
Running a tea shop   -0.0
(2 rows)

body
-------------------------------------------------------------
Farmers plant [rice] in the rainy season. [Rice] needs water.
A small shop sells tea, biscuits and [rice] cakes.
(2 rows)
SELECT title, round(bm25(articles), 3) AS score FROM articles WHERE articles MATCH 'rice' ORDER BY bm25(articles), rowid;
SELECT highlight(articles, 1, '[', ']') AS body FROM articles WHERE articles MATCH 'rice' ORDER BY rowid;
title               score
------------------  -----
Rice farming         -0.0
Running a tea shop   -0.0
(2 rows)

body
-------------------------------------------------------------
Farmers plant [rice] in the rainy season. [Rice] needs water.
A small shop sells tea, biscuits and [rice] cakes.
(2 rows)
SELECT title, round(bm25(articles), 3) AS score FROM articles WHERE articles MATCH 'rice' ORDER BY bm25(articles), rowid;
SELECT highlight(articles, 1, '[', ']') AS body FROM articles WHERE articles MATCH 'rice' ORDER BY rowid;
title               score
------------------  -----
Rice farming         -0.0
Running a tea shop   -0.0
(2 rows)

body
-------------------------------------------------------------
Farmers plant [rice] in the rainy season. [Rice] needs water.
A small shop sells tea, biscuits and [rice] cakes.
(2 rows)

The scores print as -0.0 here only because the table has three tiny rows, so the rounded numbers carry no information; on a real table they differ. The order still comes from the unrounded scores. highlight(articles, 1, '[', ']') wraps matches in column 1 (the body) in the markers you choose, which a website can turn into bold text.

4. Whole words and stemming

Full-text search matches whole words, unlike LIKE:

SELECT title FROM articles WHERE body LIKE '%farm%';
SELECT title FROM articles WHERE articles MATCH 'farmers';
SELECT title FROM articles WHERE articles MATCH 'farm';
title
------------
Rice farming
(1 row)

title
------------
Rice farming
(1 row)

title
-----
(0 rows)
SELECT title FROM articles WHERE body LIKE '%farm%';
SELECT title FROM articles WHERE articles MATCH 'farmers';
SELECT title FROM articles WHERE articles MATCH 'farm';
title
------------
Rice farming
(1 row)

title
------------
Rice farming
(1 row)

title
-----
(0 rows)
SELECT title FROM articles WHERE body LIKE '%farm%';
SELECT title FROM articles WHERE articles MATCH 'farmers';
SELECT title FROM articles WHERE articles MATCH 'farm';
title
------------
Rice farming
(1 row)

title
------------
Rice farming
(1 row)

title
-----
(0 rows)

Searching farm finds nothing, because no row contains the word "farm" itself (only "farming" and "farmers"). Users expect "farm" to find "farming". The fix is stemming: reducing words to a root form when indexing and searching. FTS5 offers a porter option:

CREATE VIRTUAL TABLE stemmed USING fts5(body, tokenize = 'porter');
INSERT INTO stemmed VALUES ('Farmers plant rice'), ('She is farming'), ('running shoes');
SELECT body FROM stemmed WHERE stemmed MATCH 'farm';
SELECT body FROM stemmed WHERE stemmed MATCH 'run';
body
--------------
She is farming
(1 row)

body
-------------
running shoes
(1 row)
CREATE VIRTUAL TABLE stemmed USING fts5(body, tokenize = 'porter');
INSERT INTO stemmed VALUES ('Farmers plant rice'), ('She is farming'), ('running shoes');
SELECT body FROM stemmed WHERE stemmed MATCH 'farm';
SELECT body FROM stemmed WHERE stemmed MATCH 'run';
body
--------------
She is farming
(1 row)

body
-------------
running shoes
(1 row)
CREATE VIRTUAL TABLE stemmed USING fts5(body, tokenize = 'porter');
INSERT INTO stemmed VALUES ('Farmers plant rice'), ('She is farming'), ('running shoes');
SELECT body FROM stemmed WHERE stemmed MATCH 'farm';
SELECT body FROM stemmed WHERE stemmed MATCH 'run';
body
--------------
She is farming
(1 row)

body
-------------
running shoes
(1 row)

With stemming, farm finds "farming" and run finds "running". Notice that "Farmers" was not reduced to the same root as "farm" by this stemmer, so it was not found. Stemming is a set of rules, not understanding, and it works for English text; other languages need their own handling.

Quick check: why does LIKE '%tea%' also find the word "steam"?

LIKE matches any text containing those letters, even inside another word. Full-text search matches whole words.

Worked example: search box for a help centre

A help site has 5,000 articles. A visitor types "refund policy".

  1. Index title and body in a full-text table (use the porter option so "refunds" matches "refund").
  2. Search "refund policy" as a phrase first; if there are few results, fall back to refund AND policy.
  3. Sort by bm25 so the best article comes first and show highlight snippets.
  4. Keep the full-text table in step with the real table (insert, update and delete in both, or use triggers, lesson 11.1).

The site and numbers are made up.

Other systems

Full-text search exists in most large databases (and in dedicated search engines), but the syntax differs: different column types, functions and ranking. Treat the ideas (tokens, an index of words, ranking, stemming) as portable and the commands as product-specific. Look up the documentation of the product you use.

Common mistakes

  • Using LIKE '%word%' for a real search box: slow, imprecise, unranked.
  • Forgetting to keep the search index in step with the main table.
  • Expecting stemming to be perfect. It is rule-based and imperfect.
  • Assuming FTS5 exists everywhere. Test it on your build of SQLite.
  • Ignoring user input. Search syntax characters such as quotes can break a query; clean or escape what users type.

Key takeaways

  • Full-text search indexes words, so it is fast, whole-word and rankable.
  • FTS5 supports AND, NOT, phrases, prefix * and column filters.
  • bm25() ranks matches (lower is better) and highlight() marks them.
  • Stemming (tokenize='porter') lets farm find farming; it is rule-based, so it is not perfect.
  • The ideas carry over to other products; the commands do not.

Practice

1. Give two problems with LIKE '%word%' as a search tool.

Show answer

Any two of: it scans every row, it matches parts of words, and it cannot rank results.

2. What does MATCH 'tea NOT sylhet' return in the lesson's data, and why?

Show answer

Only "Running a tea shop": it contains tea and not Sylhet; the first article contains Sylhet.

3. What is the difference between 'green tea' and '"green tea"'?

Show answer

Without quotes the two words are searched as separate terms (both must appear, anywhere); in quotes they must appear as an exact phrase, next to each other in order.

4. Why did MATCH 'farm' return nothing before stemming?

Show answer

Full-text search matches whole words, and no row contains the word "farm" itself, only "farming" and "farmers".

5. What does a lower bm25() value mean in FTS5?

Show answer

A better match, so you sort ascending to put the best result first.

6. After stemming was turned on, farm did not find "Farmers plant rice". What does that tell you about stemming?

Show answer

Stemming follows rules and does not understand meaning; that stemmer did not reduce "Farmers" to the same root as "farm".