繁体   English   中英

如何将MySQL查询MATCH / AGAINST转换为LIKE,以解决Stop Word List

[英]How to convert MySQL query MATCH/AGAINST to LIKE to get around Stop Word List

场景:我正在使用此查询在特定类别中的两列ProductName和Description上搜索MySql表:

$query = "SELECT * FROM Products WHERE MATCH(ProductName,Description) AGAINST ('+$terms[0]* +$terms[1]* +$terms[2]* +$terms[3]* +$terms[4]*' IN BOOLEAN MODE) AND category_description='".$search_dept."' OR MATCH(ProductName,Description) AGAINST ('+$terms[0]* +$terms[1]* +$terms[2]* +$terms[3]* +$terms[4]*' IN BOOLEAN MODE) AND category2='".$search_dept."' ORDER BY $orderby LIMIT $offset, $rowsPerPage";

搜索条件$ terms [x]来自文本输入字段,格式为:

$slash_term = addslashes($_POST['term']);
$var = @$slash_term;
$trimmed = trim($var);
$terms = explode(' ',$trimmed);

该例程非常有用,直到您使用停用词,然后该查询才被杀死。

我在共享服务器上,无法禁用停用词检查。 因此,根据我的研究,可能可以使用LIKE和%通配符来解决此问题。

因此,我如何将上面的查询转换为LIKE查询,我认为它与以下内容类似,但是无法正常工作。

    $query = "select * from Products where category_description='".$search_dept."' AND Description like \"%$trimmed%\" OR category_description='".$search_dept."' AND ProductName like \"%$trimmed%\" ORDER BY $orderby LIMIT $offset, $rowsPerPage";

我是否可以仅使用%$ trimmed%从通配符中得到每个单词? 还是我应该采取的方式? 搜索几乎总是包含多个单词。

由于第一个查询似乎几乎可以完美地工作,所以我是否值得添加一个子例程来检查用户输入的停用词,然后在搜索之前将其从短语中删除?

好的,这是我的解决方案。 我检查并从用户输入中删除所有停用词,然后继续进行原始搜索查询。 完美运作。

// format user's input
$slash_term = addslashes($_POST['term']);
$var = @$slash_term;
$trimmed = trim($var);
$terms = explode(' ',$trimmed);
// check for stop words and remove
$stop_words_file  = "list-of-english-stop-words.txt"; // load stop words file
$contents = addslashes(file_get_contents($stop_words_file)); // escape special characters
$stop_words = explode(',', $contents); // create array
foreach($terms as $key => $value) { // search user input for stop words
    if(in_array($value, $stop_words)) { // stop word found
        unset($terms[$key]); // remove it from array
    }
}
$terms = array_values($terms); // remove empty/NULL values from array
// perform search
$query = "SELECT * FROM Products WHERE MATCH(ProductName,Description) AGAINST ('+$terms[0]* +$terms[1]* +$terms[2]* +$terms[3]* +$terms[4]*' IN BOOLEAN MODE) AND category_description='".$search_dept."' OR MATCH(ProductName,Description) AGAINST ('+$terms[0]* +$terms[1]* +$terms[2]* +$terms[3]* +$terms[4]*' IN BOOLEAN MODE) AND category2='".$search_dept."' ORDER BY $orderby LIMIT $offset, $rowsPerPage";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM