本文整理汇总了PHP中SphinxClient::SetLimits方法的典型用法代码示例。如果您正苦于以下问题:PHP SphinxClient::SetLimits方法的具体用法?PHP SphinxClient::SetLimits怎么用?PHP SphinxClient::SetLimits使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SphinxClient
的用法示例。
在下文中一共展示了SphinxClient::SetLimits方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: setLimit
/**
* 设置limit
* @param int $page 第几页
* @param int $pageSize 每页多少条
*/
public function setLimit($page, $pageSize = PAGE_SIZE)
{
$page = abs(intval($page));
$pageSize = abs(intval($pageSize));
if ($page != 0) {
$page--;
}
$begin = $page * $pageSize;
$this->_sphinx->SetLimits($begin, $pageSize);
}
示例2: __construct
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;
}
示例3: 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());
}
}
示例4: 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;
}
示例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: find_by_keyword
/**
*
* @param string $keyword
* @param boolean $only_title
* @param string $modules
* @param integer $limit
* @param integer $offset
* @return array
*/
public function find_by_keyword($keyword, $only_title = FALSE, $modules = NULL, $limit = 50, $offset = 0)
{
if (Kohana::$profiling === TRUE) {
$benchmark = Profiler::start('Search', __FUNCTION__);
}
$this->_client->SetLimits($offset, $limit);
$data = $this->_client->Query($keyword, $this->_modules_to_string($modules));
$matches = Arr::get($data, 'matches', array());
if (empty($matches)) {
return array();
}
$ids = array();
foreach ($matches as $id => $row) {
$ids[$row['attrs']['module']][$id] = $row['attrs'];
}
if (isset($benchmark)) {
Profiler::stop($benchmark);
}
return $ids;
}
示例7: 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;
}
示例8: 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;
}
示例9: resetClient
protected function resetClient()
{
$this->sphinxClient->ResetFilters();
$this->sphinxClient->ResetGroupBy();
$this->sphinxClient->ResetOverrides();
$this->sphinxClient->SetLimits(0, 20);
$this->sphinxClient->SetArrayResult(true);
$this->sphinxClient->SetFieldWeights(array());
$this->sphinxClient->SetIDRange(0, 0);
$this->sphinxClient->SetIndexWeights(array());
$this->sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2);
$this->sphinxClient->SetRankingMode(SPH_RANK_NONE);
$this->sphinxClient->SetSortMode(SPH_SORT_RELEVANCE, "");
$this->sphinxClient->SetSelect("*");
}
示例10: 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;
}
示例11: 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;
}
示例12: 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;
}
示例13: sphinxSearch
/**
* 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));
}
示例14: 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;
}
示例15: 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}条信息 {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'])) {
//过滤模型
//.........这里部分代码省略.........