【PHP操做sphinx】

【index.php】php

 

【find.php】html

<?php
header("Content-type:text/html;charset=utf-8");

$keyword = $_GET['word'];
//實例化Sphinx對象
$sphinx=new SphinxClient();
//鏈接sphinx服務器
$sphinx->SetServer("localhost",9312);
//拆詞
//SPH_MATCH_ALL 和 SPH_MATCH_ANY 的區別:
//搜索「LAMP兄弟連」,ALL的結果:完整包含「LAMP兄弟連」才能被搜出來,
//單純包含「LAMP」或單純包含「兄弟連」的搜索不出來,沒有拆詞的功能。
//ANY則能夠搜索出來拆開後的詞的結果。此處使用ANY
$sphinx->SetMatchMode(SPH_MATCH_ANY);
//經過query方法搜索,「*」表示在全部的索引中搜索,至關於命令行裏面的「./indexer --all」
$result=$sphinx->query("$keyword","*");
//打印搜索的結果
//echo "<pre>";
//print_r($result);
//echo "</pre>";

//上面打印的結果中,數組的 [matches]循環便利,下標就是搜索到的文檔的主鍵Id
//使用PHP中的 array_keys()函數便可拿到下標,即:要查找的文檔的主鍵
//print_r(array_keys($result['matches']));
//結果以下:Array([0]=>1)

//使用implode或者 join用逗號把查詢出來的主鍵鏈接起來:
$ids = join(',',array_keys($result['matches']));
//echo $ids; //6,7

/*鏈接數據庫的操做*/
$p1 = mysql_connect("localhost","root","123456");
mysql_select_db("test");
mysql_query("set names utf8");
$sql="select * from post where id in ($ids)";
$rst=mysql_query($sql);
$opts=array(
   "before_match"=>"<font color='red'>",
   "after_match"=>"</font>",
);
while($row=mysql_fetch_assoc($rst)){
    //print_r($row); 

    //下面是高亮顯示所需,具體能夠查手冊    
    $final=$sphinx->buildExcerpts($row,"main",$keyword,$opts);
    echo "<pre>";
    print_r($final);
    echo "</pre>";
}

?>

 

【當前數據內容】mysql

相關文章
相關標籤/搜索