欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php读取sphinx的例子

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

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

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

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