mysql reference manual for version 4.1.0-alpha.
6.8 mysql 全文搜索
到 3.23.23 时,mysql 开始支持全文索引和搜索。全文索引在 mysql 中是一个 fulltext 类型索引。fulltext 索引用于 myisam 表,可以在 create table 时或之后使用 alter table 或 create index 在 char、varchar 或 text 列上创建。对于大的数据库,将数据装载到一个没有 fulltext 索引的表中,然后再使用 alter table (或 create index) 创建索引,这将是非常快的。将数据装载到一个已经有 fulltext 索引的表中,将是非常慢的。
全文搜索通过 match() 函数完成。
mysql> create table articles (
-> id int unsigned auto_increment not null primary key,
-> title varchar(200),
-> body text,
-> fulltext (title,body)
-> );
query ok, 0 rows affected (0.00 sec)
mysql> insert into articles values
-> (null,'mysql tutorial', 'dbms stands for database ...'),
-> (null,'how to use mysql efficiently', 'after you went through a ...'),
-> (null,'optimising mysql','in this tutorial we will show ...'),
-> (null,'1001 mysql tricks','1. never run mysqld as root. 2. ...'),
-> (null,'mysql vs. yoursql', 'in the following database comparison ...'),
-> (null,'mysql security', 'when configured properly, mysql ...');
query ok, 6 rows affected (0.00 sec)
records: 6 duplicates: 0 warnings: 0
mysql> select * from articles
-> where match (title,body) against ('database');
+----+-------------------+------------------------------------------+
| id | title | body |
+----+-------------------+------------------------------------------+
| 5 | mysql vs. yoursql | in the following database comparison ... |
| 1 | mysql tutorial | dbms stands for database ... |
+----+-------------------+------------------------------------------+
2 rows in set (0.00 sec)
函数 match() 对照一个文本集(包含在一个 fulltext 索引中的一个或多个列的列集)执行一个自然语言搜索一个字符串。搜索字符串做为 against() 的参数被给定。搜索以忽略字母大小写的方式执行。对于表中的每个记录行,match() 返回一个相关性值。即,在搜索字符串与记录行在 match() 列表中指定的列的文本之间的相似性尺度。
当 match() 被使用在一个 where 子句中时 (参看上面的例子),返回的记录行被自动地以相关性从高到底的次序排序。相关性值是非负的浮点数字。零相关性意味着不相似。相关性的计算是基于:词在记录行中的数目、在行中唯一词的数目、在集中词的全部数目和包含一个特殊词的文档(记录行)的数目。
它也可以执行一个逻辑模式的搜索。这在下面的章节中被描述。
前面的例子是函数 match() 使用上的一些基本说明。记录行以相似性递减的顺序返回。
下一个示例显示如何检索一个明确的相似性值。如果即没有 where 也没有 order by 子句,返回行是不排序的。
mysql> select id,match (title,body) against ('tutorial') from articles;
+----+-----------------------------------------+
| id | match (title,body) against ('tutorial') |
+----+-----------------------------------------+
| 1 | 0.64840710366884 |
| 2 | 0 |
| 3 | 0.66266459031789 |
| 4 | 0 |
| 5 | 0 |
| 6 | 0 |
+----+-----------------------------------------+
6 rows in set (0.00 sec)
下面的示例更复杂一点。查询返回相似性并依然以相似度递减的次序返回记录行。为了完成这个结果,你应该指定 match() 两次。这不会引起附加的开销,因为 mysql 优化器会注意到两次同样的 match() 调用,并只调用一次全文搜索代码。