我正在尝试为我的网站创建一个小型搜索。我试过使用全文索引搜索,但我永远无法让它发挥作用。这是我想出的:
if(isset($_GET['search'])) {
$search = str_replace('-', ' ', $_GET['search']);
$result = array();
$titles = mysql_query("SELECT title FROM Entries WHERE title LIKE '%$search%'");
while($row = mysql_fetch_assoc($titles)) {
$result[] = $row['title'];
}
$tags = mysql_query("SELECT title FROM Entries WHERE tags LIKE '%$search%'");
while($row = mysql_fetch_assoc($tags)) {
$result[] = $row['title'];
}
$text = mysql_query("SELECT title FROM Entries WHERE entry LIKE '%$search%'");
while($row = mysql_fetch_assoc($text)) {
$result[] = $row['title'];
}
$result = array_unique($result);
}
基本上,它会搜索数据库中所有条目的所有标题、正文和标签。这工作得很好,但我只是想知道它的效率如何?这也只适用于小型博客。无论哪种方式,我只是想知道是否可以提高效率。
最佳答案
没有办法使 LIKE '%pattern%'
查询高效。一旦获得大量数据,使用这些通配符查询的执行速度将比使用全文索引解决方案慢数百或数千倍。
你应该看看我为 MySQL 大学所做的演示: http://www.slideshare.net/billkarwin/practical-full-text-search-with-my-sql
这是让它工作的方法:
首先确保您的表使用 MyISAM 存储引擎。 MySQL FULLTEXT 索引仅支持 MyISAM 表。 (编辑 11/1/2012:MySQL 5.6 正在为 InnoDB 表引入全文索引类型。)
ALTER TABLE Entries ENGINE=MyISAM;
创建全文索引。
CREATE FULLTEXT INDEX searchindex ON Entries(title, tags, entry);
搜索它!
$search = mysql_real_escape_string($search); $titles = mysql_query("SELECT title FROM Entries WHERE MATCH(title, tags, entry) AGAINST('$search')"); while($row = mysql_fetch_assoc($titles)) { $result[] = $row['title']; }
请注意,您在
MATCH
子句中命名的列必须 与您在全文索引定义中声明的列的顺序相同。否则无法正常工作。
I've tried using full-text index search, but I could never get it to work... I'm just wondering if this could be made any more efficient.
这就像在说,“我不知道如何使用这把电锯,所以我决定用小刀砍倒这棵红杉树。我怎样才能让它像电锯一样工作?”
关于您关于搜索与超过 50% 的行匹配的词的评论。
MySQL 手册说this :
Users who need to bypass the 50% limitation can use the boolean search mode; see Section 11.8.2, “Boolean Full-Text Searches”.
和this :
The 50% threshold for natural language searches is determined by the particular weighting scheme chosen. To disable it, look for the following line in storage/myisam/ftdefs.h:
#define GWS_IN_USE GWS_PROB
Change that line to this:
#define GWS_IN_USE GWS_FREQ
Then recompile MySQL. There is no need to rebuild the indexes in this case.
此外,您可能正在搜索停用词。这些是全文搜索忽略的词,因为它们太常见了。诸如“the”之类的词。参见 http://dev.mysql.com/doc/refman/5.1/en/fulltext-stopwords.html
关于php - MySQL/PHP 搜索效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2954022/