2013-01-11 22 views
1

我已經創建了一個基於用戶(信用爲他answerzhikharev)創建了關鍵字,從數據庫中抓取相當短串查詢:訂單關鍵字結果的相關性

$searchArray = explode(' ', $search); 
$searchNumber = count($searchArray); 

$query = "SELECT * FROM tags WHERE tags.tag LIKE CONCAT('%',?,'%')" . 
    str_repeat(" OR tags.tag LIKE CONCAT('%',?,'%')", $searchNumber - 1); 

$stmt = $mysqli -> prepare($query); 
$bind_names[] = str_repeat('s', $searchNumber); 

for ($i = 0; $i < count($searchArray); $i++){ 
    $bind_name = 'bind'.$i; /*generate a name for variable bind1, bind2, bind3...*/ 
    $$bind_name = $searchArray[$i]; /*create a variable with this name and put value in it*/ 
    $bind_names[] = & $$bind_name; /*put a link to this variable in array*/ 
} 

call_user_func_array(array($stmt, 'bind_param'), &$bind_names); 
$stmt -> execute(); 

我的問題是我不知道如何根據相關性對這個結果進行排序。請注意,數據庫中的一個標籤可以包含多個單詞。

假設用戶搜索「紐約市」。然後在數據庫中,我有:

New York 
    York 
    New York City 
    New Zealand 
    Kansas City 

我想結果是這樣的:

New York City 
    New York 
    New Zealand 
    York 
    Kansas City 

應該尋找與用戶輸入中有文字和標籤最匹配的標籤與搜索中單詞的順序大致相同的單詞順序。

+0

你考慮過[全文搜索](http://dev.mysql.com/doc/en/fulltext-search.html)嗎? – eggyal

+0

@eggyal是的,我試過了,但它似乎沒有工作來搜索部分單詞。例如,搜索'ork'不會返回'York' –

+0

不,這是真的。它不會。在這種情況下,你將不得不自己計算一個相關分數... – eggyal

回答

0

這是一個獨立的全文搜索引擎(如Sphinx)的完美用例。我最近開始在一個項目中使用獅身人面像,到目前爲止我非常滿意。它的索引速度非常快,我看到直接MySQL查詢速度提高了10倍。

啓用明星模式將允許部分匹配: http://sphinxsearch.com/docs/2.0.6/conf-enable-star.html

它還允許不同的方法進行排序: http://sphinxsearch.com/docs/2.0.6/sorting-modes.html

一些更多的鏈接: http://sphinxsearch.com/docs/2.0.6/ http://php.net/manual/en /sphinx.examples.php