MySQL FULLTEXT search

You can turn user input into safe boolean-mode prefix terms and query a FULLTEXT index while keeping ID-based pagination valid in W2O2.

Learning outcomes

  • Explain why LIKE '%word%' cannot use a B+tree index efficiently, while a known prefix can.
  • Describe how a FULLTEXT inverted index finds words inside restaurant names.
  • Use boolean-mode required terms and prefix matching to enforce the restaurant search contract.
  • Convert user input into safe search terms, including Unicode letters and digits, without allowing supplied characters to become boolean operators.
  • Preserve ID-based keyset pagination when adding FULLTEXT search through a migration and sqlc query.

A customer searching for piz should find Pizza Palace, Pizzeria Roma, Dominos Pizza and Late Night Pizza Corner. A search for pizza palace should return only Pizza Palace, because every word in the query must match. Your existing restaurant list uses ID-based pagination, so adding name search must not change how pages continue.

String prefixes and B+tree indexes

A normal B+tree index stores values in sorted order. A Secondary index on restaurants.name can help MySQL find names that begin with a known prefix.

sql
SELECT id, name
FROM restaurants
WHERE name LIKE 'piz%';

MySQL can use the known starting prefix to locate a range of matching names. But this query cannot find Dominos Pizza, because piz appears after the beginning of the complete name.

A leading wildcard removes that starting point:

sql
SELECT id, name
FROM restaurants
WHERE name LIKE '%pizza%';

This can find Dominos Pizza, but an ordinary B+tree index cannot efficiently seek to a known starting range. MySQL may need to examine many names as the catalogue grows.

The distinction is about the position of the match. A prefix of the complete name can use a B+tree range. A word appearing anywhere in the name needs a different search structure.

Word-oriented indexing

A FULLTEXT index supports word-oriented searches within text. It uses an inverted index: instead of sorting complete names, it maps indexed words to the rows that contain them.

For example, a simplified index might look like this:

pizza   -> Pizza Palace, Dominos Pizza, Late Night Pizza Corner
pizzeria -> Pizzeria Roma
burger  -> Burger Barn
palace  -> Pizza Palace

A search for pizza can find the word even when it appears at the end of Dominos Pizza. A search for piz can also match the start of Pizzeria.

You create a FULLTEXT index on the restaurant name column:

sql
ALTER TABLE restaurants
ADD FULLTEXT INDEX ft_rest_name (name);

For this course, the index belongs in migration 0003. MySQL maintains the index as rows are inserted, updated and deleted.

You query the indexed column with MATCH and AGAINST:

sql
SELECT id, name
FROM restaurants
WHERE MATCH(name) AGAINST ('pizza');

This is different from searching the complete string with LIKE. MySQL uses word information from the FULLTEXT index to find candidate rows.

FULLTEXT token rules

FULLTEXT indexes have token limits. InnoDB normally ignores words shorter than innodb_ft_min_token_size, which defaults to 3 characters. The configured stopword list also excludes common words from indexing and searching.

That means a word can appear in a restaurant name but still be unavailable to FULLTEXT search. For example, a two-character token may be too short under the default configuration.

Case handling depends on the indexed column's collation. With a case-insensitive collation, PIZZA and pizza match the same indexed words. The W2O2 search contract expects case-insensitive results.

Natural language and boolean mode

MySQL offers natural-language and boolean-mode search options for FULLTEXT queries.

Natural-language mode treats the supplied text as a search query and calculates relevance scores. It is useful when you want MySQL to rank results by how relevant they are.

Boolean mode gives you control over which terms must match. Its operators include:

  • + requires a term to match.
  • - excludes a term.
  • * at the end of a term enables prefix matching.
  • () groups expressions.
  • " marks a phrase.

For example:

sql
SELECT id, name
FROM restaurants
WHERE MATCH(name) AGAINST ('+piz*' IN BOOLEAN MODE);

The + requires a match. The trailing * allows a word beginning with piz to match. This can find both Pizza Palace and Pizzeria Roma.

You can require multiple words:

sql
SELECT id, name
FROM restaurants
WHERE MATCH(name) AGAINST ('+pizza* +palace*' IN BOOLEAN MODE);

Both terms must match. Pizza Palace qualifies, but a restaurant that contains only pizza does not.

This is the matching rule W2O2 needs: every searchable word in q must match a whole word or the start of one. A query for pizza burger returns no results from the test fixture because no restaurant name contains both words.

Building a safe search expression

Boolean mode creates an input-handling problem. Characters such as +, -, *, parentheses and quotes have meanings to the search parser.

A parameterized SQL query protects the SQL statement from injection. It does not prevent the value of a parameter from changing the meaning of the boolean-mode expression.

For example, binding this input is safe at the SQL statement level:

pizza -palace

But MySQL still interprets - as a boolean operator. The user could exclude palace results even though the application intends punctuation to be plain text.

Build the search expression from the user's words instead of forwarding the original input. Extract consecutive runs of Unicode letters and digits, then add the operators your application supports.

Input:       pizza -palace
Extracted:   pizza, palace
Expression:  +pizza* +palace*

Another example:

Input:       +pizza* (roma)
Extracted:   pizza, roma
Expression:  +pizza* +roma*

The generated expression requires both words and allows each to match a prefix. User-supplied operators are discarded before the database sees the expression.

In Go, use Unicode-aware character checks when extracting words:

go
for _, r := range q {
    if unicode.IsLetter(r) || unicode.IsDigit(r) {
        word.WriteRune(r)
    } else {
        flushWord()
    }
}

This preserves letters and digits beyond ASCII. Do not restrict the search to a through z and 0 through 9.

Validate the original q at the HTTP boundary as well. W2O2 rejects a query longer than 100 characters or one containing no searchable Unicode letter or digit. Return 400 invalid_parameter with field set to q.

Search ordering and keyset pagination

FULLTEXT can calculate relevance scores, but the restaurant list already uses an ID-based cursor. Keep the search query ordered by restaurant ID so it preserves the existing Keyset pagination contract.

Consider these matching restaurants:

Pizza Palace
Dominos Pizza
Pizza Express
Pizzeria Roma

The search expression decides which rows qualify. The ID decides their order.

sql
SELECT id, name, lat, lng
FROM restaurants
WHERE is_active = 1
  AND lat BETWEEN sqlc.arg(min_lat) AND sqlc.arg(max_lat)
  AND lng BETWEEN sqlc.arg(min_lng) AND sqlc.arg(max_lng)
  AND id > sqlc.arg(after_id)
  AND MATCH(name) AGAINST (sqlc.arg(query) IN BOOLEAN MODE)
ORDER BY id
LIMIT ?;

After returning a page, the next cursor uses the final restaurant ID. The next request continues with IDs greater than that position.

Ordering by relevance would change the pagination problem. Multiple restaurants can have the same score, and scores can change when indexed content changes. A relevance-based cursor would need to carry the score and a unique tie-breaker. ID ordering avoids that change and remains compatible with W2O1's signed cursors.

The trade-off is that the first result is not necessarily the most relevant. For this exercise, predictable pagination matters more than relevance ranking.

Database and application boundaries

Keep the ordinary restaurant-list query separate from the FULLTEXT search query. The ordinary query handles requests without q. The search query adds a MATCH condition while retaining the active-status filter, geographic bounds, ID cursor condition, ordering and limit.

Put the FULLTEXT index in backend/db/migrations/ and the parameterized search query in backend/db/queries/. Use a versioned database migration so fresh and existing development databases can apply the same schema change.

Use sqlc to generate the Go parameter and result types from the SQL query. This keeps the SQL definition and generated database access code in sync.

The service can receive a separate search dependency through an interface. That keeps the search query from changing the existing query interface used by ordinary restaurant listing. The HTTP handler validates q, and the service uses the search dependency only when a query is present.

Search behaviour in W2O2

The exercise uses a fixture containing Pizza Palace, Pizzeria Roma, Burger Barn, Dominos Pizza, Pasta House, Pizza Closed, Pizza Faraway and Late Night Pizza Corner.

A query for pizza must not return Pizza Closed, because that restaurant is inactive, or Pizza Faraway, because it is outside the requested geographic bounds. Search adds a name condition; it does not replace the filters already used by the restaurant list.

For q=piz and limit=3, the four matching restaurants must appear across two pages, containing three and one results. Following next_cursor must visit each matching restaurant exactly once.

Check your understanding

Question 1 of 4

The restaurants table has a B+tree index on name. A search for Dominos Pizza uses LIKE '%pizza%'. Why can this query become expensive as the table grows?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (MySQL 8.4).

Finished Lesson 2.23?