search_interface.class.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * 搜索接口
  4. *
  5. */
  6. class search_interface {
  7. public function __construct() {
  8. //初始化sphinx
  9. pc_base::load_app_class('sphinxapi', '', 0);
  10. $this->cl = new SphinxClient();
  11. $siteid = get_siteid();
  12. $search_setting = getcache('search');
  13. $setting = $search_setting[$siteid];
  14. $mode = SPH_MATCH_EXTENDED2; //匹配模式
  15. $host = $setting['sphinxhost']; //服务ip
  16. $port = intval($setting['sphinxport']); //服务端口
  17. $ranker = SPH_RANK_PROXIMITY_BM25; //统计相关度计算模式,仅使用BM25评分计算
  18. $this->cl->SetServer($host, $port);
  19. $this->cl->SetConnectTimeout(1);
  20. $this->cl->SetArrayResult(true);
  21. $this->cl->SetMatchMode($mode);
  22. $this->cl->SetRankingMode($ranker);
  23. }
  24. /**
  25. * 搜索
  26. * @param string $q 关键词 类似sql like'%$q%'
  27. * @param array $siteids 站点id数组
  28. * @param array $typeids 类型ids 类似sql IN('')
  29. * @param array $adddate 时间范围数组 类似sql between start AND end 格式:array('start','end');
  30. * @param int $offset 偏移量
  31. * @param int $limit 匹配项数目限制 类似sql limit $offset, $limit
  32. * @param string $orderby 排序字段 类似sql order by $orderby {id:文章id,weight:权重}
  33. */
  34. public function search($q, $siteids=array(1), $typeids='', $adddate='', $offset=0, $limit=20, $orderby='@id desc') {
  35. if(CHARSET != 'utf-8') {
  36. $q = iconv(CHARSET, 'utf-8', $q);
  37. }
  38. if($orderby) {
  39. //按一种类似SQL的方式将列组合起来,升序或降序排列。
  40. $this->cl->SetSortMode(SPH_SORT_EXTENDED, $orderby);
  41. }
  42. if($limit) {
  43. $this->cl->SetLimits($offset, $limit, ($limit>1000) ? $limit : 1000);
  44. }
  45. //过滤类型
  46. if($typeids) {
  47. $this->cl->SetFilter('typeid', $typeids);
  48. }
  49. //过滤站点
  50. if($siteids) {
  51. $this->cl->SetFilter('siteid', $siteids);
  52. }
  53. //过滤时间
  54. if($adddate) {
  55. $this->cl->SetFilterRange('adddate', $adddate[0], $adddate[1], false);
  56. }
  57. $res = $this->cl->Query($q, 'main, delta');
  58. return $res;
  59. }
  60. }