欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

教你怎样在MySQL中提高全文搜索效率_MySQL

程序员文章站 2022-05-06 14:48:52
...
  很多互联网应用程序都提供了全文搜索功能,用户可以使用一个词或者词语片断作为查询项目来定位匹配的记录。在后台,这些程序使用在一个SELECT查询中的LIKE语句来执行这种查询,尽管这种方法可行,但对于全文查找而言,这是一种效率极端低下的方法,尤其在处理大量数据的时候。

  MySQL针对这一问题提供了一种基于内建的全文查找方式的解决方案。在此,开发者只需要简单地标记出需要全文查找的字段,然后使用特殊的MySQL方法在那些字段运行搜索,这不仅仅提高了性能和效率(因为MySQL对这些字段做了索引来优化搜索),而且实现了更高质量的搜索,因为MySQL使用自然语言来智能地对结果评级,以去掉不相关的项目。

  1、设置基本表格

  从创建例子表格开始,使用以下的SQL命令:

mysql> CREATE TABLE reviews (id INT(5)
PRIMARY KEY NOT NULL AUTO_INCREMENT, data TEXT);
  以上命令创建了一个简单的音乐专集资料库(主要是整段的文字),然后向这个表格中添加一些记录:

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!');

  验证数据的正确录入:

  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)
  2、定义全文搜索字段

  接下来,定义您要作为全文搜索索引的字段:

  mysql> ALTER TABLE reviews ADD FULLTEXT INDEX (data);
  Query OK, 3 rows affected (0.21 sec)
  Records: 3 Duplicates: 0 Warnings: 0
  使用SHOW INDEXES命令来检查索引已经被添加了:

  mysql> SHOW INDEXES FROM reviews;
  +---------+---------------+--------+------+------------+---------+
  | Table  | Column_name  | Packed | Null | Index_type | Comment |
  ----------+---------------+--------+------+------------+---------+
  | reviews | id      | NULL  |   | BTREE   |     |
  | reviews | data     | NULL  | YES | FULLTEXT  |     |
  +---------+---------------+--------+------+------------+---------+
  2 rows in set (0.01 sec)
  | 2 |

  +----+

  2 rows in set (0.00 sec)