/** * 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; }
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 static function getInstance($sphinxconf, $type = 'media') { $time = microtime(true); $rand = intval(substr($time, 11, 4)); $num = count($sphinxconf); $index = $rand % $num; $ret = false; if (null == self::$_sphinxpool[$type]) { $try_count = 0; while ($try_count < 3 && $ret != true) { $client = new SphinxClient(); $index = $index % $num; try { $client->setServer($sphinxconf[$index]['host'], $sphinxconf[$index]['port']); self::$_index[$type] = $sphinxconf[$index]['indexer']; $ret = $client->Open(); if ($ret == true) { self::$_conf_num[$type] = $index; break; } Systemlog::fatal("sphinx connect fail time:" . $client->_host . " " . $client->_port); $try_count++; $index++; } catch (Exception $e) { $index++; $try_count++; } } self::$_sphinxpool[$type] = $client; } return self::$_sphinxpool[$type]; }
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; }
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; }
/** * do driver instance init */ public function setup() { $settings = $this->getSettings(); if (empty($settings)) { throw new BoxRouteInstanceException('init driver instance failed: empty settings'); } $curInst = new \SphinxClient(); $curInst->setServer($settings['sphinxHost'], $settings['sphinxPort']); !empty($settings['sphinxConnectTimeout']) && $curInst->setConnectTimeout($settings['sphinxConnectTimeout']); $this->instance = $curInst; $this->isAvailable = $this->instance ? true : false; }
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; }
/** * Search in sphinx client * * @param string $query * @param string $index * @return SphinxResult|string * @throws \Exception */ public function search($query, $index = '*') { $result = $this->_sphinx_client->Query($query, $index); if (!$result) { throw new \Exception("Sphinx client error: " . $this->_sphinx_client->GetLastError()); } else { if (!empty($result['warning'])) { return $this->_sphinx_client->GetLastWarning(); } return new SphinxResult($result); } }
/** * @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; } } }
private function get_sugg_trigrams($word, SearchEngineOptions $options) { $trigrams = $this->BuildTrigrams($word); $query = "\"{$trigrams}\"/1"; $len = strlen($word); $this->resetSphinx(); $this->suggestionClient->SetMatchMode(SPH_MATCH_EXTENDED2); $this->suggestionClient->SetRankingMode(SPH_RANK_WORDCOUNT); $this->suggestionClient->SetFilterRange("len", $len - 2, $len + 4); $this->suggestionClient->SetSortMode(SPH_SORT_EXTENDED, "@weight DESC"); $this->suggestionClient->SetLimits(0, 10); $indexes = []; foreach ($options->getDataboxes() as $databox) { $indexes[] = 'suggest' . $this->CRCdatabox($databox); } $index = implode(',', $indexes); $res = $this->suggestionClient->Query($query, $index); if ($this->suggestionClient->Status() === false) { return []; } if (!$res || !isset($res["matches"])) { return []; } $words = []; foreach ($res["matches"] as $match) { $words[] = $match['attrs']['keyword']; } return $words; }
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' => ' «'. $item['attrs']['cat_title'] .'»', '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'] .' «'. $item['attrs']['cat_title'] .'»', '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; }
/** * Delete a post from the index after it was deleted */ public function index_remove($post_ids, $author_ids, $forum_ids) { $values = array(); foreach ($post_ids as $post_id) { $values[$post_id] = array(1); } $this->sphinx->UpdateAttributes($this->indexes, array('deleted'), $values); }
/** * Adds new integer values set filter to the existing list of filters. * * @param $attribute An attribute name. * @param $values Plain array of integer values. * @param bool $exclude If set to TRUE, matching items are excluded from the result set. * @return SphinxSearch_Abstract_List * @throws Exception on failure */ public function setFilter($attribute, $values, $exclude = false) { $result = $this->SphinxClient->SetFilter($attribute, $values, $exclude); if ($result === false) { throw new Exception("Error on setting filter \"" . $attribute . "\":\n" . $this->SphinxClient->GetLastError()); } return $this; }
/** * Отправляет подготовленный запрос на сфинкс, и преобразует ответ в нужный вид. * * @param string $query поисковый запрос (в оригинальном виде) * @param int $storeId ИД текущего магазина * @param string $indexCode Код индекса по которому нужно провести поиск (mage_catalog_product ...) * @param string $primaryKey Primary Key индекса (entity_id, category_id, post_id ...) * @param array $attributes Масив атрибутов с весами * @param int $offset Страница * * @return array масив ИД елементов, где ИД - ключ, релевантность значение */ protected function _query($query, $storeId, $index, $offset = 1) { $uid = Mage::helper('mstcore/debug')->start(); $indexCode = $index->getCode(); $primaryKey = $index->getPrimaryKey(); $attributes = $index->getAttributes(); $client = new SphinxClient(); $client->setMaxQueryTime(5000); //5 seconds $client->setLimits(($offset - 1) * self::PAGE_SIZE, self::PAGE_SIZE, $this->_config->getResultLimit()); $client->setSortMode(SPH_SORT_RELEVANCE); $client->setMatchMode(SPH_MATCH_EXTENDED); $client->setServer($this->_spxHost, $this->_spxPort); $client->SetFieldWeights($attributes); if ($storeId) { $client->SetFilter('store_id', $storeId); } $sphinxQuery = $this->_buildQuery($query, $storeId); if (!$sphinxQuery) { return array(); } $sphinxQuery = '@(' . implode(',', $index->getSearchableAttributes()) . ')' . $sphinxQuery; $sphinxResult = $client->query($sphinxQuery, $indexCode); if ($sphinxResult === false) { Mage::throwException($client->GetLastError() . "\nQuery: " . $query); } elseif ($sphinxResult['total'] > 0) { $entityIds = array(); foreach ($sphinxResult['matches'] as $data) { $entityIds[$data['attrs'][strtolower($primaryKey)]] = $data['weight']; } if ($sphinxResult['total'] > $offset * self::PAGE_SIZE && $offset * self::PAGE_SIZE < $this->_config->getResultLimit()) { $newIds = $this->_query($query, $storeId, $index, $offset + 1); foreach ($newIds as $key => $value) { $entityIds[$key] = $value; } } } else { $entityIds = array(); } $entityIds = $this->_normalize($entityIds); Mage::helper('mstcore/debug')->end($uid, $entityIds); return $entityIds; }
/** * 获取竞品信息 * @author zhangxiao@dachuwang.com */ public function get_list($friend_id = null, $city_id = null, $key, $key_word = null, $cate_name = null, $offset = 0, $page_size = 10) { $key = $key ?: $this->input->get_post('search_key', TRUE); $key_word = $key_word ?: $this->input->get_post('search_value', TRUE); $cate_name = $cate_name ?: $this->input->get_post('cate_name', TRUE); $friend_id = $friend_id ?: $this->input->get_post('friend_id', TRUE); $city_id = $city_id ?: $this->input->get_post('city_id', TRUE); //使用sphinx $s = new SphinxClient(); $s->setServer(C('service.spider'), 9312); $s->setMatchMode(SPH_MATCH_EXTENDED2); $s->setLimits($offset, $page_size, 100000); $s->setMaxQueryTime(30); //筛选友商城市 if ($city_id != C('open_cities.quanguo.id')) { $s->setFilter('city_id', array($city_id)); } //筛选友商站点 if ($friend_id != C('anti_sites.all.id')) { $s->setFilter('site_id', array($friend_id)); } $s->SetSortMode(SPH_SORT_EXTENDED, "product_id asc"); $fields = ''; //筛选关键字 if ($key_word) { if ($key == 'product_name') { $fields .= '@title "' . $key_word . '" '; } elseif ($key == 'product_id') { $s->setFilter('product_id', array($key_word)); } elseif ($key == 'sku_number') { $auto_ids = $this->_get_product_by_sku_num($key_word); if ($auto_ids) { $s->setFilter('auto_id', $auto_ids); } else { return array('total' => 0, 'data' => []); } } } //筛选友商品类名称 if ($cate_name) { $fields .= '@category_name "' . $cate_name . '" '; } $result = $s->query($fields, 'anti_products'); if (isset($result['matches'])) { $list = array_column($result['matches'], 'attrs'); } else { $list = array(); } $final_list = $this->_assemble_sku_num($list); $return = array('total' => $result['total'], 'data' => $final_list); return $return; }
public function __construct() { parent::SphinxClient(); $ci = get_instance(); $ci->load->config('sphinx', TRUE); $this->config = $ci->config->item('sphinx'); foreach ($this->config as $k => $i) { @call_user_func_array(array($this, 'Set' . $k), $i); } $this->SetSortMode(SPH_SORT_EXTENDED, '@weight DESC, @id DESC'); }
public function executeSearch(sfWebRequest $request) { $q = $request->getParameter('q'); include '/home/jackbravo/work/sphinx-0.9.9-rc1/api/sphinxapi.php'; $s = new SphinxClient(); $result = $s->query($q); if ($result['total'] > 0) { $query = Doctrine::getTable('Issue')->findIdsQuery(array_keys($result['matches'])); } else { $query = Doctrine::getTable('Issue')->findNullQuery(); } $pager = new sfDoctrinePager('Issue', sfConfig::get('app_max_issues_on_index')); $pager->setQuery($query); $pager->setPage($request->getParameter('page', 1)); $pager->setTableMethod('getListQuery'); $pager->init(); $this->filter = $this->getFilter($request); $this->pager = $pager; $this->from_search = $q; $this->setTemplate('index'); }
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; }
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; }
function MakeSuggestion($keyword) { $trigrams = BuildTrigrams($keyword); $query = "\"{$trigrams}\"/1"; $len = strlen($keyword); $delta = LENGTH_THRESHOLD; $cl = new SphinxClient(); $cl->SetMatchMode(SPH_MATCH_EXTENDED2); $cl->SetRankingMode(SPH_RANK_WORDCOUNT); $cl->SetFilterRange("len", $len - $delta, $len + $delta); $cl->SetSelect("*, @weight+{$delta}-abs(len-{$len}) AS myrank"); $cl->SetSortMode(SPH_SORT_EXTENDED, "myrank DESC, freq DESC"); $cl->SetArrayResult(true); // pull top-N best trigram matches and run them through Levenshtein $cl->SetLimits(0, TOP_COUNT); $res = $cl->Query($query, "suggest"); if (!$res || !$res["matches"]) { return false; } if (SUGGEST_DEBUG) { print "--- DEBUG START ---\n"; foreach ($res["matches"] as $match) { $w = $match["attrs"]["keyword"]; $myrank = @$match["attrs"]["myrank"]; if ($myrank) { $myrank = ", myrank={$myrank}"; } // FIXME? add costs? // FIXME! does not work with UTF-8.. THIS! IS!! PHP!!! $levdist = levenshtein($keyword, $w); print "id={$match['id']}, weight={$match['weight']}, freq={$match[attrs][freq]}{$myrank}, word={$w}, levdist={$levdist}\n"; } print "--- DEBUG END ---\n"; } // further restrict trigram matches with a sane Levenshtein distance limit foreach ($res["matches"] as $match) { $suggested = $match["attrs"]["keyword"]; if (levenshtein($keyword, $suggested) <= LEVENSHTEIN_THRESHOLD) { return $suggested; } } return $keyword; }
public static function newSphinxClient() { $s = new SphinxClient(); $s->setServer(Yii::app()->params['sphinx_servername'], Yii::app()->params['sphinx_port']); $s->setMaxQueryTime(10000); $s->setLimits(0, 5000, 5000); $s->setMatchMode(SPH_MATCH_EXTENDED); return $s; }
/** * Reset settings sphinx */ public function resetClient() { $this->_client->resetFilters(); $this->_client->resetGroupBy(); $this->_client->setArrayResult(false); //DEPRECATED: Do not call this method or, even better, use SphinxQL instead of an API //$this->_client->setMatchMode(SPH_MATCH_EXTENDED2); $this->_client->setLimits(0, 20, 1000, 0); $this->_client->setFieldWeights(array()); $this->_client->setSortMode(SPH_SORT_RELEVANCE, ''); $this->_client->_error = ''; $this->_client->_warning = ''; }
function query($query, $index, $offset = 0) { require_once DIR . "lib/sphinx/sphinxapi.php"; $sphinx = new SphinxClient(); $sphinx->setServer(SPHINX_HOST, SPHINX_PORT); $sphinx->SetLimits($offset, 100, 10000000); $sphinx->SetMatchMode(SPH_MATCH_EXTENDED); $sphinx->SetSortMode(SPH_SORT_ATTR_DESC, 'date_posted'); $res = $sphinx->Query($query, $index); return $res; }
/** * 搜索faq * @param string $keywords 搜索的字符串 * @param int $gameId 游戏ID * @param int $langId 语言 * @param int $kindId 分类ID */ public function search($keywords, $gameId = null, $langId = NULL, $kindId = null) { if (is_numeric($langId)) { $this->_sphinx->SetFilter('lang_id', array($langId), false); } if (is_numeric($gameId)) { $this->_sphinx->SetFilter('game_type_id', array($gameId), false); } if (is_numeric($kindId)) { $this->_sphinx->SetFilter('kind_id', array($kindId), false); } if (is_numeric($this->_faqStatus)) { $this->_sphinx->SetFilter('status', array($this->_faqStatus), true); } $result = $this->_sphinx->Query($keywords); $retResult = array('data' => $this->_getResult($result['matches']), 'info' => array('total' => $result['total'], 'total_found' => $result['total_found'], 'time' => $result['time'], 'words' => $result['words'])); return $retResult; }
/** * Search for the specified query string. * * @param string $query The query string that we are searching for. * @param array $indexes The indexes to perform the search on. * * @return array The results of the search. * * $indexes should look like: * * $indexes = array( * 'IndexLabel' => array( * 'result_offset' => (int), // optional unless result_limit is set * 'result_limit' => (int), // optional unless result_offset is set * 'field_weights' => array( // optional * 'FieldName' => (int), * ..., * ), * ), * ..., * ); */ public function search($query, array $indexes, $escapeQuery = true) { if ($escapeQuery) { $query = $this->sphinx->escapeString($query); } $results = array(); foreach ($indexes as $label => $options) { /** * Ensure that the label corresponds to a defined index. */ if (!isset($this->indexes[$label])) { continue; } /** * Set the offset and limit for the returned results. */ if (isset($options['result_offset']) && isset($options['result_limit'])) { $this->sphinx->setLimits($options['result_offset'], $options['result_limit']); } /** * Weight the individual fields. */ if (isset($options['field_weights'])) { $this->sphinx->setFieldWeights($options['field_weights']); } /** * Perform the query. */ $results[$label] = $this->sphinx->query($query, implode(' ', $this->indexes[$label]["index"])); if ($results[$label]['status'] !== SEARCHD_OK) { throw new \RuntimeException(sprintf('Searching index "%s" for "%s" failed with error "%s".', $label, $query, $this->sphinx->getLastError())); } } /** * If only one index was searched, return that index's results directly. */ if (count($indexes) === 1 && count($results) === 1) { $results = reset($results); } /** * FIXME: Throw an exception if $results is empty? */ return $results; }
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; }
protected function execute() { $sph = $this->sphinxClient->RunQueries(); if ($error = $this->sphinxClient->GetLastError()) { throw new ESphinxException($error); } if ($error = $this->sphinxClient->GetLastWarning()) { throw new ESphinxException($error); } if (!is_array($sph)) { throw new ESphinxException("Sphinx client returns result not array"); } $results = array(); foreach ($sph as $result) { if (isset($result['error']) && strlen($result['error'])) { throw new ESphinxException($result['error']); } $results[] = new ESphinxResult($result); } return $results; }
/** * 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)); }
function Query($query, $pIndexMixed, $comment = "") { global $gBitDb; $ret = array(); if (is_numeric($pIndexMixed)) { $searchIndex = $this->getIndex($pIndexMixed); } elseif (is_string($pIndexMixed)) { $searchIndex['index_name'] = $pIndexMixed; } elseif (is_array($pIndexMixed)) { $searchIndex =& $pIndexMixed; } // $this->SetMatchMode(SPH_MATCH_PHRASE); $this->SetServer($searchIndex['host'], (int) $searchIndex['port']); if (!empty($searchIndex['index_options']['field_weights'])) { $this->SetFieldWeights($searchIndex['index_options']['field_weights']); } if (!empty($searchIndex['index_options']['index_weights'])) { $this->SetIndexWeights($searchIndex['index_options']['index_weights']); } if (!empty($searchIndex['index_name']) && ($ret = parent::Query($query, $searchIndex['index_name'], $comment))) { $ret['query'] = $query; $ret['index_name'] = $searchIndex['index_name']; $processorFunction = !empty($searchIndex['result_processor_function']) ? $searchIndex['result_processor_function'] : 'sphinx_liberty_results'; if (function_exists($processorFunction)) { $ret = $processorFunction($ret); } } if (!empty($searchIndex['index_id'])) { $truncQuery = substr($query, 0, 250); $res = $gBitDb->query("UPDATE `" . BIT_DB_PREFIX . "sphinx_search_log` SET `last_searched`=?, `last_searched_ip`=?, `search_count`=`search_count`+1 WHERE `search_phrase`=? AND `index_id`=?", array(time(), $_SERVER['REMOTE_ADDR'], $truncQuery, $searchIndex['index_id'])); if (!$gBitDb->mDb->Affected_Rows()) { $gBitDb->query("INSERT INTO `" . BIT_DB_PREFIX . "sphinx_search_log` (`last_searched`, `last_searched_ip`, `search_phrase`, `index_id`) VALUES(?,?,?,?)", array(time(), $_SERVER['REMOTE_ADDR'], $truncQuery, $searchIndex['index_id'])); } } return $ret; }