ModuleSphinx
Package | modules.sphinx |
---|---|
Inheritance | class ModuleSphinx » Module » LsObject |
Since | 1.0 |
Source Code | /classes/modules/sphinx/Sphinx.class.php |
Модуль для работы с машиной полнотекстового поиска Sphinx
Protected Properties
Property | Type | Description | Defined By |
---|---|---|---|
bIsInit | bool | Указывает на то, была ли проведенна инициализация модуля | Module |
oEngine | Engine | Объект ядра | Module |
oSphinx | SphinxClient|null | Объект сфинкса | ModuleSphinx |
Public Methods
Method | Description | Defined By |
---|---|---|
FindContent() | Непосредственно сам поиск | ModuleSphinx |
GetLastError() | Получить ошибку при последнем обращении к поиску | ModuleSphinx |
GetNumResultsByType() | Возвращает число найденых элементов в зависимоти от их типа | ModuleSphinx |
GetSnippet() | Получаем сниппеты(превью найденых элементов) | ModuleSphinx |
Init() | Инициализация | ModuleSphinx |
SetInit() | Помечает модуль как инициализированный | Module |
Shutdown() | Метод срабатывает при завершении работы ядра | Module |
__call() | Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля | Module |
__construct() | При создании модуля передаем объект ядра | Module |
isInit() | Возвращает значение флага инициализации модуля | Module |
Protected Methods
Method | Description | Defined By |
---|---|---|
InitSphinx() | Инициализация сфинкса | ModuleSphinx |
__clone() | Блокируем копирование/клонирование объекта | Module |
Property Details
oSphinx
property
protected SphinxClient|null $oSphinx;
Объект сфинкса
Method Details
FindContent()
method
public array FindContent(string $sTerms, string $sObjType, int $iOffset, int $iLimit, array $aExtraFilters)
| ||
$sTerms | string | Поисковый запрос |
$sObjType | string | Тип поиска |
$iOffset | int | Сдвиг элементов |
$iLimit | int | Количество элементов |
$aExtraFilters | array | Список фильтров |
{return} | array |
Source Code: /classes/modules/sphinx/Sphinx.class.php#61 (show)
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;
}
Непосредственно сам поиск
GetLastError()
method
public string GetLastError()
| ||
{return} | string |
Source Code: /classes/modules/sphinx/Sphinx.class.php#106 (show)
public function GetLastError(){
return $this->oSphinx->GetLastError();
}
Получить ошибку при последнем обращении к поиску
GetNumResultsByType()
method
public int GetNumResultsByType(string $sTerms, string $sObjType, array $aExtraFilters)
| ||
$sTerms | string | Поисковый запрос |
$sObjType | string | Тип поиска |
$aExtraFilters | array | Список фильтров |
{return} | int |
Source Code: /classes/modules/sphinx/Sphinx.class.php#47 (show)
public function GetNumResultsByType($sTerms, $sObjType = 'topics', $aExtraFilters){
$aResults = $this->FindContent($sTerms, $sObjType, 1, 1, $aExtraFilters);
return $aResults['total_found'];
}
Возвращает число найденых элементов в зависимоти от их типа
GetSnippet()
method
public array GetSnippet(string $sText, string $sIndex, string $sTerms, string $before_match, string $after_match)
| ||
$sText | string | Текст |
$sIndex | string | Название индекса |
$sTerms | string | Поисковый запрос |
$before_match | string | Добавляемый текст перед ключом |
$after_match | string | Добавляемый текст после ключа |
{return} | array |
Source Code: /classes/modules/sphinx/Sphinx.class.php#119 (show)
public function GetSnippet($sText, $sIndex, $sTerms, $before_match, $after_match){
$aReturn = $this->oSphinx->BuildExcerpts(array($sText), Config::Get('module.search.entity_prefix').$sIndex.'Index', $sTerms, array(
'before_match' => $before_match,
'after_match' => $after_match,
)
);
return $aReturn[0];
}
Получаем сниппеты(превью найденых элементов)
Init()
method
public void Init()
|
Source Code: /classes/modules/sphinx/Sphinx.class.php#22 (show)
public function Init() {
$this->InitSphinx();
}
Инициализация
InitSphinx()
method
protected void InitSphinx()
|
Source Code: /classes/modules/sphinx/Sphinx.class.php#28 (show)
protected function InitSphinx() {
/**
* Получаем объект Сфинкса(из Сфинкс АПИ)
*/
$this->oSphinx = new SphinxClient();
$this->oSphinx->SetServer(Config::Get('module.search.sphinx.host'), intval(Config::Get('module.search.sphinx.port')));
/**
* Устанавливаем тип сортировки
*/
$this->oSphinx->SetSortMode(SPH_SORT_EXTENDED, "@weight DESC, @id DESc");
}
Инициализация сфинкса