当前位置:Gxlcms > PHP教程 > php读取sphinx的例子

php读取sphinx的例子

时间:2021-07-01 10:21:17 帮助过:21人阅读

  1. //检查sphinx是否能连接,不能重试两次,能则连接,不用mysql协议,仅供参考
  2. function checkSphinxNoMysql() {
  3. $flag = true;
  4. $retries = 0;
  5. while ( $flag && $retries < 2 ) {
  6. $s = new SphinxClient ();
  7. $s->setServer ( $_ENV ['db_host'], $_ENV ['current_sphinx_port'] );
  8. if (! $s->open ()) {
  9. //此处为如果连接不上就更改配置文件,根据项目需要来写
  10. //global $configDefault;
  11. //updateConfig ( $configDefault );
  12. $retries ++;
  13. } else {
  14. $flag = false;
  15. break;
  16. }
  17. }
  18. return $s;
  19. if ($retries >= 2) {
  20. //sendemail or not
  21. return false;
  22. }
  23. }
  24. $order_column = 'id DESC,time DESC';//排序规则
  25. //$s = checkSphinx ();
  26. $s = new SphinxClient ();
  27. $s->setServer ( 'sphinx_host', 'sphinx_port');
  28. //以上两句代码亦可使用$s = checkSphinx ();来代替
  29. $indexname = "page_keyword";//索引名字
  30. $s->setMatchMode ( SPH_MATCH_PHRASE );
  31. $s->SetSortMode ( SPH_SORT_EXTENDED, $order_column );
  32. $s->setMaxQueryTime ( 100000 );
  33. $s->setLimits ( 0, $limit_total, $limit_total );
  34. $keyword_sphinx = iconv ( "gbk", "utf-8", $keyword );
  35. $result = $s->query ( $keyword_sphinx, $indexname );
  36. $s->close ();
  37. if ($result ['total'] > 0) {
  38. var_dump($result ['matches']);
  39. //根据打印出的结果进行相应的读取
  40. }
  41. ?>

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

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

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

人气教程排行