您好,欢迎访问一九零五行业门户网

利用MySQL内置函数实现全文搜索功能_MySQL

match (col1,col2,...) against (expr [in boolean mode | with query expansion])
mysql支持全文索引和搜索功能。mysql中的全文索引类型fulltext的索引。  fulltext 索引仅可用于 myisam 表;他们可以从char、varchar或text列中作为create table语句的一部分被创建,或是随后使用alter table 或 create index被添加。对于较大的数据集,将你的资料输入一个没有fulltext索引的表中,然后创建索引,其速度比把资料输入现有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 (title,body) values
-> ('mysql tutorial','dbms stands for database ...'),
-> ('how to use mysql well','after you went through a ...'),
-> ('optimizing mysql','in this tutorial we will show ...'),
-> ('1001 mysql tricks','1. never run mysqld as root. 2. ...'),
-> ('mysql vs. yoursql','in the following database comparison ...'),
-> ('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()函数对于一个字符串执行资料库内的自然语言搜索。一个资料库就是1套1个或2个包含在fulltext内的列。搜索字符串作为对against()的参数而被给定。对于表中的每一行, match() 返回一个相关值,即, 搜索字符串和 match()表中指定列中该行文字之间的一个相似性度量。
在默认状态下, 搜索的执行方式为不区分大小写方式。然而,你可以通过对编入索引的列使用二进制排序方式执行区分大小写的全文搜索。 例如,可以向一个使用latin1字符集的列给定latin1_bin 的排序方式,对于全文搜索区分大小写。
如上述所举例子,当match()被用在一个 where 语句中时,相关值是非负浮点数。零相关的意思是没有相似性。相关性的计算是基于该行中单词的数目, 该行中独特子的数目,资料库中单词的总数,以及包含特殊词的文件(行)数目。
对于自然语言全文搜索,要求match() 函数中命名的列和你的表中一些fulltext索引中包含的列相同。对于前述问讯, 注意,match()函数(题目及全文)中所命名的列和文章表的fulltext索引中的列相同。若要分别搜索题目和全文,应该对每个列创建fulltext索引。
或者也可以运行布尔搜索或使用查询扩展进行搜索。
上面的例子基本上展示了怎样使用返回行的相关性顺序渐弱的match()函数。而下面的例子则展示了怎样明确地检索相关值。返回行的顺序是不定的,原因是  select 语句不包含 where或order by 子句:
mysql> select id, match (title,body) against ('tutorial')
-> from articles;
+----+-----------------------------------------+
| id | match (title,body) against ('tutorial') |
+----+-----------------------------------------+
|1 |0.65545833110809 |
|2 | 0 |
|3 |0.66266459226608 |
|4 | 0 |
|5 | 0 |
|6 | 0 |
+----+-----------------------------------------+
6 rows in set (0.00 sec)
其它类似信息

推荐信息