Get better search results in MySQL

Source: Internet
Author: User
Many Internet applications provide full-text search functions. Users can use a word or word segment as a query item to locate matching records. In the background, these programs use the LIKE statement in a SELECT query to execute this query. Although this method is feasible, it is an extremely inefficient method for full-text search, especially in

Many Internet applications provide full-text search functions. Users can use a word or word segment as a query item to locate matching records. In the background, these programs use the LIKE statement in a SELECT query to execute this query. Although this method is feasible, it is an extremely inefficient method for full-text search, especially in

Many Internet applications provide full-text search functions. Users can use a word or word segment as a query item to locate matching records. In the background, these programs use the LIKE statement in a SELECT query to execute this query. Although this method is feasible, it is an extremely inefficient method for full-text search, especially when processing a large amount of data.

MySQL provides a built-in full-text search solution for this problem. Here, developers only need to simply mark the fields that require full-text search, and then use special MySQL methods to run search on those fields, this not only improves the performance and efficiency (because MySQL indexes these fields to optimize the search), but also achieves higher quality search, because MySQL uses natural language to intelligently rate the results to remove irrelevant items.

This article will show you how to perform full-text search in MySQL.

Use the following SQL command to create an example table:

mysql> CREATE TABLE reviews (id INT(5) PRIMARY KEY NOT NULL 
AUTO_INCREMENT, data TEXT);

The above command creates a simple music album database (mainly text in the entire segment), and then adds some records to the table:

mysql> INSERT INTO `reviews` (`id`, `data`) VALUES
(1, 'Gingerboy has a new single out called Throwing Rocks.
It\'s great!');
mysql> INSERT INTO `reviews` (`id`, `data`) VALUES
(2, 'Hello all, I really like the new Madonna single.
One of the hottest tracks currently playing...I\'ve been
listening to it all day');
mysql> INSERT INTO `reviews` (`id`, `data`)
VALUES (3, 'Have you heard the new band Hotter Than Hell?
They have five members and they burn their instruments
when they play in concerts.
These guys totally rock! Like, awesome, dude!');

Verify that the data is entered correctly:

mysql> SELECT * FROM reviews;
+----+--------------------------------------------+
id data                                      
+----+--------------------------------------------+
  1 Gingerboy has a new single out called ... 
  2 Hello all, I really like the new Madon ...
  3 Have you heard the new band Hotter Than...
+----+--------------------------------------------+
3 rows in set (0.00 sec)

Next, define the fields to be indexed as full-text search

mysql> ALTER TABLE reviews ADD FULLTEXT INDEX (data);
Query OK, 3 rows affected (0.21 sec)
Records: 3  Duplicates: 0  Warnings: 0

Run the show indexes command to check whether the index has been added:

mysql> SHOW INDEXES FROM reviews;
+---------+---------------+--------+------+------------+---------+
Table   Column_name   Packed Null Index_type Comment
----------+---------------+--------+------+------------+---------+
reviews   id           NULL         BTREE              
reviews   data         NULL   YES  FULLTEXT           
+---------+---------------+--------+------+------------+---------+


When you have data and indexes, you can use MySQL full-text search. The simplest full-text search method is with MATCH... the SELECT query of the AGAINST statement. The following is a simple example to find records containing the word "single:

mysql> SELECT id FROM reviews WHERE MATCH (data) AGAINST ('single');+----+
id
+----+
  1
  2
+----+

2 rows in set (0.00 sec)

Here, MATCH () compares the text in the field passed to it as a parameter with the parameter passed to AGAINST (). If there is a MATCH, it is returned in the normal way. Note that you can pass more than one field and use MATCH () to view it. You only need to use commas to split the field list.

When MySQL receives a full-text search request, it scores each record internally, and the non-matching record score is zero, the "more relevant" record will get a relatively higher score than the "less relevant" record. Relevance is determined by a series of MySQL differentiation standards. You can view the MySQL user manual to obtain more information.

To view the score of each record, you only need to return the MATCH () method as part of the result set, as shown below:

mysql> SELECT id, MATCH (data) AGAINST ('rock') FROM reviews;
+----+-------------------------------+
id MATCH (data) AGAINST ('rock')
+----+-------------------------------+
  1                              0
  2                              0
  3                1.3862514533815
+----+-------------------------------+

3 rows in set (0.00 sec)

You can also use the logical search modifier for more accurate search, which is achieved by adding a special in boolean mode modifier to the AGAINST statement. IN the following example, the record containing the word "single" but not "Madonna" will be searched:

mysql> SELECT id FROM reviews WHERE MATCH (data) AGAINST ('+single 
-madonna' IN BOOLEAN MODE);
+----+
id
+----+
  1
+----+

1 row in set (0.00 sec)

This search feature is usually used to search for a word segment (rather than a complete word), which can be achieved through the * (asterisk) operator IN the in boolean mode statement, the following example shows how to find records with "hot" In a word:

mysql> SELECT id FROM reviews WHERE MATCH (data) AGAINST ('hot*' 
IN BOOLEAN MODE);+----+
id
+----+
  3
  2
+----+

2 rows in set (0.00 sec)

You can also use this method to find at least one parameter passed to AGAINST. The following example finds a record that contains at least one of the words "hell" and "rocks:

mysql> SELECT id FROM reviews WHERE MATCH (data) AGAINST ('hell 
rocks' IN BOOLEAN MODE);
+----+
id
+----+
  1
  3
+----+

3 rows in set (0.00 sec)

The above examples demonstrate the comparison with the traditional SELECT... LIKE statement, a more effective method for full-text search, when you need to write the MySQL database search interface next time, you can try this method.

(Responsible editor: Haina baichuan qlmzl11268@hotmail.com TEL :( 010) 68476606-8007)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.