php实现搜索类封装示例

这篇文章主要为大家详细介绍了php实现搜索类封装示例,感兴趣的小伙伴们可以参考一下,本文为大家分享了php实现搜索类封装示例,供大家参考,具体内容如下:

  1. <?php
  2. /**
  3. * SoClass.php
  4. * 索引与搜索类 */
  5. class SoClass {
  6. private $_xindex;
  7. private $_xsearch;
  8. private $_project;
  9. public function __construct($project){
  10. //载入引导文件
  11. require_once 'lib/XS.php';
  12. //初始化
  13. $xs = new XS($project);
  14. $this->_project = $project;
  15. $this->_xindex = $xs->index;
  16. $this->_xsearch = $xs->search;
  17. $this->_xsearch->setCharset('UTF-8');
  18. }
  19. public function query($keyWord,$row=20,$jnum=0){
  20. $xs = new XS($this->_project);
  21. $xs->search->setFuzzy();
  22. $xs->search->setAutoSynonyms();
  23. $xs->search->setQuery($keyWord); //支持同义词搜索,默认打开
  24. $xs->search->setLimit($row, $jnum); //设置返回结果最多为 5 条,并跳过前 10 条
  25. $docs = $xs->search->search(); //执行搜索,将搜索结果文档保存在 $docs 数组中
  26. $count = $xs->search->count(); //获取搜索结果的匹配总数估算值
  27. if($count){
  28. $data = array();
  29. foreach ($docs as $key=>$doc){
  30. $data[$key]['pid'] = $doc->pid;
  31. $data[$key]['nid'] = $doc->nid;
  32. $data[$key]['category'] = $doc->category;
  33. $data[$key]['url'] = $doc->url;
  34. $data[$key]['name'] = $xs->search->highlight(htmlspecialchars($doc->name));
  35. $data[$key]['message'] = $xs->search->highlight(htmlspecialchars($doc->message));
  36. }
  37. return array('data'=>$data,'count'=>$count);
  38. }
  39. return array();
  40. }
  41. public function hotWord($num,$type='lastnum'){
  42. return $this->_xsearch->getHotQuery($num,$type);
  43. }
  44. public function expanded($keyWord){
  45. return $this->_xsearch->getExpandedQuery($keyWord);
  46. }
  47. public function lastCount(){
  48. return $this->_xsearch->getLastCount();
  49. }
  50. public function index($data,$update=0){
  51. // 创建文档对象
  52. $doc = new XSDocument;
  53. $doc->setFields($data);
  54. // 添加或更新到索引数据库中
  55. if(!$update){
  56. $this->_xindex->add($doc);
  57. }else{
  58. $this->_xindex->update($doc);
  59. }
  60. }
  61. public function delete($idArray){
  62. //删除索引(主键删除array('1','2','3'))
  63. $this->_xindex->del($idArray);
  64. }
  65. public function addSynonym($word1,$word2){
  66. $this->_xindex->addSynonym($word1,$word2);
  67. }
  68. public function clearIndex(){
  69. $this->_xindex->clean();
  70. }
  71. }
  72. ?>

以上就是本文的全部内容,希望对大家学习php程序设计有所帮助。