我如何将其更改为进行全文搜索而不是 LIKE?
经过一番研究后,我将这段代码放在一起来搜索数据库中的 mysql 表。虽然它工作得很好,但它限制自己与用户输入的单词完全匹配。有人知道如何制作它以使其符合我的某种相关性吗?我一直在阅读有关全文搜索的内容,但我似乎无法真正理解它。
例如,如果您在两个字段中搜索“未回答的问题”,我希望能够获得这样的结果,将搜索到的单词包含在它显示的任何字符串中,并根据相关性列出它,就像这样(搜索结果示例输出): - 未解答的问题 - 回答问题 - 回答问题 - 未解答的问题 - 未解答的问题 - 问题 - 回答
$k = trim ($_GET['search']);
$i = "";
$terms = explode (" ", $k);
$query = "SELECT * FROM table1 WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "fld_title LIKE '%$each%' OR fld_keyword LIKE '%$each%' ";
else
$query .= "OR fld_title LIKE '%$each%' OR fld_keyword LIKE '%$each%' ";
}
// connect
include_once "connect.php"; //connect 2 db
$query = mysql_query($query);
$numrows = mysql_num_rows ($query);
if ($numrows > 0){
while ($row = mysql_fetch_assoc ($query)){
//
//
// echo out something here
//
//
}
}else
{
echo "No results found for <b>$k</b>";
}
after some researching I put this code together to search a mysql table in the db. while it works fine, it limit itself to match the words exactly as the user enters it. anyone know how to make it so that it matches my some sort of relevancy? I have been reading about the full text search but I cant really seem to grasp it.
for example, if you search for 'unanswered questions' in two fields, I want to be able to get result like that include the searched word(s) in any string that it show up in, and list it according to relevancy, like so (search results example output):
- unanswered questions
- answered questions
- answer question
- unanswered questions
- unanswered questions
- questions
- answer
$k = trim ($_GET['search']);
$i = "";
$terms = explode (" ", $k);
$query = "SELECT * FROM table1 WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "fld_title LIKE '%$each%' OR fld_keyword LIKE '%$each%' ";
else
$query .= "OR fld_title LIKE '%$each%' OR fld_keyword LIKE '%$each%' ";
}
// connect
include_once "connect.php"; //connect 2 db
$query = mysql_query($query);
$numrows = mysql_num_rows ($query);
if ($numrows > 0){
while ($row = mysql_fetch_assoc ($query)){
//
//
// echo out something here
//
//
}
}else
{
echo "No results found for <b>$k</b>";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要进行全文搜索,您必须:
在表中创建全文索引(注意字段不能是 BLOB)
在您的情况下:
在 php 中更改
for
如果您想查看结果的相关性:
MATCH-AGAINST 返回数字:0 表示不匹配或其他取决于匹配。
您可以“按相关性排序”,更改查询以使搜索更相关... MATCH(fld_title, fld_keyword) AGAINST ('".$k."') > 0.5
只有一个问题:AGAINST 部分(对你来说是 $k)必须大于 3 个字符。
to do a fulltext search you have to:
Create a Fulltext index in the table (note the fields can't be BLOB)
in your case:
in php change
for
if you want to see the relevancy of the results:
The MATCH-AGAINST returns a number: 0 for no match or other depending on matching.
You can "order by relevancy", change the query for make more relevant the search... MATCH(fld_title, fld_keyword) AGAINST ('".$k."') > 0.5
Only one problem: the AGAINST part ($k for you) must be greater than 3 characters.