Home Database Mysql Tutorial PHP+MYSQL实现全文检索_MySQL

PHP+MYSQL实现全文检索_MySQL

Jun 01, 2016 pm 01:16 PM
how

使用分词类库,分词类库请参见:http://www.xunsearch.com/scws/

如何使用PHP实现全文检索功能?
很多人可能马上可以想出几种方案,比如:文件检索法、采用SQL的like语句等方法,但这些方法效率都相当的低。
这里介绍一种比较高效的PHP全文检索实现方法,这就是采用MYSQL的FULLTEXT字段类型。但是MYSQL的FULLTEXT字段对中文的支持不是很好,本文也一并介绍如何通过PHP+MYSQL实现中文全文检索功能。
首先需要用到一个PHP中文分词扩展模块——SCWS,关于这个模块的安装和使用大家可以到www.ftphp.com/scws去查找相关内容(如有问题请留言)。
然后再看看mysql的fulltext字段类型的相关信息:
MySQL3.23.23之后的版本开始支持全文索引和搜索。全文索引在 MySQL 中是一个 FULLTEXT 类型索引。
FULLTEXT 索引用于 MyISAM 表,可以在 CREATE TABLE 时或之后使用 ALTER TABLE 或 CREATE INDEX 在 CHAR、VARCHAR 或 TEXT 列上创建。对于大的数据库,将数据装载到一个没有 FULLTEXT 索引的表中,然后再使用 ALTER TABLE (或 CREATE INDEX) 创建索引,这将是非常快的。将数据装载到一个已经有 FULLTEXT 索引的表中,将是非常慢的。

MYSQL全文搜索通过 MATCH() 函数完成。
下面举一简单例子:
1、新建数据表:
CREATE TABLE fulltext_sample(copy TEXT,FULLTEXT(copy)) TYPE=MyISAM;
这里的copy就是一个fulltext类型的字段,如果建表的时候没有添加全文检索字段,也可以通过alert来添加,如:
ALTER TABLE fulltext_sample ADD FULLTEXT(copy)
2、插入数据:
INSERT INTO fulltext_sample VALUES
('It appears good from here'),
('The here and the past'),
('Why are we hear'),
('An all-out alert'),
('All you need is love'),
('A good alert');
3、数据检索:
SELECT * FROM fulltext_sample WHERE MATCH(copy) AGAINST('love');
上面就是mysql的全文检索功能,注意:在全文索引上进行搜索是不区分大小写的。

下面再看如何实现中文全文检索。
fulltext字段是以词语为单位,词语之间需要用空格隔开,而汉语的句子中各个词语之间并不会用空格隔开,因此我们需要对中文进行分词,这也就是为什么上面需要强词用到中文分词扩展模块。
但是尽管对中文进行分词,MYSQL还是不能通过MATCH来实现中文的全文检索,这需要通过一定的方法来进行转换,一个比较简单实用的方法是采用下面这个函数(当然还有更好的),它将中文进行了urlencode转换。
function q_encode($str)
{
$data = array_filter(explode(" ",$str));
$data = array_flip(array_flip($data));
foreach ($data as $ss) {
  if (strlen($ss)>1 )
   $data_code .= str_replace("%","",urlencode($ss)) . " ";
}
$data_code = trim($data_code);
return $data_code;
}
将转换过后的内容保存至事先定义好的fulltext字段。同样,在查询的时候也需要将查询的关键词进行同样方法的转换。

PHP+Mysql实现UTF8全文搜索的方法

本文讲解一下如何在海量的数据中能够快速的进行全文检索呢?MySQL提供了一个全文索引功能,也就是把字段设置上FULLTEXT索引属性,然后通过SELECT的MATCH AGAINST语句进行查找。

我们开发的一个纯英文站点TouchUs - The Global Yellow Pages & Business Directory(www.touchus.org)就是利用MySQL的这一功能,实现了对十多万条数据的平均全文检索时间小于0.5秒。但是在开发TouchUs的中文网站——城市黄页网时(www.city39.cn),碰到了新的问题。原来英文排版时词和词之间是通过空格区分的,FULLText可以完全支持,但是对中文或者是东亚文字就没有这么简单了,因为中文的词和词之间并没有明显的分隔,所以MySQL不支持中文字符的全文检索。

如何让MySQL也能支持中文的全文检索呢?偶然间产生了一个思路,那就是能不能在中文分词后,通过对中文进行编码转化成英文字符,这样就在中英文间建立一个特定的联系,然后再进行全文检索,这样不就实现了中文的全文索引了吗?经过试验,答案是肯定的。下面是在城市黄页网中实现的具体过程:

1. 建立一个单独的索引表,比如对应members表,我们建立一个members_index表。

用户信息表(members)                    用户信息全文索引表(members_index)

User_id                                              user_id

User_name                                       index_intro

User_introduction                                   

在members_index表的index_intro中加入fulltext索引。

2. 对用户信息表(members)的User_introduction字段内容进行中文分词处理

中文分词的处理过程,可以参考简易中文分词系统http://www.ftphp.com/scws/,在城市黄页网中,我们采用了scws的PHP扩展模块方式来实现中文分词。scws的php扩展模块安装非常简单,只需简单编译配置后即可使用。在具体的php代码中,我们写了如下的函数来实现分词后将分词结果用空格进行连接。

//中文分词函数

function str_fc($str) {

$so = scws_new();

$so->set_charset('utf8');

// 这里没有调用 set_dict 和 set_rule 系统会自动试调用 ini 中指定路径下的词典和规则文件

$so->send_text($str);

while ($tmp = $so->get_result())

{

foreach (  $tmp as $ss ){

$s = trim($ss[word]);

if ( $s )

$mystr .= trim($ss[word]) . " ";

//echo urlencode(trim($ss[word])) . " ";

}

}

return $mystr;

}

该函数返回就是用空格连接的分词结果。

3. 对分词结果进行编码,可以采用多种编码方式,比如base64编码、urlencode编码、汉字转拼音等,对gb2312甚至可以采用区位码编码方式。考虑到存储空间以及便利性,我们采用了PHP的urlencode编码方式。需要注意的是,在编码前,我们可以去掉重复的分词来节约存储空间,编码后要去掉编码结果中的%符号,因为urlencode采用RFC 1738???行编码,会产生很多%,而%在MySQL是通配符。下面是编码过程用到的PHP代码

$data = str_fc($data);  //中文分词

$data = array_filter(explode(" ",$data)); //删除数组空项

$data = array_flip(array_flip($data));  //删除重复项

//对分词结果进行urlcode编码

foreach (  $data as $ss ) {

if (strlen($ss)>1 )

$data_code .= str_replace("%","",urlencode($ss)) . " ";

}

这里的$data_code就是编码后的结果。把编码结果根据user_id存入用户信息全文索

引表(members_index)

4. 在进行搜索处理时,首先对用户输入的关键字进行同样的分词编码处理,然后通过MySQL的SELECT的MATCH  AGAINST语句进行全文快速检索,根据检索结的user_id即可调用用户信息表(members)中的原始数据进行显示,而没有必要进行一次解码重组。

以上MySQL UTF8中文全文检索方法.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is there a future for employment in clinical pharmacy at Harbin Medical University? (What are the employment prospects for clinical pharmacy at Harbin Medical University?) Is there a future for employment in clinical pharmacy at Harbin Medical University? (What are the employment prospects for clinical pharmacy at Harbin Medical University?) Jan 02, 2024 pm 08:54 PM

What are the employment prospects of clinical pharmacy at Harbin Medical University? Although the national employment situation is not optimistic, pharmaceutical graduates still have good employment prospects. Overall, the supply of pharmaceutical graduates is less than the demand. Pharmaceutical companies and pharmaceutical factories are the main channels for absorbing such graduates. The demand for talents in the pharmaceutical industry is also growing steadily. According to reports, in recent years, the supply-demand ratio for graduate students in majors such as pharmaceutical preparations and natural medicinal chemistry has even reached 1:10. Employment direction of clinical pharmacy major: After graduation, students majoring in clinical medicine can engage in medical treatment, prevention, medical research, etc. in medical and health units, medical research and other departments. Employment positions: Medical representative, pharmaceutical sales representative, sales representative, sales manager, regional sales manager, investment manager, product manager, product specialist, nurse

How to download win10 image quickly How to download win10 image quickly Jan 07, 2024 am 11:33 AM

Recently, some friends reported how to download win10 image files. Because there are so many image files on the market, what should I do if I want to find a regular file to download? Today, the editor has brought you the link to download the image and the detailed solution steps. Let’s take a look at them together. win10 image quick download and installation tutorial download link >>> System Home Ghostwin101909 image 64-bit version v2019.11<<<>>>Win10 image 64-bit v2019.07<<<>>>Win10 image 32-bit v2019.07<< <1. Search through the Internet

How to clean temp folder How to clean temp folder Feb 22, 2024 am 09:15 AM

How to clean the temp folder As we use the computer, temporary files (temp files) will gradually accumulate. These temporary files are generated when we use the computer, such as cache files when browsing the web, temporary files during software installation, etc. Failure to clean the temp folder for a long time may occupy a large amount of disk space and affect the speed of the computer. Therefore, cleaning the temp folder regularly is a necessary step to maintain computer performance. Below, we will introduce some simple ways to clean the temp folder. Method 1: Manually clean t

How to reset Win10 system How to reset Win10 system Jun 29, 2023 pm 03:14 PM

How to reset Win10 system? Nowadays, many friends like to use computers with Win10 system. However, they will inevitably encounter some unsolvable problems when using computers. At this time, you can try to reset the system. So how should you do it? Let’s follow the editor to watch the tutorial on resetting the Win10 system. Users in need should not miss it. Tutorial on resetting the Win10 system 1. Click Windows and select Settings. 2. Click Update and Security. 3. Select Restore. 4. Click Start on the right to reset this computer. The above is the entire content of [How to reset Win10 system - Tutorial on resetting Win10 system]. More exciting tutorials are available on this site!

How to check win11 computer configuration How to check win11 computer configuration Jun 29, 2023 pm 12:15 PM

How to check win11 computer configuration? The win11 system is a very practical computer operating system version. This version provides users with rich functions, allowing users to have a better computer operating experience. So many friends who use computers are curious about their computers. Specific configuration, how to perform this operation in win11 system? Many friends don’t know how to operate in detail. The editor has compiled a tutorial on how to view the win11 computer configuration below. If you are interested, follow the editor and read on! Win11 computer configuration view tutorial 1. Click the windows icon on the taskbar below or press the "windows key" on the keyboard to open the start menu. 2. Find "Settings" or "sett" in the start menu.

Solve the problem of environment detection when reinstalling the system Solve the problem of environment detection when reinstalling the system Jan 08, 2024 pm 03:33 PM

How to solve the problem that the environment test fails when reinstalling the system and needs to be rewritten. The reason is: the mobile phone is poisoned. You can install anti-virus software such as Mobile Manager for anti-virus. 2. Many junk files are stored inside the mobile phone, causing the running memory of the mobile phone to be occupied. Just clear the phone cache to solve this problem. 3. The phone memory is occupied too much by saved software and files. It is no problem to delete unnecessary files and software frequently. As long as your hardware configuration meets the installation requirements, you can use the new one directly. Reinstall the system from the system disk! You can use a USB flash drive or hard disk to install, which is very fast. But the key is to use a system disk with good compatibility (supports installation in IDE, ACHI, and RAID modes), and it can be automatically and permanently activated, which has been verified. so

How to add the values ​​of HTML elements? How to add the values ​​of HTML elements? Sep 16, 2023 am 08:41 AM

This article will teach you how to add the value of an element in HTML. We have a basic understanding of the value attribute in HTML and the situations in which it is used. Let's look forward to a better understanding of the HTMLvalue attribute. In HTML, the value attribute is used to describe the value of the element it is used with. It has different meanings for various HTML components. Usage - It can be used with,,,,,, and, elements. -When the value attribute is present, it indicates what the default value of the input element is. It has different meanings for various types of input: when the button appears in "button," "reset," and &qu

how to reset password in mysql how to reset password in mysql Feb 18, 2024 pm 12:41 PM

MySQL is an open source relational database management system that is widely used in various types of application development. When using the MySQL database, you often need to change the password to improve the security of the database. This article will introduce how to change the MySQL password through specific code examples. In MySQL, you can change the password by following the following steps: Log in to the MySQL database server: Open a command prompt or terminal window and execute the following command: mysql-uroo

See all articles