Full-Text Search — Database

LIKE '%word%' matches fragments of letters: "milk" is found in "buttermilk", and "palm coffee" isn't found in "Palm Sugar Milk Coffee". LIKE also has no…

In the SQL lesson Filtering Data, LIKE was the way to search text: LIKE '%milk%' means "milk" anywhere. Use that LIKE for the search box of Sunset Coffee's menu, then type "milk". Toast appears too, and it isn't a milk drink at all.

A search box needs a different tool: full-text search (FTS), which finds words inside long text through an index of words, instead of matching fragments of letters row by row. Think of hashtags on social media. Tap #milk, and the app shows every post with that hashtag right away, because it already keeps a list of posts for each hashtag. Full-text search keeps the same kind of list for every word in the text. The hashtag is a word, and its list of posts is the list of rows that contain that word. LIKE '%milk%' is more like opening every post one by one and reading its caption letter by letter.

The menu we're searching

Sunset Coffee now has 6 menu items, each with a description:

id name description
1 Milk Coffee Espresso and fresh milk, just sweet enough.
2 Palm Sugar Milk Coffee Milk coffee with palm sugar. Fresh milk, real palm sugar.
3 Milk Tea Black tea pulled with sweet condensed milk.
4 Toast Thick buttermilk bread in three layers, chocolate and cheese.
5 Iced Black Coffee Coffee with no sugar and no milk.
6 Matcha Latte Japanese matcha with oat milk.

LIKE matches letters, not words

Here is a search for "milk" with LIKE, in the name and in the description:

SELECT id, name FROM products
WHERE name LIKE '%milk%' OR description LIKE '%milk%';

The result is 6 rows, the whole menu. Toast is in it because its description contains "buttermilk". LIKE '%milk%' means "the letters m, i, l, k in a row, anywhere", including in the middle of another word.

The second problem is in the query plan. EXPLAIN QUERY PLAN in front of that query answers SCAN products: SQLite reads every row, one by one. An ordinary (B-tree) index is sorted by the first letters. A % at the front means the first letters can be anything, so the index can't be used. With 6 rows you don't notice. With 600,000 descriptions, all read every time a customer types, you do.

The third problem: LIKE '%palm coffee%' returns 0 rows, even though Palm Sugar Milk Coffee exists. LIKE looks for those two words exactly side by side, in that order.

An index of words (inverted index)

Full-text search splits text into words (called tokens). This splitting step is called tokenizing. Then FTS builds an inverted index: a list of every word, and for each word, the rows that contain it. The inverted index is the list of posts for each hashtag from the picture above. SQLite has the FTS4 module (an add-on feature) and a newer version, FTS5. The SQLite that the Lab runs in your browser has the FTS4 module:

CREATE VIRTUAL TABLE products_fts USING fts4(content="products", name, description);
INSERT INTO products_fts(products_fts) VALUES ('rebuild');

SELECT rowid, name FROM products_fts WHERE products_fts MATCH 'milk';

The result is 5 rows: the items with id 1, 2, 3, 5 and 6. Toast is gone, because "buttermilk" is a word of its own. You can look inside the index through an fts4aux table (a helper table that shows what an FTS4 index holds). Below are four of its words. The term column is the word, documents is how many rows contain it, and occurrences is how many times it appears:

term documents occurrences
buttermilk 1 1
coffee 3 5
milk 5 9
palm 1 3

MATCH 'palm coffee' means both words must be there, wherever they are, so Palm Sugar Milk Coffee is found. The query plan now reads SCAN products_fts VIRTUAL TABLE INDEX 4:. On a virtual table, the number after INDEX matters, not the word SCAN: INDEX 4 is the FTS module's code for a search through the word index. If the module read every row, it would say INDEX 0.

One thing doesn't change: Iced Black Coffee still appears for "milk", because its description says "no milk". FTS matches words, not meaning.

Ranking: the best match on top

A good search sorts its results from most to least relevant. That's called ranking. The simplest way: count how many times the searched word appears. In FTS4, offsets() gives 4 numbers for each match, separated by spaces. So this query counts the numbers (the spaces + 1) and divides the count by 4. The result is the number of matches:

SELECT p.id, p.name,
  (length(offsets(products_fts)) - length(replace(offsets(products_fts), ' ', '')) + 1) / 4 AS hits
FROM products_fts
JOIN products p ON p.id = products_fts.rowid
WHERE products_fts MATCH 'milk'
ORDER BY hits DESC, p.id;
id name hits
2 Palm Sugar Milk Coffee 3
1 Milk Coffee 2
3 Milk Tea 2
5 Iced Black Coffee 1
6 Matcha Latte 1

LIKE can't sort like this: a row matches or it doesn't, that's all. Other databases have ready-made ranking: ts_rank in PostgreSQL, and the score from MATCH ... AGAINST in MySQL.

In PostgreSQL and MySQL

PostgreSQL uses two data types: tsvector (text already split into words, with their positions) and tsquery (the keywords you search for). For example, to_tsvector('simple', 'Milk coffee with palm sugar') gives 'coffee':2 'milk':1 'palm':4 'sugar':5 'with':3. 'simple' is the name of a configuration, the rules for how words are split and processed.

ALTER TABLE products ADD COLUMN search tsvector
  GENERATED ALWAYS AS (to_tsvector('simple', name || ' ' || description)) STORED;
CREATE INDEX products_search_idx ON products USING GIN (search);

SELECT name, ts_rank(search, query) AS rank
FROM products, to_tsquery('simple', 'coffee & palm') AS query
WHERE search @@ query
ORDER BY rank DESC;

MySQL uses a FULLTEXT index and MATCH ... AGAINST. Its default mode looks for rows that contain any of the words, then sorts them by relevance. When both words are required, use AGAINST ('+coffee +palm' IN BOOLEAN MODE): a + in front of a word means that word is required.

ALTER TABLE products ADD FULLTEXT INDEX products_ft (name, description);
SELECT name FROM products WHERE MATCH(name, description) AGAINST ('coffee palm');

In Laravel, the index is created in a migration and used with whereFullText(). Laravel turns it into MATCH ... AGAINST on MySQL and to_tsvector(...) @@ plainto_tsquery(...) on PostgreSQL:

$table->fullText(['name', 'description']); // in a migration

Product::whereFullText(['name', 'description'], 'coffee palm')->get();

Database FTS or a separate search engine?

A database's built-in FTS is enough for many apps. Separate search engines are programs made only for searching that run outside the database, such as Meilisearch, Algolia and Elasticsearch. Separate search engines are used when you need more:

Scale Budget Pick
small any PostgreSQL FTS, already in your database
medium free Meilisearch, open source, self-hosted (on your own server)
medium paid Algolia, a hosted service (Algolia runs the servers), you just pay
large any Elasticsearch, a cluster of many servers for very large data

In Laravel, Laravel Scout (Laravel's official search package) wraps these options: each option becomes a driver (a connector) in Scout. Start with the database driver, which searches your MySQL or PostgreSQL database directly. By default this driver uses LIKE, and it uses a full-text index for the columns you mark with SearchUsingFullText. If you later need typo tolerance, change SCOUT_DRIVER in the .env file (the app's settings file) to Meilisearch, Algolia or Typesense (another open source search engine). The search code, for example Product::search('coffee palm')->get(), stays the same.

⚠️ Searches that miss, are out of date, or throw errors

TL;DR: LIKE '%word%' matches fragments of letters: "milk" is found in "buttermilk", and "palm coffee" isn't found in "Palm Sugar Milk Coffee". LIKE also has no ranking (an order from the best match down), and its query plan is a SCAN of every row. Full-text search splits text into words and keeps an inverted index, a list of words and the rows that contain each word. So it searches through the index, matches whole words, and can sort by relevance (ranking). SQLite has the FTS4/FTS5 modules with the MATCH operator. PostgreSQL has tsvector (text split into words), tsquery (the words you search for), @@ (matches) and GIN indexes (a kind of index made for an inverted index). MySQL has FULLTEXT indexes with MATCH ... AGAINST. In Laravel, MySQL and PostgreSQL FTS are both used through whereFullText(). Need typo tolerance (search that survives typing mistakes), faceting (filters with their counts) or instant search (results change with every letter typed)? Use a separate search engine (a program made only for searching, outside the database): Meilisearch, Algolia or Elasticsearch.

⚡ LIKE matches letters, not words

Write:

SELECT id, name FROM products
WHERE name LIKE '%milk%' OR description LIKE '%milk%';
Guess first: Toast's description is "Thick buttermilk bread in three layers, chocolate and cheese", and Toast isn't a milk drink at all. Is Toast found too?

It is. Its description contains "buttermilk", and LIKE '%milk%' looks for the letters m, i, l, k in a row, anywhere.

Meaning: % means any text. LIKE with a % at the front can't use an index either, so it always does a SCAN (reads every row). LIKE also has no ranking (an order from the best match down).

⚡ An index of words

Write:

SELECT rowid, name FROM products_fts WHERE products_fts MATCH 'milk';

Meaning: Full-text search (FTS) splits text into words and keeps an inverted index, a list of words and the rows that contain each word. products_fts is an FTS4 table (SQLite's FTS module) that holds a word index of the name and description columns of products, and rowid is the row's id. MATCH 'milk' looks for the word "milk" through that index. Toast is no longer found, because "buttermilk" is a different word. The results can also be sorted by relevance (ranking).

⚡ When you need a search engine

Meaning: Need typo tolerance (search that survives typing mistakes), faceting (filters with their counts) or instant search (results change with every letter typed)? Use a separate search engine, a program made only for searching that runs outside the database, such as Meilisearch, Algolia or Elasticsearch. For simple search, the database's built-in FTS is enough.

In the exercise, the returned text must be exact, capital letters included, for example "PostgreSQL FTS".

What you will learn