Using Fulltext Indexes in MySQL – Part 1

One of the more useful MySQL features is the ability to search for text using a FULLTEXT index. Currently this is only available if you use the MyISAM table type (which is the default table type, so if you don’t know what table type you’re using, it’ll most likely be MyISAM). A fulltext index can be created for a TEXT, CHAR or VARCHAR type field, or combination of fields. We’re going to create a sample table and use it to explore the various features.

The simple form of usage (the MATCH() function) is available to all MySQL servers from version 3.23.23, while the more complex usage (the IN BOOLEAN MODE modifier) is available from version 4. The first part of this article looks at the former, and the second part at the latter.

A sample table

We’re going to use the following table throughout this tutorial.

CREATE TABLE fulltext_sample(copy TEXT,FULLTEXT(copy)) TYPE=MyISAM;

The TYPE=MyISAM clause isn’t necessary unless you’ve set the default table type to be something other than MyISAM (perhaps you use InnoDB tables to make use of MySQL’s transactional capabilities). Once you’ve created the table, populate it with some data, as follows:

INSERT INTO fulltext_sample VALUES
('It appears good from here'), 
('The here and the past'), 
('Why are we hear'), 
('An all-out alert'), 
('All you need is love'), 
('A good alert');

If you’d already created an existing table, you can add a FULLTEXT index with the ALTER TABLE statement (as well as the CREATE INDEX statement), for example:

ALTER TABLE fulltext_sample ADD FULLTEXT(copy)

Searching for text

The syntax of a FULLTEXT search is simple. You MATCH the field AGAINST the text you are searching for, for example:

mysql> SELECT * FROM fulltext_sample WHERE MATCH(copy) AGAINST('love');
| copy                 |
| All you need is love |

Searches on a FULLTEXT index are performed case-insensitively (as are searches on TEXT and non-binary VARCHAR fields generally). So the following works as well:

mysql> SELECT * FROM fulltext_sample WHERE MATCH(copy) AGAINST('LOVE');
| copy                 |
| All you need is love |

FULLTEXT indexes are most often used to search natural language text, such as through newspaper articles, web page contents and so on. For this reason MySQL has added a number of features to assist this kind of searching. MySQL does not index any words less than or equal to 3 characters in length, nor does it index any words that appear in more than 50% of the rows. This means that if your table contains 2 or less rows, a search on a FULLTEXT index will never return anything. In future, MySQL will make this behavior more flexible, but for now it should suit most natural language uses. If most fields in your database contain the word ‘music’, you probably don’t want these records returned, You can use the IN BOOLEAN MODE modifier to get around the 50% threshold, as you’ll see in Part 2 of this article.

Results are returned in order of relevance, from highest to lowest.

The main features

A list of the main features of a standard FULLTEXT search follows:

  • Excludes partial words
  • Excludes words less than 4 characters in length (3 or less)
  • Excludes words that appear in more than half the rows (meaning at least 3 rows are required)
  • Hyphenated words are treated as two words
  • Rows are returned in order of relevance, descending
  • Words in the stopword list (common words) are also excluded from the search results. The stopword list is based upon common English words, so if your data is used for a different purpose, you’ll probably want to change the list. Unfortunately, doing so at present is not easy. You’ll need to edit the file myisam/ft_static.c. recompile MySQL, and rebuild the indexes! To save you hunting through the source, or if you have a binary version of MySQL, here is a list of stopwords. Note that these can and do change with different versions. To be absolutely sure, you’ll have to check the specific list for your version.



Let's have a look at some of the consequences of this. If you were a bit lazy in your typing, and tried 'to look for the word 'love', as follows:
mysql> SELECT * FROM fulltext_sample WHERE MATCH(copy) AGAINST('lov');
Empty set (0.00 sec)

you'd get nothing back, as the FULLTEXT index only contains complete words, not partial words. You'd have to write the full word to get anything back, as you did in the first example.

As mentioned, hyphenated words are also excluded from the FULLTEXT index (they are indexed as separate words), so the following also returns nothing:

mysql> SELECT * FROM fulltext_sample WHERE MATCH(copy) AGAINST('all-out');
Empty set (0.00 sec)

Unfortunately, both words are less than the required 4 letters, so they don't appear on their own either, and cannot be found at all with an ordinary search. Part 2 of this tutorial looks at BOOLEAN MODE searches when you can search for partial or hyphenated words.

You can also search for more than one word at a time, by separating the words with commas. Try and return records containing the words 'here' and 'appears', as follows:

mysql> SELECT * FROM fulltext_sample WHERE MATCH(copy) AGAINST('here');
Empty set (0.01 sec)

Unexpectedly this returns nothing. But, a more careful look at the stopword list shows
this word is listed, so they are excluded from the index. Stopwords are a common cause of people complaining that the MySQL FULLTEXT index facility is not working properly. If your query does return a result, then the stopword list in your version of MySQL does not contain the word 'here'.


The following example shows how the records are returned in order of precedence:

mysql> SELECT * FROM fulltext_sample WHERE MATCH(copy) AGAINST('good,alert');
| copy                      |
| A good alert              |
| It appears good from here |
| An all-out alert          |

The record 'A good alert' appears first, as it contains both words being searched for. You don't have to believe me - just ask MySQL to display the precedence in the results. Simply repeat the MATCH() function in the field list, as follows:

mysql> SELECT copy,MATCH(copy) AGAINST('good,alert') AS relevance 
FROM fulltext_sample WHERE MATCH(copy) AGAINST('good,alert');
| copy                      | relevance        |
| A good alert              |  1.3551264824316 |
| An all-out alert          | 0.68526663197496 |
| It appears good from hear | 0.67003110026735 |

The relevance calculation is fairly complex and is based upon the number of words in the index, the number of unique words in that row, the total number of words in both the index and the result, as well as the weight of the word (for the average English sentence, the word 'cool' will be weighted less, and therefore have a lower relevance, than the word 'dandy', though trends can change!). The figures may differ in your version of MySQL, as MySQL does occasionally tweak the calculation algorithms.

While the standard FULLTEXT search is fairly useful and sufficient for many, MySQL 4 takes it much further. Part 2 of this article looks at BOOLEAN FULLTEXT searches, which offer a lot more functionality.

Ian Gilfillan
Ian Gilfillan
Ian Gilfillan lives in Cape Town, South Africa. He is the author of the book 'Mastering MySQL 4', published by Sybex, and has been working with MySQL since 1997. These days he develops mainly in PHP and MySQL, although confesses to starting out with BASIC and COBOL, way back when, and still has a soft spot for Perl. He developed South Africa's first online grocery store, and has developed and taught internet development and other technical courses for various institutions. He has majors in Programming and Information Systems, as well as English and Philosophy. For 5 years he was Lead Developer and IT Manager for Independent Online, South Africa's premier news portal. However, he has now 'retired' from fulltime work, and is hoping that his next book will be more in the style of William Blake and Allen Ginsberg.
Get the Free Newsletter!
Subscribe to Cloud Insider for top news, trends & analysis
This email address is invalid.
Get the Free Newsletter!
Subscribe to Cloud Insider for top news, trends & analysis
This email address is invalid.

Latest Articles