本文整理汇总了PHP中SphinxClient::Query方法的典型用法代码示例。如果您正苦于以下问题:PHP SphinxClient::Query方法的具体用法?PHP SphinxClient::Query怎么用?PHP SphinxClient::Query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SphinxClient
的用法示例。
在下文中一共展示了SphinxClient::Query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: search
/**
* 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);
}
}
示例2: SphinxClient
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());
}
}
示例3: get_sugg_trigrams
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;
}
示例4: search
/**
* 搜索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;
}
示例5: sphinx_add_result_forum
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;
}
示例6: query
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;
}
示例7: query
/**
* 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;
}
示例8: sphinx_add_result_clubs
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;
}
示例9: FindContent
/**
* Непосредственно сам поиск
*
* @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;
}
示例10: MakeSuggestion
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;
}
示例11: FindContent
/**
* Непосредственно сам поиск
*
* @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;
}
示例12: getResultByTag
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;
}
示例13: get
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;
}
示例14: Query
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;
}
示例15: __construct
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);
}