SetServer() public méthode

set searchd host name (string) and port (integer)
public SetServer ( $host, $port )
Exemple #1
0
 public function __construct(array $config)
 {
     parent::__construct($config);
     Kohana::load(Kohana::find_file('vendors', 'sphinxapi'));
     $this->_client = new SphinxClient();
     $this->_client->SetServer($this->config('host'), $this->config('port'));
 }
 /**
  * Sphinx server connector initialization
  * 
  * @return SphinxClient
  */
 function init_sphinx()
 {
     $this->sphinx = new SphinxClient();
     $this->sphinx->SetServer($this->admin_options['sphinx_host'], intval($this->admin_options['sphinx_port']));
     $this->sphinx->SetMatchMode(SPH_MATCH_EXTENDED2);
     return $this->sphinx;
 }
Exemple #3
0
 /**
  * Constructor.
  *
  * @param string $host The server's host name/IP.
  * @param string $port The port that the server is listening on.
  * @param array $indexes The list of indexes that can be used.
  */
 function __construct()
 {
     //sphinx
     $sphinxconf = Yaf_Registry::get("config")->get('sphinx')->toArray();
     $this->host = $sphinxconf['host'];
     $this->port = $sphinxconf['port'];
     $this->indexes = $sphinxconf['indexes'];
     $this->sphinx = new SphinxClient();
     $this->sphinx->SetServer($this->host, $this->port);
     //sphinx连接超时时间,单位为秒
     $this->sphinx->SetConnectTimeout(5);
     //sphinx搜索结果集返回方式:TRUE为普通数组返回,FALSE为PHP hash格式返回
     $this->sphinx->SetArrayResult(false);
     //sphinx最大搜索时间,单位为毫秒
     $this->sphinx->SetMaxQueryTime(5000);
     //匹配模式
     $this->sphinx->SetMatchMode(SPH_MATCH_EXTENDED2);
     //设置权重评分模式,详见sphinx文档第6.3.2节:SetRankingMode
     $this->sphinx->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
     //设置排序模式排序模式
     $this->sphinx->SetSortMode(SPH_SORT_EXTENDED, '@weight DESC,@id DESC');
     //中文分词配置
     $httpcwsconf = Yaf_Registry::get("config")->get('httpcws')->toArray();
     //中文分词HTTPCWS服务器接口地址
     $this->httpcws_url = 'http://' . $httpcwsconf['host'] . ':' . $httpcwsconf['port'] . '/?w=';
 }
 /**
  * Initialize the Sphinx search engine
  * @return void
  */
 public function initialize()
 {
     $this->_connectionOptions = array('host_name' => $this->modx->getOption('discuss.sphinx.host_name', null, 'localhost'), 'port' => $this->modx->getOption('discuss.sphinx.port', null, 9312), 'connection_timeout' => $this->modx->getOption('discuss.sphinx.connection_timeout', null, 30), 'searchd_retries' => $this->modx->getOption('discuss.sphinx.searchd_retries', null, 3), 'searchd_retry_delay' => $this->modx->getOption('discuss.sphinx.searchd_retry_delay', null, 10000));
     $this->_indices = $this->modx->getOption('discuss.sphinx.indexes', null, 'discuss_posts');
     $this->client = new SphinxClient();
     $this->client->SetServer($this->_connectionOptions['host_name'], $this->_connectionOptions['port']);
     $this->client->SetConnectTimeout($this->_connectionOptions['connection_timeout']);
     $this->client->SetMatchMode(SPH_MATCH_EXTENDED);
     return true;
 }
 public function setServer(array $parameters = array())
 {
     if (!isset($parameters[0])) {
         $parameters[0] = 'localhost';
     }
     if (!isset($parameters[1])) {
         $parameters[1] = 3386;
     }
     $this->sphinxClient->SetServer($parameters[0], $parameters[1]);
 }
 /**
  * Инициализация сфинкса
  */
 protected function InitSphinx()
 {
     /**
      * Получаем объект Сфинкса(из Сфинкс АПИ)
      */
     $this->oSphinx = new SphinxClient();
     $this->oSphinx->SetServer(Config::Get('module.search.sphinx.host'), intval(Config::Get('module.search.sphinx.port')));
     /**
      * Устанавливаем тип сортировки
      */
     $this->oSphinx->SetSortMode(SPH_SORT_EXTENDED, "@weight DESC, @id DESc");
 }
 /**
  * 初始化搜索引擎
  */
 private function _initSphinx()
 {
     $this->_loadCore('Help_SphinxClient');
     $this->_sphinx = new SphinxClient();
     $this->_sphinx->SetServer(SPHINX_HOST, SPHINX_PORT);
     $this->_sphinx->SetConnectTimeout(5);
     //连接时间
     $this->_sphinx->SetArrayResult(true);
     $this->_sphinx->SetMaxQueryTime(10);
     //设置最大超时时间
     $this->_sphinx->SetMatchMode(SPH_MATCH_ANY);
     //匹配模式
 }
 /**
  * 初始化搜索引擎
  */
 private function _initSphinx()
 {
     import('@.Util.SphinxClient');
     $this->_sphinx = new SphinxClient();
     $this->_sphinx->SetServer(C('SPHINX_HOST'), C('SPHINX_PORT'));
     $this->_sphinx->SetConnectTimeout(5);
     //连接时间
     $this->_sphinx->SetArrayResult(true);
     //设置数组返回
     $this->_sphinx->SetMaxQueryTime(10);
     //设置最大超时时间
     $this->_sphinx->SetMatchMode(SPH_MATCH_ANY);
     //匹配模式
 }
 /**
  * Set Sphinx server connection parameters.
  *
  * @param array $parameters list of params, where first item is host, second is port
  * @example 'localhost'
  * @example 'localhost:3314'
  * @example array("localhost", 3386)
  * @link http://sphinxsearch.com/docs/current.html#api-func-setserver
  */
 public function setServer($parameters = null)
 {
     $server = self::DEFAULT_SERVER;
     $port = self::DEFAULT_PORT;
     if (is_string($parameters)) {
         $parameters = explode(':', $parameters);
     }
     if (isset($parameters[0])) {
         $server = $parameters[0];
     }
     if (isset($parameters[1])) {
         $port = $parameters[1];
     }
     $this->sphinxClient->SetServer($server, $port);
 }
 /**
  * @{inheritDoc}
  */
 public function initialise()
 {
     if (!class_exists('SphinxClient')) {
         require $this->phpbb_root_path . 'includes/sphinxapi.' . $this->php_ext;
     }
     $this->client = new \SphinxClient();
     $this->client->SetServer($this->config['fulltext_sphinx_host'] ? $this->config['fulltext_sphinx_host'] : 'localhost', $this->config['fulltext_sphinx_port'] ? (int) $this->config['fulltext_sphinx_port'] : 9312);
     $id = $this->get_id();
     $indexes = '';
     foreach ($this->types as $type) {
         $indexes .= "\n\t\t\t\tindex_cdb_{$type}_{$id}_main;\n\t\t\t\tindex_cdb_{$type}_{$id}_delta;\n\t\t\t";
     }
     $this->indexes = $indexes;
     return $this;
 }
 /**
  * Constructor
  * Creates a new \phpbb\search\fulltext_postgres, which is used as a search backend
  *
  * @param string|bool $error Any error that occurs is passed on through this reference variable otherwise false
  * @param string $phpbb_root_path Relative path to phpBB root
  * @param string $phpEx PHP file extension
  * @param \phpbb\auth\auth $auth Auth object
  * @param \phpbb\config\config $config Config object
  * @param \phpbb\db\driver\driver_interface Database object
  * @param \phpbb\user $user User object
  * @param \phpbb\event\dispatcher_interface	$phpbb_dispatcher	Event dispatcher object
  */
 public function __construct(&$error, $phpbb_root_path, $phpEx, $auth, $config, $db, $user, $phpbb_dispatcher)
 {
     $this->phpbb_root_path = $phpbb_root_path;
     $this->php_ext = $phpEx;
     $this->config = $config;
     $this->phpbb_dispatcher = $phpbb_dispatcher;
     $this->user = $user;
     $this->db = $db;
     $this->auth = $auth;
     // Initialize \phpbb\db\tools\tools object
     global $phpbb_container;
     // TODO inject into object
     $this->db_tools = $phpbb_container->get('dbal.tools');
     if (!$this->config['fulltext_sphinx_id']) {
         $this->config->set('fulltext_sphinx_id', unique_id());
     }
     $this->id = $this->config['fulltext_sphinx_id'];
     $this->indexes = 'index_phpbb_' . $this->id . '_delta;index_phpbb_' . $this->id . '_main';
     if (!class_exists('SphinxClient')) {
         require $this->phpbb_root_path . 'includes/sphinxapi.' . $this->php_ext;
     }
     // Initialize sphinx client
     $this->sphinx = new \SphinxClient();
     $this->sphinx->SetServer($this->config['fulltext_sphinx_host'] ? $this->config['fulltext_sphinx_host'] : 'localhost', $this->config['fulltext_sphinx_port'] ? (int) $this->config['fulltext_sphinx_port'] : 9312);
     $error = false;
 }
Exemple #12
0
 public function __construct()
 {
     parent::__construct();
     // 获取关键字
     $this->keyword = t($this->data['keyword']);
     $this->type = $this->data['type'] ? intval($this->data['type']) : 1;
     // 分页数
     $page = intval($this->data['page']);
     $page <= 0 && ($page = 1);
     // 分页大小
     $pageSize = 10;
     // 使用sphinx进行搜索功能
     $sphinx = new SphinxClient();
     // 配置sphinx服务器信息
     $sphinx->SetServer(self::SPHINX_HOST, self::SPHINX_PORT);
     // 配置返回结果集
     $sphinx->SetArrayResult(true);
     // 匹配结果偏移量
     $sphinx->SetLimits(($page - 1) * $pageSize, $pageSize, 1000);
     // 设置最大搜索时间
     $sphinx->SetMaxQueryTime(3);
     // 设置搜索模式
     $sphinx->setMatchMode(SPH_MATCH_PHRASE);
     $this->sphinx = $sphinx;
 }
Exemple #13
0
 function hook_search($search)
 {
     $offset = 0;
     $limit = 500;
     $sphinxClient = new SphinxClient();
     $sphinxpair = explode(":", SPHINX_SERVER, 2);
     $sphinxClient->SetServer($sphinxpair[0], (int) $sphinxpair[1]);
     $sphinxClient->SetConnectTimeout(1);
     $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30, 'feed_title' => 20));
     $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2);
     $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
     $sphinxClient->SetLimits($offset, $limit, 1000);
     $sphinxClient->SetArrayResult(false);
     $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
     $result = $sphinxClient->Query($search, SPHINX_INDEX);
     $ids = array();
     if (is_array($result['matches'])) {
         foreach (array_keys($result['matches']) as $int_id) {
             $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
             array_push($ids, $ref_id);
         }
     }
     $ids = join(",", $ids);
     if ($ids) {
         return array("ref_id IN ({$ids})", array());
     } else {
         return array("ref_id = -1", array());
     }
 }
 public function __construct()
 {
     parent::__construct();
     $this->infohash_model = new InfohashModel();
     $sphinx = new SphinxClient();
     $sphinx->SetServer(Config::get('app.sphinx.host'), Config::get('app.sphinx.port'));
     $sphinx->SetArrayResult(true);
     $this->sphinx = $sphinx;
 }
Exemple #15
0
function sphinx_add_result_forum($items) {
    $inCore = cmsCore::getInstance();

    global $_LANG;
    cmsCore::loadLanguage('components/forum');
    $config = $inCore->loadComponentConfig('forum');
    $search_model = cms_model_search::initModel();
    
    foreach ($items as $id => $item) {
        if (!cmsCore::checkContentAccess($item['attrs']['access_list'])) { continue; }
            
        $pages = ceil($item['attrs']['post_count'] / $config['pp_thread']);

        $result_array = array(
            'link' => '/forum/thread'. $id .'-'. $pages .'.html',
            'place' => $item['attrs']['forum'],
            'placelink' => '/forum/'. $item['attrs']['forum_id'],
            'description' => $search_model->getProposalWithSearchWord($item['attrs']['description']),
            'title' => $item['attrs']['title'],
            'pubdate' => date('Y-m-d H:i:s', $item['attrs']['pubdate'])
        );

        $search_model->addResult($result_array);
    }
    
    // Ищем в тексте постов
    
    $cl = new SphinxClient();

    $cl->SetServer('127.0.0.1', 9312);
    $cl->SetMatchMode(SPH_MATCH_EXTENDED2);
    $cl->SetLimits(0, 100);
    
    $result = $cl->Query($search_model->against, $search_model->config['Sphinx_Search']['prefix'] .'_forum_posts');
            
    if ($result !== false) {
        foreach ($result['matches'] as $id => $item) {
            $pages = ceil($item['attrs']['post_count'] / $config['pp_thread']);
            $post_page = ($pages > 1) ? postPage::getPage($item['attrs']['thread_id'], $id, $config['pp_thread']) : 1;
            
            $result_array = array(
                'link' => '/forum/thread'. $item['attrs']['thread_id'] .'-'. $post_page .'.html#'. $id,
                'place' => $_LANG['FORUM_POST'],
                'placelink' => '/forum/thread'. $item['attrs']['thread_id'] .'-'. $post_page .'.html#'. $id,
                'description' => $search_model->getProposalWithSearchWord($item['attrs']['content_html']),
                'title' => $item['attrs']['thread'],
                'imageurl' => $item['attrs']['fileurl'],
                'pubdate' => date('Y-m-d H:i:s', $item['attrs']['pubdate'])
            );

            $search_model->addResult($result_array);
        }
    }
    
    return;
}
Exemple #16
0
 public function __construct(array $config)
 {
     $this->_sphinx = new \SphinxClient();
     if (isset($config['host'])) {
         if (!isset($config['host'])) {
             $config['port'] = 9312;
         }
         $this->_sphinx->SetServer($config['host'], $config['port']);
     }
     if (isset($config['retries'])) {
         if (!isset($config['delay'])) {
             $config['delay'] = 0;
         }
         $this->_sphinx->SetRetries($config['retries'], $config['delay']);
     }
     if (isset($config['timeout'])) {
         $this->_sphinx->SetConnectTimeout($config['timeout']);
     }
 }
 public function __construct(Application $app, $host, $port, $rt_host, $rt_port)
 {
     $this->app = $app;
     $this->sphinx = new \SphinxClient();
     $this->sphinx->SetServer($host, $port);
     $this->sphinx->SetArrayResult(true);
     $this->sphinx->SetConnectTimeout(1);
     $this->suggestionClient = new \SphinxClient();
     $this->suggestionClient->SetServer($host, $port);
     $this->suggestionClient->SetArrayResult(true);
     $this->suggestionClient->SetConnectTimeout(1);
     try {
         $this->rt_conn = @new \PDO(sprintf('mysql:host=%s;port=%s;', $rt_host, $rt_port));
         $this->rt_conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
     } catch (\PDOException $e) {
         $this->rt_conn = null;
     }
     return $this;
 }
Exemple #18
0
 private function _getSphinxClient()
 {
     require_once SCRIPT_BASE . 'lib/sphinx-2.1.9/sphinxapi.php';
     $sphinxClient = new SphinxClient();
     $sphinxClient->SetServer('127.0.0.1', 9312);
     $sphinxClient->SetConnectTimeout(20);
     $sphinxClient->SetArrayResult(true);
     $sphinxClient->SetWeights(array(1000, 1));
     $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED);
     return $sphinxClient;
 }
Exemple #19
0
 /**
  * Инициализация сфинкса
  */
 protected function InitSphinx()
 {
     // * Получаем объект Сфинкса(из Сфинкс АПИ)
     $this->oSphinx = new SphinxClient();
     $sHost = Config::Get('plugin.sphinx.host');
     $nPort = 0;
     if (strpos($sHost, ':')) {
         list($sHost, $nPort) = explode(':', $sHost);
     }
     // * Подключаемся
     $this->oSphinx->SetServer($sHost, intval($nPort));
     $sError = $this->GetLastError();
     if ($sError) {
         $sError .= "\nhost:{$sHost}";
         $this->LogError($sError);
         return false;
     }
     // * Устанавливаем тип сортировки
     $this->oSphinx->SetSortMode(SPH_SORT_EXTENDED, "@weight DESC, @id DESc");
 }
Exemple #20
0
function sphinx_client()
{
    global $globals, $db;
    static $cl = false;
    if (!$cl) {
        $cl = new SphinxClient();
        $cl->SetServer($globals['sphinx_server'], $globals['sphinx_port']);
        // Request for status values, it's used in other sites
        $globals['status_values'] = $db->get_enum_values('links', 'link_status');
    }
    return $cl;
}
Exemple #21
0
 /**
  * __construct()
  * 构造函数
  */
 public function __construct()
 {
     parent::__construct();
     parent::SetServer(SPH_HOST, 9312);
     //parent::SetServer("localhost",9312);
     //parent::SetConnectTimeout(10);
     parent::SetMatchMode(SPH_MATCH_EXTENDED2);
     //parent::SetFieldWeights($this->weights);
     parent::SetRankingMode(SPH_RANK_WORDCOUNT);
     //
     parent::SetSortMode(SPH_SORT_EXTENDED, '@weight desc');
     parent::SetArrayResult(TRUE);
     $this->SetLimits($this->offset, $this->limit);
 }
Exemple #22
0
 /**
  * @return SphinxClient
  */
 public function getSphinxClient()
 {
     if (null === $this->_sphinxClient) {
         if (!class_exists("SphinxClient")) {
             $this->load->library('sphinx/sphinxapi');
         }
         $sphinxClient = new SphinxClient();
         $sphinxClient->SetServer($this->config->get('sphinx_search_server'), $this->config->get('sphinx_search_port'));
         $sphinxClient->SetConnectTimeout(1);
         //$sphinxClient->_mbenc = "UTF-8";
         $sphinxClient->ResetFilters();
         $this->_sphinxClient = $sphinxClient;
     }
     return $this->_sphinxClient;
 }
function new_sphinx()
{
    global $CONF;
    if ($CONF['unit_test_active']) {
        return new DummySphinx();
    } else {
        if (!$CONF['sphinx']) {
            return NULL;
        } else {
            $sphinx = new SphinxClient();
            $sphinx->SetServer($CONF['sphinx_host'], $CONF['sphinx_port']);
            return $sphinx;
        }
    }
}
Exemple #24
0
function sphinx_add_result_clubs($items) {
    global $_LANG;
    
    cmsCore::m('clubs');
    $search_model = cms_model_search::initModel();
    
    foreach ($items as $id => $item) {
        $result_array = array(
            'link' => cmsCore::m('clubs')->getPostURL($item['attrs']['user_id'], $item['attrs']['seolink']),
            'place' => ' &laquo;'. $item['attrs']['cat_title'] .'&raquo;',
            'placelink' => cmsCore::m('clubs')->getBlogURL($item['attrs']['user_id']),
            'description' => $search_model->getProposalWithSearchWord($item['attrs']['content_html']),
            'title' => $item['attrs']['title'],
            'imageurl' => $item['fileurl'],
            'pubdate' => date('Y-m-d H:i:s', $item['attrs']['pubdate'])
        );

        $search_model->addResult($result_array);
    }
    
    /////// поиск по клубным фоткам //////////
    $cl = new SphinxClient();

    $cl->SetServer('127.0.0.1', 9312);
    $cl->SetMatchMode(SPH_MATCH_EXTENDED2);
    $cl->SetLimits(0, 100);
    
    $result = $cl->Query($search_model->against, $search_model->config['Sphinx_Search']['prefix'] .'_clubs_photos');
            
    if ($result !== false) {
        foreach ($result['matches'] as $id => $item) {
            $result_array = array(
                'link' => '/clubs/photo'. $id .'.html',
                'place' => $_LANG['CLUBS_PHOTOALBUM'] .' &laquo;'. $item['attrs']['cat_title'] .'&raquo;',
                'placelink' => '/clubs/photoalbum'. $item['attrs']['cat_id'],
                'description' => $search_model->getProposalWithSearchWord($item['attrs']['description']),
                'title' => $item['attrs']['title'],
                'imageurl' => (file_exists(PATH .'/images/photos/medium/'. $item['attrs']['file']) ? '/images/photos/medium/'. $item['attrs']['file'] : ''),
                'pubdate' => date('Y-m-d H:i:s', $item['attrs']['pubdate'])
            );

            $search_model->addResult($result_array);
        }
    }
    
    return;
}
Exemple #25
0
 public function getSphinxAdapter()
 {
     require_once Mage::getBaseDir('lib') . DIRECTORY_SEPARATOR . 'sphinxapi.php';
     // Connect to our Sphinx Search Engine and run our queries
     $sphinx = new SphinxClient();
     $host = Mage::getStoreConfig('sphinxsearch/server/host');
     $port = Mage::getStoreConfig('sphinxsearch/server/port');
     if (empty($host)) {
         return $sphinx;
     }
     if (empty($port)) {
         $port = 9312;
     }
     $sphinx->SetServer($host, $port);
     $sphinx->SetMatchMode(SPH_MATCH_EXTENDED2);
     $sphinx->setFieldWeights(array('name' => 7, 'category' => 1, 'name_attributes' => 1, 'data_index' => 3));
     $sphinx->setLimits(0, 200, 1000, 5000);
     // SPH_RANK_PROXIMITY_BM25 ist default
     $sphinx->SetRankingMode(SPH_RANK_SPH04, "");
     // 2nd parameter is rank expr?
     return $sphinx;
 }
Exemple #26
0
 public function getResultByTag($keyword = "", $offset = 0, $limit = 0, $searchParams = array())
 {
     $sphinx = $this->config->item('sphinx');
     $query = array();
     $cl = new SphinxClient();
     $cl->SetServer($sphinx['ip'], $sphinx['port']);
     // 注意这里的主机
     $cl->SetConnectTimeout($sphinx['timeout']);
     $cl->SetArrayResult(true);
     //         $cl->SetIDRange(89,90);//过滤ID
     if (isset($searchParams['provice_sid']) && $searchParams['provice_sid']) {
         $cl->setFilter('provice_sid', array($searchParams['provice_sid']));
     }
     if (isset($searchParams['city_sid']) && $searchParams['city_sid']) {
         $cl->setFilter('city_sid', array($searchParams['city_sid']));
     }
     if (isset($searchParams['piccode']) && $searchParams['piccode']) {
         $cl->setFilter('piccode', array($searchParams['piccode']));
     }
     if (isset($searchParams['recent']) && $searchParams['recent']) {
         $cl->SetFilterRange('createtime', time() - 86400 * 30, time());
         //近期1个月
     }
     if (isset($searchParams['searchtype']) && $searchParams['searchtype']) {
         //精确:模糊
         $searchtype = SPH_MATCH_ALL;
     } else {
         $searchtype = SPH_MATCH_ANY;
     }
     $cl->SetLimits($offset, $limit);
     $cl->SetMatchMode($searchtype);
     // 使用多字段模式
     $cl->SetSortMode(SPH_SORT_EXTENDED, "@weight desc,@id desc");
     $index = "*";
     $query = $cl->Query($keyword, $index);
     $cl->close();
     return $query;
 }
Exemple #27
0
 /**
  * sphinx search
  */
 public function sphinxSearch(Request $request, \SphinxClient $sphinx)
 {
     $search = $request->get('search');
     //sphinx的主机名和端口  //mysql -h 127.0.0.1 -P 9306
     $sphinx->SetServer('127.0.0.1', 9312);
     //设定搜索模式 SPH_MATCH_ALL(匹配所有的查询词)
     $sphinx->SetMatchMode(SPH_MATCH_ALL);
     //设置返回结果集为数组格式
     $sphinx->SetArrayResult(true);
     //匹配结果的偏移量,参数的意义依次为:起始位置,返回结果条数,最大匹配条数
     $sphinx->SetLimits(0, 20, 1000);
     //最大搜索时间
     $sphinx->SetMaxQueryTime(10);
     //索引源是配置文件中的 index 类,如果有多个索引源可使用,号隔开:'email,diary' 或者使用'*'号代表全部索引源
     $result = $sphinx->query($search, '*');
     //返回值说明  total 本次查询返回条数  total_found 一共检索到多少条   docs 在多少文档中出现  hits——共出现了多少次
     //关闭查询连接
     $sphinx->close();
     //打印结果
     /*echo "<pre>";
       print_r($result);
       echo "</pre>";exit();*/
     $ids = [0];
     if (!empty($result)) {
         foreach ($result['matches'] as $key => $val) {
             $ids[] = $val['id'];
         }
     }
     $ids = implode(',', array_unique($ids));
     $list = DB::select("SELECT * from documents WHERE id IN ({$ids})");
     if (!empty($list)) {
         foreach ($list as $key => $val) {
             $val->content = str_replace($search, '<span style="color: red;">' . $search . '</span>', $val->content);
             $val->title = str_replace($search, '<span style="color: red;">' . $search . '</span>', $val->title);
         }
     }
     return view('/sphinx.search')->with('data', array('total' => $result['total'] ? $result['total'] : 0, 'time' => $result['time'] ? $result['time'] : 0, 'list' => $list));
 }
Exemple #28
0
    fwrite($stdout, "Sphinx is disabled in config.php.\n");
    exit(0);
}
$SphinxAPI = realpath($CATSHome . '/' . SPHINX_API);
if (!file_exists($SphinxAPI)) {
    fwrite($stderr, "Config Error: SPHINX_API could not be found.\n");
    exit(1);
}
include $SphinxAPI;
/* Sphinx API likes to throw PHP errors *AND* use it's own error
 * handling.
 */
assert_options(ASSERT_WARNING, 0);
/* Execute the Sphinx query. */
$sphinx = new SphinxClient();
$sphinx->SetServer(SPHINX_HOST, SPHINX_PORT);
$sphinx->SetWeights(array(0, 100, 0, 0, 50));
$sphinx->SetMatchMode(SPH_MATCH_BOOLEAN);
$sphinx->SetLimits(0, 10);
$sphinx->SetSortMode(SPH_SORT_TIME_SEGMENTS, 'date_added');
$sphinx->SetFilter('site_id', TEST_SITE_ID);
/* Execute the Sphinx query. Sphinx can ask us to retry if its
 * maxed out. Retry up to 5 times.
 */
$tries = 0;
do {
    /* Wait for one second if this isn't out first attempt. */
    if (++$tries > 1) {
        sleep(1);
    }
    $results = $sphinx->Query(TEST_QUERY, SPHINX_INDEX);
 public function index()
 {
     C('TOKEN_ON', false);
     $seo = seo();
     $this->assign("seo", $seo);
     if (isset($_GET['q'])) {
         G('search');
         //关键字
         $q = Input::forSearch(safe_replace($this->_get("q")));
         $q = htmlspecialchars(strip_tags($q));
         //时间范围
         $time = $this->_get("time");
         //模型
         $mid = (int) $this->_get("modelid");
         //栏目
         $catid = (int) $this->_get("catid");
         //排序
         $order = array("adddate" => "DESC", "searchid" => "DESC");
         //搜索历史记录
         $shistory = cookie("shistory");
         if (!$shistory) {
             $shistory = array();
         }
         $model = F("Model");
         $category = F("Category");
         if (trim($_GET['q']) == '') {
             header('Location: ' . U("Search/Index/index"));
             exit;
         }
         array_unshift($shistory, $q);
         $shistory = array_slice(array_unique($shistory), 0, 10);
         //加入搜索历史
         cookie("shistory", $shistory);
         $where = array();
         //每页显示条数
         $pagesize = $this->config['pagesize'] ? $this->config['pagesize'] : 10;
         //缓存时间
         $cachetime = (int) $this->config['cachetime'];
         //按时间搜索
         if ($time == 'day') {
             //一天
             $search_time = time() - 86400;
             $where['adddate'] = array("GT", $search_time);
         } elseif ($time == 'week') {
             //一周
             $search_time = time() - 604800;
             $where['adddate'] = array("GT", $search_time);
         } elseif ($time == 'month') {
             //一月
             $search_time = time() - 2592000;
             $where['adddate'] = array("GT", $search_time);
         } elseif ($time == 'year') {
             //一年
             $search_time = time() - 31536000;
             $where['adddate'] = array("GT", $search_time);
         } else {
             $search_time = 0;
         }
         //可用数据源
         $this->config['modelid'] = $this->config['modelid'] ? $this->config['modelid'] : array();
         //按模型搜索
         if ($mid && in_array($mid, $this->config['modelid'])) {
             $where['modelid'] = array("EQ", (int) $mid);
         }
         //按栏目搜索
         if ($catid) {
             //不支持多栏目搜索,和父栏目搜索。
             $where['catid'] = array("EQ", (int) $catid);
         }
         //分页模板
         $TP = '共有{recordcount}条信息&nbsp;{pageindex}/{pagecount}&nbsp;{first}{prev}{liststart}{list}{listend}{next}{last}';
         //如果开启sphinx
         if ($this->config['sphinxenable']) {
             import("Sphinxapi", APP_PATH . C("APP_GROUP_PATH") . '/Search/Class/');
             $sphinxhost = $this->config['sphinxhost'];
             $sphinxport = $this->config['sphinxport'];
             $cl = new SphinxClient();
             //设置searchd的主机名和TCP端口
             $cl->SetServer($sphinxhost, $sphinxport);
             //设置连接超时
             $cl->SetConnectTimeout(1);
             //控制搜索结果集的返回格式
             $cl->SetArrayResult(true);
             //设置全文查询的匹配模式 api http://docs.php.net/manual/zh/sphinxclient.setmatchmode.php
             $cl->SetMatchMode(SPH_MATCH_EXTENDED2);
             //设置排名模式 api http://docs.php.net/manual/zh/sphinxclient.setrankingmode.php
             $cl->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
             //按一种类似SQL的方式将列组合起来,升序或降序排列。用weight是权重排序
             $cl->SetSortMode(SPH_SORT_EXTENDED, "@weight desc");
             //设置返回结果集偏移量和数目
             $page = (int) $this->_get(C("VAR_PAGE"));
             $page = $page < 1 ? 1 : $page;
             $offset = $pagesize * ($page - 1);
             $cl->SetLimits($offset, $pagesize, $pagesize > 1000 ? $pagesize : 1000);
             if (in_array($time, array("day", "week", "month", "year"))) {
                 //过滤时间
                 $cl->SetFilterRange('adddate', $search_time, time(), false);
             }
             if ($mid && in_array($mid, $this->config['modelid'])) {
                 //过滤模型
                 $cl->SetFilter('modelid', (int) $mid);
             }
             if ($catid) {
                 //过滤栏目
                 $cl->SetFilter('catid', (int) $catid);
             }
             //执行搜索 api http://docs.php.net/manual/zh/sphinxclient.query.php
             $res = $cl->Query($q, "*");
             //信息总数
             $count = $res['total'];
             //如果结果不为空
             if (!empty($res['matches'])) {
                 $result_sphinx = $res['matches'];
             }
             $result = array();
             //数组重新组合
             foreach ($result_sphinx as $k => $v) {
                 $result[$k] = array("searchid" => $v['id'], "adddate" => $v['attrs']['adddate'], "catid" => $v['attrs']['catid'], "id" => $v['attrs']['id'], "modelid" => $v['attrs']['modelid']);
             }
             $words = array();
             //搜索关键字
             foreach ($res['words'] as $k => $v) {
                 $words[] = $k;
             }
             $page = page($count, $pagesize);
             $page->SetPager('default', $TP, array("listlong" => "6", "first" => "首页", "last" => "尾页", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => ""));
             $this->assign("Page", $page->show('default'));
         } else {
             import("Segment", APP_PATH . C("APP_GROUP_PATH") . '/Search/Class/');
             $Segment = new Segment();
             //分词结果
             $segment_q = $Segment->get_keyword($Segment->split_result($q));
             $words = explode(" ", $segment_q);
             if (!empty($segment_q)) {
                 $where['_string'] = " MATCH (`data`) AGAINST ('{$segment_q}' IN BOOLEAN MODE) ";
             } else {
                 //这种搜索最不行
                 $where['data'] = array('like', "%{$q}%");
             }
             //查询结果缓存
             if ($cachetime) {
                 //统计
                 $count = M("Search")->cache(true, $cachetime)->where($where)->count();
                 $page = page($count, $pagesize);
                 $result = M("Search")->cache(true, $cachetime)->where($where)->limit($page->firstRow . ',' . $page->listRows)->order($order)->select();
             } else {
                 $count = M("Search")->where($where)->count();
                 $page = $this->page($count, $pagesize);
                 $result = M("Search")->where($where)->limit($page->firstRow . ',' . $page->listRows)->order($order)->select();
             }
             $page->SetPager('default', $TP, array("listlong" => "6", "first" => "首页", "last" => "尾页", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => ""));
             $this->assign("Page", $page->show('default'));
         }
         //搜索结果处理
         if ($result && is_array($result)) {
             foreach ($result as $k => $r) {
                 $modelid = $r['modelid'];
                 $id = $r['id'];
                 $tablename = ucwords($model[$modelid]['tablename']);
                 if ($tablename) {
                     $result[$k] = M($tablename)->where(array("id" => $id))->find();
                 }
             }
         }
         //搜索记录
         if (strlen($q) < 17 && strlen($q) > 1 && $result) {
             $res = M("SearchKeyword")->where(array('keyword' => $q))->find();
             if ($res) {
                 //关键词搜索数+1
                 M("SearchKeyword")->where(array('keyword' => $q))->setInc("searchnums");
             } else {
                 //关键词转换为拼音
                 load("@.iconvfunc");
                 $pinyin = gbk_to_pinyin(iconv('utf-8', 'gbk//IGNORE', $q));
                 if (is_array($pinyin)) {
                     $pinyin = implode('', $pinyin);
                 }
                 M("SearchKeyword")->add(array('keyword' => $q, 'searchnums' => 1, 'data' => $segment_q, 'pinyin' => $pinyin));
             }
         }
         //相关搜索功能
         if ($this->config['relationenble']) {
             $map = array();
             //相关搜索
             if (!empty($segment_q)) {
                 $relation_q = str_replace(' ', '%', $segment_q);
             } else {
                 $relation_q = $q;
             }
             $map['_string'] = " MATCH (`data`) AGAINST ('%{$relation_q}%' IN BOOLEAN MODE) ";
             $relation = M("SearchKeyword")->where($map)->select();
             $this->assign("relation", $relation);
         }
         foreach ($this->config['modelid'] as $modelid) {
             $source[$modelid] = array("name" => $model[$modelid]['name'], "modelid" => $modelid);
         }
         //搜索结果
         $this->assign("result", $result);
         //运行时间
         $search_time = G('search', 'end', 6);
         $this->assign("count", $count ? $count : 0);
         $this->assign("search_time", $search_time);
         $this->assign("keyword", $q);
         $this->assign("category", $category);
         $this->assign("source", $source);
         $this->assign("time", $time);
         $this->assign("modelid", $mid);
         $this->assign("shistory", $shistory);
         //分词后的搜索关键字
         $this->assign("words", $words);
         $this->display("search");
     } else {
         $this->display();
     }
 }
function do_query($search_str)
{
    //$tmp_var = array(array('itemName' => "test1"), array('itemName' => "test2"), array('itemName' => "test3"));
    //echo implode(",",tmp_var);
    //echo json_encode($tmp_var);
    //return tmp_var;
    $q = "";
    $sql = "";
    $mode = SPH_MATCH_ALL;
    $host = "localhost";
    $port = 9312;
    $index = "*";
    $groupby = "";
    $groupsort = "@group desc";
    $filter = "group_id";
    $filtervals = array();
    $distinct = "";
    $sortby = "";
    $sortexpr = "";
    $limit = 20;
    $ranker = SPH_RANK_PROXIMITY_BM25;
    $select = "*";
    $cl = new SphinxClient();
    $cl->SetServer($host, $port);
    $cl->SetConnectTimeout(1);
    $cl->SetArrayResult(true);
    $cl->SetWeights(array(100, 1));
    $cl->SetMatchMode($mode);
    if (count($filtervals)) {
        $cl->SetFilter($filter, $filtervals);
    }
    if ($groupby) {
        $cl->SetGroupBy($groupby, SPH_GROUPBY_ATTR, $groupsort);
    }
    if ($sortby) {
        $cl->SetSortMode(SPH_SORT_EXTENDED, $sortby);
    }
    if ($sortexpr) {
        $cl->SetSortMode(SPH_SORT_EXPR, $sortexpr);
    }
    if ($distinct) {
        $cl->SetGroupDistinct($distinct);
    }
    if ($select) {
        $cl->SetSelect($select);
    }
    if ($limit) {
        $cl->SetLimits(0, $limit, $limit > 1000 ? $limit : 1000);
    }
    $cl->SetRankingMode($ranker);
    $res = $cl->Query($search_str, $index);
    //return $res;
    if (is_array($res["matches"])) {
        $results = array();
        $n = 1;
        //print "Matches:\n";
        foreach ($res["matches"] as $docinfo) {
            //print "$n. doc_id=$docinfo[id], weight=$docinfo[weight]";
            $attr_array = array();
            $results[$docinfo[id]];
            foreach ($res["attrs"] as $attrname => $attrtype) {
                $value = $docinfo["attrs"][$attrname];
                if ($attrtype == SPH_ATTR_MULTI || $attrtype == SPH_ATTR_MULTI64) {
                    $value = "(" . join(",", $value) . ")";
                } else {
                    if ($attrtype == SPH_ATTR_TIMESTAMP) {
                        $value = date("Y-m-d H:i:s", $value);
                    }
                }
                $attr_array[$attrname] = $value;
                //print $value;
            }
            $results[$docinfo[id]] = $attr_array;
            $n++;
            //print implode("",$results)."\n";
        }
        return $results;
    }
}