Home > Articles

This chapter is from the book

This chapter is from the book

Using FULLTEXT Searches

MySQL includes the capability for performing full text searches. The full-text search engine allows you to look for words or phrases without using pattern-matching operations. There are three kinds of full-text search:

  • Natural language searching. The search string is parsed into words and the search looks for records containing these words.

  • Boolean mode searching. The search string is parsed into words, but words can be modified by operator characters that indicate specific requirements such as that a given word should be present or absent in matching records, or that records must contain an exact phrase.

  • Query expansion searching. This kind of search occurs in two phases. The first phase is a natural language search. Then a second search is done using the original search string concatenated with the most highly relevant matching records from the first search. This expands the search on the basis of the assumption that words related to the original search string will match relevant records that the original string did not.

Full-text search capability is enabled for a given table by creating a special kind of index and has the following characteristics:

  • Full-text searches are based on FULLTEXT indexes, which can be created only for MyISAM tables. Only CHAR, VARCHAR, and TEXT columns can be included in a FULLTEXT index.

  • Common words are ignored for FULLTEXT searches, where "common" means "present in at least half the records." It's especially important to remember this when you're setting up a test table to experiment with the FULLTEXT capability. Be sure to insert at least three records into your test table. If the table has just one or two records, every word in it will occur at least 50% of the time and you'll never get any results!

  • There is a built-in list of common words such as "the," "after," and "other" that are called "stopwords" and that are always ignored.

  • Words that are too short also are ignored. By default, "too short" is defined as fewer than four characters, but you can reconfigure the server to set the minimum length to a different value.

  • Words are defined as sequences of characters that include letters, digits, apostrophes, and underscores. This means that a string like "full-blooded" is considered to contain two words, "full" and "blooded." Normally, a full-text search matches whole words, not partial words, and the FULLTEXT engine considers a record to match a search string if it includes any of the words in the search string. A variant form of search called a boolean full-text search allows you to impose the additional constraint that all the words must be present (either in any order, or, to perform a phrase search, in exactly the order listed in the search string, including any punctuation). With a boolean search, it's also possible to match records that do not include certain words, or to add a wildcard modifier to match all words that begin with a given prefix.

  • A FULLTEXT index can be created for a single column or multiple columns. If it spans multiple columns, searches based on the index look through all the columns simultaneously. The flip side of this is that when you perform a search, you must specify a column list that corresponds exactly to the set of columns that matches some FULLTEXT index. For example, if you want to search col1 sometimes, col2 sometimes, and both col1 and col2 sometimes, you should have three indexes: one for each of the columns separately, and one that includes both columns.

The following examples show how to use full-text searching by creating FULLTEXT indexes and then performing queries on them using the MATCH operator. A script to create the table and some sample data to load into it are available in the fulltext directory of the sampdb distribution.

A FULLTEXT index is created much the same way as other indexes. That is, you can define it with CREATE TABLE when creating the table initially, or add it afterward with ALTER TABLE or CREATE INDEX. Because FULLTEXT indexes require you to use MyISAM tables, you can take advantage of one of the properties of the MyISAM storage engine if you're creating a new table to use for FULLTEXT searches: Table loading proceeds more quickly if you populate the table first and then add the indexes afterward, rather than loading data into an already indexed table. Suppose that you have a data file named apothegm.txt containing famous sayings and the people to whom they're attributed:

Aeschylus             Time as he grows old teaches many lessons
Alexander Graham Bell Mr. Watson, come here. I want you!
Benjamin Franklin     It is hard for an empty bag to stand upright
Benjamin Franklin     Little strokes fell great oaks
Benjamin Franklin     Remember that time is money
Miguel de Cervantes   Bell, book, and candle
Proverbs 15:1         A soft answer turneth away wrath
Theodore Roosevelt    Speak softly and carry a big stick
William Shakespeare   But, soft! what light through yonder window breaks?
Robert Burton         I light my candle from their torches.

If you want to search by phrase and attribution separately or together, you need to index each column separately, and also create an index that includes both columns. You can create, populate, and index a table named apothegm as follows:

CREATE TABLE apothegm (attribution VARCHAR(40), phrase TEXT) ENGINE = MyISAM;
LOAD DATA LOCAL INFILE 'apothegm.txt' INTO TABLE apothegm;
ALTER TABLE apothegm
  ADD FULLTEXT (phrase),
  ADD FULLTEXT (attribution),
  ADD FULLTEXT (phrase, attribution);

Natural Language FULLTEXT Searches

After setting up the table, perform natural language full-text searches on it using MATCH to name the column or columns to search and AGAINST() to specify the search string. For example:

mysql> SELECT * FROM apothegm WHERE MATCH(attribution) AGAINST('roosevelt');
+--------------------+------------------------------------+
| attribution        | phrase                             |
+--------------------+------------------------------------+
| Theodore Roosevelt | Speak softly and carry a big stick |
+--------------------+------------------------------------+
mysql> SELECT * FROM apothegm WHERE MATCH(phrase) AGAINST('time');
+-------------------+-------------------------------------------+
| attribution       | phrase                                    |
+-------------------+-------------------------------------------+
| Benjamin Franklin | Remember that time is money               |
| Aeschylus         | Time as he grows old teaches many lessons |
+-------------------+-------------------------------------------+
mysql> SELECT * FROM apothegm WHERE MATCH(attribution, phrase)
    -> AGAINST('bell');
+-----------------------+------------------------------------+
| attribution           | phrase                             |
+-----------------------+------------------------------------+
| Alexander Graham Bell | Mr. Watson, come here. I want you! |
| Miguel de Cervantes   | Bell, book, and candle             |
+-----------------------+------------------------------------+

In the last example, note how the query finds records that contain the search word in different columns, which demonstrates the FULLTEXT capability of searching multiple columns at once. Also note that the order of the columns as named in the query is attribution, phrase. That differs from the order in which they were named when the index was created (phrase, attribution), which illustrates that order does not matter. What matters is that there must be some FULLTEXT index that consists of exactly the columns named.

If you just want to see how many records a search matches, use COUNT(*):

mysql> SELECT COUNT(*) FROM apothegm WHERE MATCH(phrase) AGAINST('time');
+----------+
| COUNT(*) |
+----------+
|        2 |
+----------+

Output rows for natural language FULLTEXT searches are ordered by decreasing relevance when you use a MATCH expression in the WHERE clause. Relevance values are non-negative floating point values, with zero indicating "no relevance." To see these values, use a MATCH expression in the output column list:

mysql> SELECT phrase, MATCH(phrase) AGAINST('time') AS relevance
    -> FROM apothegm;
+-----------------------------------------------------+-----------------+
| phrase                                              | relevance       |
+-----------------------------------------------------+-----------------+
| Time as he grows old teaches many lessons           | 1.3253291845322 |
| Mr. Watson, come here. I want you!                  |               0 |
| It is hard for an empty bag to stand upright        |               0 |
| Little strokes fell great oaks                      |               0 |
| Remember that time is money                         | 1.3400621414185 |
| Bell, book, and candle                              |               0 |
| A soft answer turneth away wrath                    |               0 |
| Speak softly and carry a big stick                  |               0 |
| But, soft! what light through yonder window breaks? |               0 |
| I light my candle from their torches.               |               0 |
+-----------------------------------------------------+-----------------+

A natural language search finds records that contain any of the search words, so a query such as the following returns records with either "hard" or "soft":

mysql> SELECT * FROM apothegm WHERE MATCH(phrase)
    -> AGAINST('hard soft');
+---------------------+-----------------------------------------------------+
| attribution         | phrase                                              |
+---------------------+-----------------------------------------------------+
| Benjamin Franklin   | It is hard for an empty bag to stand upright        |
| Proverbs 15:1       | A soft answer turneth away wrath                    |
| William Shakespeare | But, soft! what light through yonder window breaks? |
+---------------------+-----------------------------------------------------+

Boolean Mode FULLTEXT Searches

Greater control over multiple-word matching can be obtained by using boolean mode FULLTEXT searches. This type of search is performed by adding IN BOOLEAN MODE after the search string in the AGAINST() function. Boolean searches have the following characteristics:

  • The 50% rule is ignored; searches find words even if they occur in more than half of the records.

  • Results are not sorted by relevance.

  • Modifiers may be applied to words in the search string. A leading plus or minus sign requires a word to be present or not present in matching records. For example, a search string of 'bell' matches records that contain "bell," but a search string of '+bell -candle' in boolean mode matches only records that contain "bell" and do not contain "candle."

  • mysql> SELECT * FROM apothegm
        -> WHERE MATCH(attribution, phrase)
        -> AGAINST('bell');
    +-----------------------+------------------------------------+
    | attribution           | phrase                             |
    +-----------------------+------------------------------------+
    | Alexander Graham Bell | Mr. Watson, come here. I want you! |
    | Miguel de Cervantes   | Bell, book, and candle             |
    +-----------------------+------------------------------------+
    mysql> SELECT * FROM apothegm
        -> WHERE MATCH(attribution, phrase)
        -> AGAINST('+bell -candle' IN BOOLEAN MODE);
    +-----------------------+------------------------------------+
    | attribution           | phrase                             |
    +-----------------------+------------------------------------+
    | Alexander Graham Bell | Mr. Watson, come here. I want you! |
    +-----------------------+------------------------------------+

    A trailing asterisk acts as a wildcard so that any record containing words beginning with the search word match. For example 'soft*' matches "soft," "softly," "softness," and so forth:

    mysql> SELECT * FROM apothegm WHERE MATCH(phrase)
        -> AGAINST('soft*' IN BOOLEAN MODE);
    +---------------------+-----------------------------------------------------+
    | attribution         | phrase                                              |
    +---------------------+-----------------------------------------------------+
    | Proverbs 15:1       | A soft answer turneth away wrath                    |
    | William Shakespeare | But, soft! what light through yonder window breaks? |
    | Theodore Roosevelt  | Speak softly and carry a big stick                  |
    +---------------------+-----------------------------------------------------+

    However, the wildcard feature cannot be used to match words shorter than the minimum index word length.

    The full set of boolean mode modifiers is listed under the entry for MATCH in Appendix C, "Operator and Function Reference."

  • Stop words are ignored just as for natural language searches, even if marked as required. A search for '+Alexander +the +great' finds records containing "Alexander" and "great," but ignores "the" as a stopword.

  • A phrase search can be performed to require all words to be present in a particular order. Enclose the phrase within double quotes, and include punctuation and whitespace that is present in the phrase you want to match. In other words, you must specify the exact phrase:

  • mysql> SELECT * FROM apothegm
        -> WHERE MATCH(attribution, phrase)
        -> AGAINST('"bell book and candle"' IN BOOLEAN MODE);
    Empty set (0.00 sec)
    mysql> SELECT * FROM apothegm
        -> WHERE MATCH(attribution, phrase)
        -> AGAINST('"bell, book, and candle"' IN BOOLEAN MODE);
    +---------------------+------------------------+
    | attribution         | phrase                 |
    +---------------------+------------------------+
    | Miguel de Cervantes | Bell, book, and candle |
    +---------------------+------------------------+
  • If you want to use IN BOOLEAN MODE searches with tables that were initially created before that capability was added (MySQL 4.0.2), you must rebuild the indexes entirely. Do so like this:

  • REPAIR TABLE tbl_name USE_FRM;
  • It's possible to perform a boolean mode full-text search on columns that are not part of a FULLTEXT index, although this is much slower than using indexed columns.

Query Expansion FULLTEXT Searches

A full-text search with query expansion performs a two-phase search. The initial search is like a regular natural language search. Then the most highly relevant records from this search are used for the second phase. The words in these records are used along with the original search terms to perform a second search. Because the set of search terms is larger, the result generally includes records that are not found in the first phase but are related to them.

To perform this kind of search, add WITH QUERY EXPANSION following the search terms. The following example provides an illustration. The first query shows a natural language search. The second query shows a query expansion search. Its result includes an extra record that contains none of the original search terms. This record is found because it contains the word "candle" that is present in one of the records found by the natural language search.

mysql> SELECT * FROM apothegm
    -> WHERE MATCH(attribution, phrase)
    -> AGAINST('bell book');
+-----------------------+------------------------------------+
| attribution           | phrase                             |
+-----------------------+------------------------------------+
| Miguel de Cervantes   | Bell, book, and candle             |
| Alexander Graham Bell | Mr. Watson, come here. I want you! |
+-----------------------+------------------------------------+
mysql> SELECT * FROM apothegm
    -> WHERE MATCH(attribution, phrase)
    -> AGAINST('bell book' WITH QUERY EXPANSION);
+-----------------------+---------------------------------------+
| attribution           | phrase                                |
+-----------------------+---------------------------------------+
| Miguel de Cervantes   | Bell, book, and candle                |
| Alexander Graham Bell | Mr. Watson, come here. I want you!    |
| Robert Burton         | I light my candle from their torches. |
+-----------------------+---------------------------------------+

Configuring the FULLTEXT Search Engine

Several full-text parameters are configurable and can be modified by setting system variables. The parameters that determine the shortest and longest words to index in FULLTEXT indexes are ft_min_word_len and ft_max_word_len. Words with lengths outside the range defined by these two variables are ignored when FULLTEXT indexes are built. The default minimum value is 4. The default maximum value depends on your server version. Currently in MySQL 4.1, the maximum is 84.

Suppose that you want to change the minimum word length from 4 to 3. Do so like this:

  1. Start the server with the ft_min_word_len variable set to 3. To ensure that this happens whenever the server starts, it's best to place the setting in an option file such as /etc/my.cnf:

  2. [mysqld]
    set-variable = ft_min_word_len=3
  3. For any existing tables that already have FULLTEXT indexes, you must rebuild those indexes. You can drop and add the indexes, but it's easier and sufficient to perform a quick repair operation:

  4. REPAIR TABLE tbl_name QUICK;
  5. Any new FULLTEXT indexes that you create after changing the parameter will use the new value automatically.

For more information on setting system variables, see Appendix D. For details on using option files, see Appendix F.

Note: If you use myisamchk to rebuild indexes for a table that contains any FULLTEXT indexes, see the FULLTEXT-related notes in the myisamchk description in Appendix F.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020