PHP读取sphinx实例

阅读原文:http://yzswyl.cn/blread-1611.html

1.未采用mysql二进制网络协议的代码:

//检查sphinx是否能连接,不能重试两次,能则连接,不用mysql协议,仅供参考
function checkSphinxNoMysql() {
    $flag = true;
    $retries = 0;
    while ( $flag && $retries < 2 ) {
        $s = new SphinxClient ();
        $s->setServer ( $_ENV ['db_host'], $_ENV ['current_sphinx_port'] );
        if (! $s->open ()) {
            //此处为如果连接不上就更改配置文件,根据项目需要来写
            //global $configDefault;
            //updateConfig ( $configDefault );
            $retries ++;
        } else {
              $flag = false;
            break;
        }
    }
    return $s;
    if ($retries >= 2) {
        //sendemail or not
        return false;
    }
}
  
$order_column = 'id DESC,time DESC';//排序规则
//$s = checkSphinx ();
$s = new SphinxClient ();
$s->setServer ( 'sphinx_host', 'sphinx_port');
//以上两句代码亦可使用$s = checkSphinx ();来代替
$indexname = "page_keyword";//索引名字
$s->setMatchMode ( SPH_MATCH_PHRASE );
$s->SetSortMode ( SPH_SORT_EXTENDED, $order_column );
$s->setMaxQueryTime ( 100000 );
$s->setLimits ( 0, $limit_total, $limit_total );
$keyword_sphinx = iconv ( "gbk", "utf-8", $keyword );
$result = $s->query ( $keyword_sphinx, $indexname );
$s->close ();
if ($result ['total'] > 0) {
    var_dump($result ['matches']);
    //根据打印出的结果进行相应的读取
}

2.采用mysql二进制网络协议的代码:

//检查sphinx是否能连接,不能重试两次,能则连接,用mysql14协议
protected function checkSphinx() {
    $flag = true;
    $retries = 0;
    while ( $flag && $retries < 2 ) {
        $conn = mysql_connect ( "{$_ENV ['db_host']}:{$_ENV ['current_sphinx_port']}" );
        if (! $conn) {
            //此处为如果连接不上就更改配置文件,根据项目需要来写
            //global $configDefault;
            //updateConfig ( $configDefault );
            $retries ++;
        } else {
            $flag = false;
            break;
        }
    }
    if ($retries >= 2) {
        die ( "Please contact with administrator." );
    }
    return $conn;
}
  
$order_column = 'id DESC,time DESC';//排序规则
$conn = mysql_connect ( "sphinx_host:sphinx_port" );
//以上代码亦可使用$conn = checkSphinx ();来代替
if (! $conn) {
    return - 1;//连接不上返回状态
}
$keyword_sphinx = iconv ( "gbk", "utf-8", $keyword );
//keyword为索引名字
$sql = "select * from keyword where match('{$keyword_sphinx}') order by {$order_column} limit {$limit_total} option max_matches={$limit_total}";
$result = @mysql_query ( $sql, $conn );
  
$i = 0;
while ( ($row = mysql_fetch_array ( $result )) !== false ) {
    var_dump($row);
    //根据打印出的结果进行相应的读取
}
$totals = $this->getTotalFound ($conn);//获取总记录个数

如何获取总记录个数参考:sphinxql如何得到结果数?show meta的详细说明?

关于开启mysql二进制网络协议参考:Sphinx/MySQL 协议支持与SphinxQL

 

 

posted @ 2012-12-03 19:51  雪洁  阅读(3372)  评论(1编辑  收藏  举报