关键字搜索和排名结果

时间:2011-12-20 10:33:49

标签: php mysql

假设我的mySQL表中有5个文档作为行和2列'document'和'description'。

  • 文件1:John和Nancy是最好的朋友。
  • 文件2:John,Casey,David,Nancy是最好的朋友。
  • 文件3:南希和凯西是最好的朋友。
  • 文件4:大卫与凯西有关系。大卫和凯西疯狂相爱。
  • 文件5:大卫和约翰是兄弟姐妹。

因此,如果搜索查询是“David Casey”,则如何根据所有5个文档中的术语频率计算查询,并根据频率对结果进行排名。

在这种情况下,结果应该是这样的:

  • 文件4(因为有2个'David'和2'Casey')
  • 文件2(1'David'和1'Casey')
  • 文件3(1'Casey')
  • 文件5(1'David')

我读过许多tf-idf文章,但没有一篇可以帮助我。我不知道如何编写代码。

这是我目前的代码:

  

$ searchCondition =“description LIKE'%”。 implode(“%'或描述LIKE'%”,$ searchTerms)。 “%'”;

     

$ query =“SELECT description FROM table1 WHERE $ searchCondition ORDER BY description ASC”;

     

$ result = mysqli_query($ dbc,$ query);

     

...

     

...

     

...

1 个答案:

答案 0 :(得分:0)

这肯定有用:

$searchCondition = "description LIKE '%" . implode("%' OR description LIKE '%", $searchTerms) . "%'";
$orderCondition = array();
foreach ($searchTerms as $word) {
    $orderCondition[] = "(length(description)-length(replace(description,\"".$word."\",\"\")))/length(\"".$word."\")";
}
$orderConditionString = "(".implode(" + ", $orderCondition).")";

$query = "SELECT description FROM table1 WHERE $searchCondition ORDER BY $orderConditionString DESC";

数据库中的项目按降序排序。所以最相关的是第一位的。

注意:只有当关键字的数量很少时才能正常工作。因为每个关键字检查3次长度。因此,更大的表和更多关键字的响应时间可能会有所不同;)

相关问题