/** * 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); } }
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()); } }
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; }
/** * 搜索faq * @param string $keywords 搜索的字符串 * @param int $gameId 游戏ID * @param int $kindId 分类ID */ public function search($keywords, $gameId = null, $kindId = null) { $this->_sphinx->SetFilter('lang_id', array(C('LANG_ID')), 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; }
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; }
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; }
/** * Calls SphinxClient::query * @param $query * @param string $comment * @return bool */ public function query($query, $comment = "") { $results = $this->client->Query($query, $this->_indices, $comment); if (!$results) { if ($this->getError(true)) { $this->modx->log(modX::LOG_LEVEL_ERROR, "Sphinx search connection failed on API side"); } $this->modx->log(modX::LOG_LEVEL_ERROR, "Sphinx search issued error: " . $this->getError()); } if ($this->getWarning() != '') { $this->modx->log(modX::LOG_LEVEL_WARN, "Sphinx search issued warning: " . $this->getWarning()); } return $results; }
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; }
/** * Непосредственно сам поиск * * @param string $sQuery Поисковый запрос * @param string $sObjType Тип поиска * @param int $iOffset Сдвиг элементов * @param int $iLimit Количество элементов * @param array $aExtraFilters Список фильтров * * @return array */ public function FindContent($sQuery, $sObjType, $iOffset, $iLimit, $aExtraFilters) { // * используем кеширование при поиске $sExtraFilters = serialize($aExtraFilters); $cacheKey = Config::Get('plugin.sphinx.prefix') . "searchResult_{$sObjType}_{$sQuery}_{$iOffset}_{$iLimit}_{$sExtraFilters}"; if (false === ($data = E::ModuleCache()->Get($cacheKey))) { // * Параметры поиска $this->oSphinx->SetMatchMode(SPH_MATCH_ALL); $this->oSphinx->SetLimits($iOffset, $iLimit, 1000); // * Устанавливаем атрибуты поиска $this->oSphinx->ResetFilters(); if (!is_null($aExtraFilters)) { foreach ($aExtraFilters as $sAttribName => $sAttribValue) { $this->oSphinx->SetFilter($sAttribName, is_array($sAttribValue) ? $sAttribValue : array($sAttribValue)); } } // * Ищем $sIndex = Config::Get('plugin.sphinx.prefix') . $sObjType . 'Index'; $data = $this->oSphinx->Query($sQuery, $sIndex); if (!is_array($data)) { // Если false, то, скорее всего, ошибка и ее пишем в лог $sError = $this->GetLastError(); if ($sError) { $sError .= "\nquery:{$sQuery}\nindex:{$sIndex}"; if ($aExtraFilters) { $sError .= "\nfilters:"; foreach ($aExtraFilters as $sAttribName => $sAttribValue) { $sError .= $sAttribName . '=(' . (is_array($sAttribValue) ? join(',', $sAttribValue) : $sAttribValue) . ')'; } } $this->LogError($sError); } return false; } /** * Если результатов нет, то и в кеш писать не стоит... * хотя тут момент спорный */ if ($data['total'] > 0) { E::ModuleCache()->Set($data, $cacheKey, array(), 60 * 15); } } return $data; }
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; }
/** * Непосредственно сам поиск * * @param string $sTerms Поисковый запрос * @param string $sObjType Тип поиска * @param int $iOffset Сдвиг элементов * @param int $iLimit Количество элементов * @param array $aExtraFilters Список фильтров * @return array */ public function FindContent($sTerms, $sObjType, $iOffset, $iLimit, $aExtraFilters) { /** * используем кеширование при поиске */ $sExtraFilters = serialize($aExtraFilters); $cacheKey = Config::Get('module.search.entity_prefix') . "searchResult_{$sObjType}_{$sTerms}_{$iOffset}_{$iLimit}_{$sExtraFilters}"; if (false === ($data = $this->Cache_Get($cacheKey))) { /** * Параметры поиска */ $this->oSphinx->SetMatchMode(SPH_MATCH_ALL); $this->oSphinx->SetLimits($iOffset, $iLimit); /** * Устанавливаем атрибуты поиска */ $this->oSphinx->ResetFilters(); if (!is_null($aExtraFilters)) { foreach ($aExtraFilters as $sAttribName => $sAttribValue) { $this->oSphinx->SetFilter($sAttribName, is_array($sAttribValue) ? $sAttribValue : array($sAttribValue)); } } /** * Ищем */ if (!is_array($data = $this->oSphinx->Query($sTerms, Config::Get('module.search.entity_prefix') . $sObjType . 'Index'))) { return FALSE; // Скорее всего недоступен демон searchd } /** * Если результатов нет, то и в кеш писать не стоит... * хотя тут момент спорный */ if ($data['total'] > 0) { $this->Cache_Set($data, $cacheKey, array(), 60 * 15); } } return $data; }
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; }
function get() { $this->total_count = 0; $result = $this->sphinx->Query($this->search_string, $this->index_name); if ($result['status'] !== SEARCHD_OK) { throw new Exception(sprintf('Searching index "%s" for "%s" failed with error "%s".', $this->index_name, $this->search_string, $this->getErrorMessage())); } // Get total count of existing results. $this->total_count = (int) $result['total_found']; // Get time taken for search. $this->time = $result['time']; $data = []; if ($result['total'] > 0 && isset($result['matches'])) { $data['time'] = $result['time']; $data['total'] = $result['total_found']; $i = 0; foreach ($result['matches'] as $k => $v) { $data['data'][$i++] = $v['attrs']; } } unset($result); return $data; }
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; }
public function __construct($rowsPerPage, $currentPage, $siteID, $wildCardString, $sortBy, $sortDirection) { $this->_db = DatabaseConnection::getInstance(); $this->_siteID = $siteID; $this->_sortByFields = array('firstName', 'lastName', 'city', 'state', 'dateModifiedSort', 'dateCreatedSort', 'ownerSort'); if (ENABLE_SPHINX) { /* Sphinx API likes to throw PHP errors *AND* use it's own error * handling. */ assert_options(ASSERT_WARNING, 0); $sphinx = new SphinxClient(); $sphinx->SetServer(SPHINX_HOST, SPHINX_PORT); $sphinx->SetWeights(array(0, 100, 0, 0, 50)); $sphinx->SetMatchMode(SPH_MATCH_EXTENDED); $sphinx->SetLimits(0, 1000); $sphinx->SetSortMode(SPH_SORT_TIME_SEGMENTS, 'date_added'); // FIXME: This can be sped up a bit by actually grouping ranges of // site IDs into their own index's. Maybe every 500 or so at // least on the Hosted system. $sphinx->SetFilter('site_id', array($this->_siteID)); /* Create the Sphinx query string. */ $wildCardString = DatabaseSearch::humanToSphinxBoolean($wildCardString); /* 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($wildCardString, SPHINX_INDEX); $errorMessage = $sphinx->GetLastError(); } while ($results === false && strpos($errorMessage, 'server maxed out, retry') !== false && $tries <= 5); /* Throw a fatal error if Sphinx errors occurred. */ if ($results === false) { $this->fatal('Sphinx Error: ' . ucfirst($errorMessage) . '.'); } /* Throw a fatal error (for now) if Sphinx warnings occurred. */ $lastWarning = $sphinx->GetLastWarning(); if (!empty($lastWarning)) { // FIXME: Just display a warning, and notify dev team. $this->fatal('Sphinx Warning: ' . ucfirst($lastWarning) . '.'); } /* Show warnings for assert()s again. */ assert_options(ASSERT_WARNING, 1); if (empty($results['matches'])) { $this->_WHERE = '0'; } else { $attachmentIDs = implode(',', array_keys($results['matches'])); $this->_WHERE = 'attachment.attachment_id IN(' . $attachmentIDs . ')'; } } else { $this->_WHERE = DatabaseSearch::makeBooleanSQLWhere(DatabaseSearch::fulltextEncode($wildCardString), $this->_db, 'attachment.text'); } /* How many companies do we have? */ $sql = sprintf("SELECT\n COUNT(*) AS count\n FROM\n attachment\n LEFT JOIN candidate\n ON attachment.data_item_id = candidate.candidate_id\n AND attachment.data_item_type = %s\n AND attachment.site_id = candidate.site_id\n LEFT JOIN user AS owner_user\n ON candidate.owner = owner_user.user_id\n WHERE\n resume = 1\n AND\n %s\n AND\n (ISNULL(candidate.is_admin_hidden) OR (candidate.is_admin_hidden = 0))\n AND\n (ISNULL(candidate.is_active) OR (candidate.is_active = 1))\n AND\n attachment.site_id = %s", DATA_ITEM_CANDIDATE, $this->_WHERE, $this->_siteID); $rs = $this->_db->getAssoc($sql); /* Pass "Search By Resume"-specific parameters to Pager constructor. */ parent::__construct($rs['count'], $rowsPerPage, $currentPage); }
/** * 全文搜索 * */ private function full_search($search_txt) { $conf = C('fullindexer'); uk86_import('libraries.sphinx'); $cl = new SphinxClient(); $cl->SetServer($conf['host'], $conf['port']); $cl->SetConnectTimeout(1); $cl->SetArrayResult(true); $cl->SetRankingMode($conf['rankingmode'] ? $conf['rankingmode'] : 0); $cl->setLimits(0, $conf['querylimit']); $matchmode = $conf['matchmode']; $cl->setMatchMode($matchmode); //可以使用全文搜索进行状态筛选及排序,但需要经常重新生成索引,否则结果不太准,所以暂不使用。使用数据库,速度会慢些 // $cl->SetFilter('store_state',array(1),false); // if ($_GET['key'] == 'store_credit'){ // $order = $_GET['order'] == 'desc' ? SPH_SORT_ATTR_DESC : SPH_SORT_ATTR_ASC; // $cl->SetSortMode($order,'store_sort'); // } $res = $cl->Query($search_txt, $conf['index_shop']); if ($res) { if (is_array($res['matches'])) { foreach ($res['matches'] as $value) { $matchs_id[] = $value['id']; } } } if ($search_txt != '') { $condition['store.store_id'] = array('in', $matchs_id); } return $condition; }
<?php require "sphinxapi.php"; $cl = new SphinxClient(); $cl->SetServer('127.0.0.1', 9312); $cl->SetConnectTimeout(1); $cl->SetArrayResult(true); // $cl->SetWeights ( array ( 100, 1 ) ); $cl->SetMatchMode(SPH_MATCH_EXTENDED2); $cl->SetRankingMode(SPH_RANK_WORDCOUNT); // $cl->SetSortMode ( SPH_SORT_EXTENDED, '@weight DESC' ); // $cl->SetSortMode ( SPH_SORT_EXPR, $sortexpr ); // $cl->SetFieldWeights(array('title'=>10,'content'=>1)); $res = $cl->Query('sphinxse', "*"); print_r($res['matches']);
/** * Edit settings related to the sphinx or sphinxQL search function. * * - Called by ?action=admin;area=managesearch;sa=sphinx. * - Checks if connection to search daemon is possible */ public function action_managesphinx() { global $txt, $context, $modSettings; // Saving the settings if (isset($_POST['save'])) { checkSession(); validateToken('admin-mssphinx'); updateSettings(array('sphinx_data_path' => rtrim($_POST['sphinx_data_path'], '/'), 'sphinx_log_path' => rtrim($_POST['sphinx_log_path'], '/'), 'sphinx_stopword_path' => $_POST['sphinx_stopword_path'], 'sphinx_indexer_mem' => (int) $_POST['sphinx_indexer_mem'], 'sphinx_searchd_server' => $_POST['sphinx_searchd_server'], 'sphinx_searchd_port' => (int) $_POST['sphinx_searchd_port'], 'sphinxql_searchd_port' => (int) $_POST['sphinxql_searchd_port'], 'sphinx_max_results' => (int) $_POST['sphinx_max_results'])); } elseif (isset($_POST['checkconnect'])) { checkSession(); validateToken('admin-mssphinx'); // If they have not picked sphinx yet, let them know, but we can still check connections if (empty($modSettings['search_index']) || $modSettings['search_index'] !== 'sphinx' && $modSettings['search_index'] !== 'sphinxql') { $context['settings_message'][] = $txt['sphinx_test_not_selected']; $context['error_type'] = 'notice'; } // Try to connect via Sphinx API? if (!empty($modSettings['search_index']) && ($modSettings['search_index'] === 'sphinx' || empty($modSettings['search_index']))) { if (@file_exists(SOURCEDIR . '/sphinxapi.php')) { include_once SOURCEDIR . '/sphinxapi.php'; $mySphinx = new SphinxClient(); $mySphinx->SetServer($modSettings['sphinx_searchd_server'], (int) $modSettings['sphinx_searchd_port']); $mySphinx->SetLimits(0, (int) $modSettings['sphinx_max_results']); $mySphinx->SetMatchMode(SPH_MATCH_BOOLEAN); $mySphinx->SetSortMode(SPH_SORT_ATTR_ASC, 'id_topic'); $request = $mySphinx->Query('test', 'elkarte_index'); if ($request === false) { $context['settings_message'][] = $txt['sphinx_test_connect_failed']; $context['error_type'] = 'serious'; } else { $context['settings_message'][] = $txt['sphinx_test_passed']; } } else { $context['settings_message'][] = $txt['sphinx_test_api_missing']; $context['error_type'] = 'serious'; } } // Try to connect via SphinxQL if (!empty($modSettings['search_index']) && ($modSettings['search_index'] === 'sphinxql' || empty($modSettings['search_index']))) { if (!empty($modSettings['sphinx_searchd_server']) && !empty($modSettings['sphinxql_searchd_port'])) { $result = @mysqli_connect($modSettings['sphinx_searchd_server'] === 'localhost' ? '127.0.0.1' : $modSettings['sphinx_searchd_server'], '', '', '', (int) $modSettings['sphinxql_searchd_port']); if ($result === false) { $context['settings_message'][] = $txt['sphinxql_test_connect_failed']; $context['error_type'] = 'serious'; } else { $context['settings_message'][] = $txt['sphinxql_test_passed']; } } else { $context['settings_message'][] = $txt['sphinxql_test_connect_failed']; $context['error_type'] = 'serious'; } } } elseif (isset($_POST['createconfig'])) { checkSession(); validateToken('admin-mssphinx'); require_once SUBSDIR . '/ManageSearch.subs.php'; createSphinxConfig(); } // Setup for the template $context['page_title'] = $txt['search_sphinx']; $context['page_description'] = $txt['sphinx_description']; $context['sub_template'] = 'manage_sphinx'; createToken('admin-mssphinx'); }
function sphinx_search($query, $offset = 0, $limit = 30) { require_once 'lib/sphinxapi.php'; $sphinxClient = new SphinxClient(); $sphinxClient->SetServer('localhost', 9312); $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($query, 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); } } return $ids; }
/** * Performs a search on keywords depending on display specific params. You have to run split_keywords() first * * @param string $type contains either posts or topics depending on what should be searched for * @param string $fields contains either titleonly (topic titles should be searched), msgonly (only message bodies should be searched), firstpost (only subject and body of the first post should be searched) or all (all post bodies and subjects should be searched) * @param string $terms is either 'all' (use query as entered, words without prefix should default to "have to be in field") or 'any' (ignore search query parts and just return all posts that contain any of the specified words) * @param array $sort_by_sql contains SQL code for the ORDER BY part of a query * @param string $sort_key is the key of $sort_by_sql for the selected sorting * @param string $sort_dir is either a or d representing ASC and DESC * @param string $sort_days specifies the maximum amount of days a post may be old * @param array $ex_fid_ary specifies an array of forum ids which should not be searched * @param string $post_visibility specifies which types of posts the user can view in which forums * @param int $topic_id is set to 0 or a topic id, if it is not 0 then only posts in this topic should be searched * @param array $author_ary an array of author ids if the author should be ignored during the search the array is empty * @param string $author_name specifies the author match, when ANONYMOUS is also a search-match * @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered * @param int $start indicates the first index of the page * @param int $per_page number of ids each page is supposed to contain * @return boolean|int total number of results */ public function keyword_search($type, $fields, $terms, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, &$start, $per_page) { // No keywords? No posts. if (!strlen($this->search_query) && !sizeof($author_ary)) { return false; } $id_ary = array(); $join_topic = $type != 'posts'; // Sorting if ($type == 'topics') { switch ($sort_key) { case 'a': $this->sphinx->SetGroupBy('topic_id', SPH_GROUPBY_ATTR, 'poster_id ' . ($sort_dir == 'a' ? 'ASC' : 'DESC')); break; case 'f': $this->sphinx->SetGroupBy('topic_id', SPH_GROUPBY_ATTR, 'forum_id ' . ($sort_dir == 'a' ? 'ASC' : 'DESC')); break; case 'i': case 's': $this->sphinx->SetGroupBy('topic_id', SPH_GROUPBY_ATTR, 'post_subject ' . ($sort_dir == 'a' ? 'ASC' : 'DESC')); break; case 't': default: $this->sphinx->SetGroupBy('topic_id', SPH_GROUPBY_ATTR, 'topic_last_post_time ' . ($sort_dir == 'a' ? 'ASC' : 'DESC')); break; } } else { switch ($sort_key) { case 'a': $this->sphinx->SetSortMode($sort_dir == 'a' ? SPH_SORT_ATTR_ASC : SPH_SORT_ATTR_DESC, 'poster_id'); break; case 'f': $this->sphinx->SetSortMode($sort_dir == 'a' ? SPH_SORT_ATTR_ASC : SPH_SORT_ATTR_DESC, 'forum_id'); break; case 'i': case 's': $this->sphinx->SetSortMode($sort_dir == 'a' ? SPH_SORT_ATTR_ASC : SPH_SORT_ATTR_DESC, 'post_subject'); break; case 't': default: $this->sphinx->SetSortMode($sort_dir == 'a' ? SPH_SORT_ATTR_ASC : SPH_SORT_ATTR_DESC, 'post_time'); break; } } // Most narrow filters first if ($topic_id) { $this->sphinx->SetFilter('topic_id', array($topic_id)); } $search_query_prefix = ''; switch ($fields) { case 'titleonly': // Only search the title if ($terms == 'all') { $search_query_prefix = '@title '; } // Weight for the title $this->sphinx->SetFieldWeights(array("title" => 5, "data" => 1)); // 1 is first_post, 0 is not first post $this->sphinx->SetFilter('topic_first_post', array(1)); break; case 'msgonly': // Only search the body if ($terms == 'all') { $search_query_prefix = '@data '; } // Weight for the body $this->sphinx->SetFieldWeights(array("title" => 1, "data" => 5)); break; case 'firstpost': // More relative weight for the title, also search the body $this->sphinx->SetFieldWeights(array("title" => 5, "data" => 1)); // 1 is first_post, 0 is not first post $this->sphinx->SetFilter('topic_first_post', array(1)); break; default: // More relative weight for the title, also search the body $this->sphinx->SetFieldWeights(array("title" => 5, "data" => 1)); break; } if (sizeof($author_ary)) { $this->sphinx->SetFilter('poster_id', $author_ary); } // As this is not simply possible at the moment, we limit the result to approved posts. // This will make it impossible for moderators to search unapproved and softdeleted posts, // but at least it will also cause the same for normal users. $this->sphinx->SetFilter('post_visibility', array(ITEM_APPROVED)); if (sizeof($ex_fid_ary)) { // All forums that a user is allowed to access $fid_ary = array_unique(array_intersect(array_keys($this->auth->acl_getf('f_read', true)), array_keys($this->auth->acl_getf('f_search', true)))); // All forums that the user wants to and can search in $search_forums = array_diff($fid_ary, $ex_fid_ary); if (sizeof($search_forums)) { $this->sphinx->SetFilter('forum_id', $search_forums); } } $this->sphinx->SetFilter('deleted', array(0)); $this->sphinx->SetLimits($start, (int) $per_page, SPHINX_MAX_MATCHES); $result = $this->sphinx->Query($search_query_prefix . str_replace('"', '"', $this->search_query), $this->indexes); // Could be connection to localhost:9312 failed (errno=111, // msg=Connection refused) during rotate, retry if so $retries = SPHINX_CONNECT_RETRIES; while (!$result && strpos($this->sphinx->GetLastError(), "errno=111,") !== false && $retries--) { usleep(SPHINX_CONNECT_WAIT_TIME); $result = $this->sphinx->Query($search_query_prefix . str_replace('"', '"', $this->search_query), $this->indexes); } if ($this->sphinx->GetLastError()) { add_log('critical', 'LOG_SPHINX_ERROR', $this->sphinx->GetLastError()); if ($this->auth->acl_get('a_')) { trigger_error($this->user->lang('SPHINX_SEARCH_FAILED', $this->sphinx->GetLastError())); } else { trigger_error($this->user->lang('SPHINX_SEARCH_FAILED_LOG')); } } $result_count = $result['total_found']; if ($result_count && $start >= $result_count) { $start = floor(($result_count - 1) / $per_page) * $per_page; $this->sphinx->SetLimits((int) $start, (int) $per_page, SPHINX_MAX_MATCHES); $result = $this->sphinx->Query($search_query_prefix . str_replace('"', '"', $this->search_query), $this->indexes); // Could be connection to localhost:9312 failed (errno=111, // msg=Connection refused) during rotate, retry if so $retries = SPHINX_CONNECT_RETRIES; while (!$result && strpos($this->sphinx->GetLastError(), "errno=111,") !== false && $retries--) { usleep(SPHINX_CONNECT_WAIT_TIME); $result = $this->sphinx->Query($search_query_prefix . str_replace('"', '"', $this->search_query), $this->indexes); } } $id_ary = array(); if (isset($result['matches'])) { if ($type == 'posts') { $id_ary = array_keys($result['matches']); } else { foreach ($result['matches'] as $key => $value) { $id_ary[] = $value['attrs']['topic_id']; } } } else { return false; } $id_ary = array_slice($id_ary, 0, (int) $per_page); return $result_count; }
$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($q, $index); //////////////// // print me out //////////////// if ($res === false) { print "Query failed: " . $cl->GetLastError() . ".\n"; } else { if ($cl->GetLastWarning()) { print "WARNING: " . $cl->GetLastWarning() . "\n\n"; } print "Query '{$q}' retrieved {$res['total']} of {$res['total_found']} matches in {$res['time']} sec.\n"; print "Query stats:\n"; if (is_array($res["words"])) { foreach ($res["words"] as $word => $info) { print " '{$word}' found {$info['hits']} times in {$info['docs']} documents\n"; }
$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); $errorMessage = $sphinx->GetLastError(); } while ($results === false && strpos($errorMessage, 'server maxed out, retry') !== false && $tries <= 5); /* Throw a fatal error if Sphinx errors occurred. */ if ($results === false) { fwrite($stderr, 'Sphinx Error: ' . ucfirst($errorMessage) . ".\n"); exit(1); } /* Throw a fatal error (for now) if Sphinx warnings occurred. */ $lastWarning = $sphinx->GetLastWarning(); if (!empty($lastWarning)) { fwrite($stderr, 'Sphinx Warning: ' . ucfirst($lastWarning) . ".\n"); exit(1); } fwrite($stdout, "Sphinx appears to be working properly.\n"); exit(0);
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; } }
function getCategory($keywords) { $q = $keywords; $mode = SPH_MATCH_EXTENDED; $item = array(); $comma_separated = ""; //Init config $host = SPHINX_SERVER; $port = SPHINX_PORT; $index = '*'; $ranker = SPH_RANK_PROXIMITY_BM25; $cl = new SphinxClient(); $cl->SetServer($host, $port); $cl->SetConnectTimeout(1); $cl->SetWeights(array(100, 1)); $cl->SetMatchMode($mode); $cl->SetRankingMode($ranker); $cl->SetArrayResult(true); $cl->SetFilter('status', array('1')); $cl->SetGroupBy("level_1_category_id", SPH_GROUPBY_ATTR, "@count DESC"); $res = $cl->Query($q, $index); $arr = array(); if ($res && isset($res["matches"])) { if (is_array($res["matches"])) { foreach ($res["matches"] as $results) { $arr[] = $results["attrs"]; } } } return $arr; }
<?php require_once "sphinxapi-2.0.4.php"; $cl = new SphinxClient(); #$cl->SetServer(’192.168.1.150′, 9312); //注意这里的主机 #$cl->SetMatchMode(SPH_MATCH_EXTENDED); //使用多字段模式 $cl->SetLimits(0, 1); $query_string = "詩婷"; $result = $cl->Query($query_string); $total = intval($result['total_found']); echo $total; $cl->SetLimits(0, $total); $result = $cl->Query($query_string); #$err = $cl->GetLastError(); var_dump($result); #var_dump($err);
default: ShowError('ಥ_ಥ,出错啦!!!', 'javascript:closeWindow()', '关闭'); } $sp = new SphinxClient(); $sp->SetServer('10.211.55.14', 9312); //设置spinx的服务器地址和端口 $sp->SetArrayResult(true); //设置 显示结果集方式 $sp->SetLimits(0, 1000); //同sql语句中的LIMIT $sp->SetSortMode(SPH_SORT_RELEVANCE); //设置默认按照相关性排序 $sp->SetMatchMode($mod); if ($keyToSearch != " ") { // 如果关键字为空 不执行 否则程序出错 $result = $sp->Query($keyToSearch, "*"); } //执行搜索 $count = $result['total']; //计算一共多少页 // $pn=(ceil($count / 10)); if (is_array($result['matches'])) { $sql_id = array(); foreach ($result['matches'] as $k => $v) { $sql_id[$i] = $v["id"]; $i++; } $sql_query = array(); foreach ($sql_id as $id) { $sql = "select * from shegongku where id =" . $id; $sql_query[$i] = $sql;
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}条信息 {pageindex}/{pagecount} {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(); } }
<?php header('Content-Type: text/html;charset="UTF-8"'); if ($_GET) { // 关键词 $keyword = urldecode(trim(strip_tags($_GET['keyword']))); if ($keyword) { require "sphinxapi.php"; $cl = new SphinxClient(); $cl->SetServer('127.0.0.1', 9312); $cl->SetConnectTimeout(3); $cl->SetArrayResult(true); $cl->SetMatchMode(SPH_MATCH_ANY); $res = $cl->Query($keyword, "*"); echo '<pre>'; print_r($res); } } else { echo '<form method="get"><input type="type" name="keyword"><input type="submit" value="商品搜索"></form>'; }
<?php require "sphinxapi.php"; $cl = new SphinxClient(); $cl->SetRankingMode(SPH_RANK_PROXIMITY); $cl->Query('query');
/** * Finds companies ids by name filter * * @param string $name * @return array */ protected function getIdsByFilter($nameFilter) { $appConfig = $this->app['config']; $sphinxConfig = $appConfig['sphinx.options']; $sphinx = new \SphinxClient(); $sphinx->SetServer($sphinxConfig['host'], $sphinxConfig['port']); $sphinx->SetMatchMode(SPH_MATCH_ANY); $result = $sphinx->Query("*{$nameFilter}*", $sphinxConfig['index.company']); $companyIds = array(); if ($result === false) { return $companyIds; } if (!empty($result["matches"])) { foreach ($result["matches"] as $docId => $docInfo) { $companyIds[] = $docId; } } return $companyIds; }