/** * Connect to sphinx */ public function init() { if (!class_exists('SphinxClient', false)) { include_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'SphinxClient.php'; } $this->_client = new SphinxClient(); $this->_client->setServer($this->server, $this->port); $this->_client->setMaxQueryTime($this->maxQueryTime); $this->resetClient(); }
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; }
/** * 获取竞品信息 * @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; }
/** * Отправляет подготовленный запрос на сфинкс, и преобразует ответ в нужный вид. * * @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; }
dheader('Location: search.php?mod=forum'); } elseif (isset($srchfid) && !empty($srchfid) && $srchfid != 'all' && !(is_array($srchfid) && in_array('all', $srchfid)) && empty($forumsarray)) { showmessage('search_forum_invalid', 'search.php?mod=forum'); } elseif (!$fids) { showmessage('group_nopermission', NULL, array('grouptitle' => $_G['group']['grouptitle']), array('login' => 1)); } if ($_G['adminid'] != '1' && $_G['setting']['search']['forum']['maxspm']) { if (DB::result_first("SELECT COUNT(*) FROM " . DB::table('common_searchindex') . " WHERE srchmod='{$srchmod}' AND dateline>'{$_G['timestamp']}'-60") >= $_G['setting']['search']['forum']['maxspm']) { showmessage('search_toomany', 'search.php?mod=forum', array('maxspm' => $_G['setting']['search']['forum']['maxspm'])); } } if ($srchtype == 'fulltext' && $_G['setting']['sphinxon']) { require_once libfile('class/sphinx'); $s = new SphinxClient(); $s->setServer($_G['setting']['sphinxhost'], intval($_G['setting']['sphinxport'])); $s->setMaxQueryTime(intval($_G['setting']['sphinxmaxquerytime'])); $s->SetRankingMode($_G['setting']['sphinxrank']); $s->setLimits(0, intval($_G['setting']['sphinxlimit']), intval($_G['setting']['sphinxlimit'])); $s->setGroupBy('tid', SPH_GROUPBY_ATTR); if ($srchfilter == 'digest') { $s->setFilterRange('digest', 1, 3, false); } if ($srchfilter == 'top') { $s->setFilterRange('displayorder', 1, 2, false); } else { $s->setFilterRange('displayorder', 0, 2, false); } if (!empty($srchfrom) && empty($srchtxt) && empty($srchuid) && empty($srchuname)) { $expiration = TIMESTAMP + $cachelife_time; $keywords = ''; if ($before) {
public function fetch() { if (!class_exists('SphinxClient')) { return false; } $s = new SphinxClient(); $s->setServer($this->_sphinxHost, $this->_sphinxPort); if (count($this->_arrSearchOutRangeColumnMinMax) > 0) { foreach ($this->_arrSearchOutRangeColumnMinMax as $value) { $d = explode(',', $value); $s->setFilterRange($d[0], $d[1], $d[2], true); } } if (count($this->_arrSearchInRangeColumnMinMax) > 0) { foreach ($this->_arrSearchInRangeColumnMinMax as $value) { $d = explode(',', $value); $s->setFilterRange($d[0], $d[1], $d[2], false); } } $s->setConnectTimeout($this->_connectTimeout); $s->setMaxQueryTime($this->{$_maxquerytime}); // $s->setRetries ( int $this->retriesCount , int $this->retriesDelay ); // $s->setMatchMode($this->searchMode); $s->setFieldWeights($this->_fieldweights); // $s->setFilter ( string $attribute , array $values [, bool $exclude = false ] ); // $s->setFilterFloatRange ( string $attribute , float $min , float $max [, bool $exclude = false ] ); // $s->setFilterRange ( string $attribute , int $min , int $max [, bool $exclude = false ] ); // $s->setGeoAnchor ( string $attrlat , string $attrlong , float $latitude , float $longitude ); // $s->setGroupBy ( string $attribute , int $func [, string $groupsort = "@group desc" ] ); // $s->setGroupDistinct ( string $attribute ); // $s->setIDRange ( int $min , int $max ); $s->setIndexWeights($this->_arrIndexweights); // $s->setLimits ( int $offset , int $limit [, int $max_matches = 0 [, int $cutoff = 0 ]] ); $s->setMatchMode($this->searchMode); // $s->setOverride ( string $attribute , int $type , array $values ); $s->setRankingMode($this->rankMode); // $s->setSelect ( string $clause ); // $s->setSortMode ( int $mode [, string $sortby ] ); return $s->query($this->_query); }
if (!empty($res)) { foreach ($res as $k => $r) { if ($r['price_mopt'] != 0) { $prices[$k] = number_format($r['price_mopt'], 0, ".", ""); } } } // Поиск Sphinx ============================================ } elseif ($GLOBALS['CONFIG']['search_engine'] == 'sphinx') { // Инициализация соединения со Sphinx $sphinx = new SphinxClient(); // $sphinx->SetServer("localhost", 9312); $sphinx->SetServer('31.131.16.159', 9312); $sphinx->SetConnectTimeout(1); $sphinx->SetArrayResult(true); $sphinx->setMaxQueryTime(100); $sphinx->setLimits(0, 10000); $sphinx->SetSortMode(SPH_SORT_RELEVANCE); $sphinx->SetRankingMode(SPH_RANK_PROXIMITY_BM25); // разбор строки запроса if (ctype_digit($query)) { $result = $sphinx->Query($query, 'art' . $GLOBALS['CONFIG']['search_index_prefix']); } else { $words = explode(' ', $query); $i = 0; foreach ($words as &$w) { if (strlen($w) > 2) { $sphinx->SetMatchMode(SPH_MATCH_ALL); $result = $sphinx->Query('( ' . $w . ' | ' . $w . '* | *' . $w . '* | *' . $w . ' ) ', 'name' . $GLOBALS['CONFIG']['search_index_prefix']); if ($result['total'] == 0) { $w = Transliterate($w);
private static function getSphinx() { // {{{ $sphinx = new SphinxClient(); $sphinx->setServer("localhost", 9312); $sphinx->setMatchMode(SphinxClient::SPH_MATCH_PHRASE); $sphinx->setLimits(0, 1000); $sphinx->setMaxQueryTime(30); return $sphinx; }
public function init() { parent::init(); include_once dirname(__FILE__) . '/models/DGSphinxSearchResult.php'; $this->client = new SphinxClient(); $this->client->setServer($this->server, $this->port); $this->client->setMaxQueryTime($this->maxQueryTime); Yii::trace("weigth: " . print_r($this->fieldWeights, true), 'CEXT.DGSphinxSearch.doSearch'); $this->resetCriteria(); }
<?if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){ header('Content-Type: text/javascript; charset=utf-8'); $Product = new Products(); if(isset($_POST['action'])) switch($_POST['action']){ case "search": // Асинхронный поиск по сайту if(isset($_POST['query']) && $_POST['query'] != ''){ $query = trim($_POST['query']); // Инициализация соединения со Sphinx $sphinx = new SphinxClient(); // $sphinx->SetServer("localhost", 9312); $sphinx->SetServer('81.17.140.234', 9312); $sphinx->SetConnectTimeout(1); $sphinx->SetArrayResult(true); $sphinx->setMaxQueryTime(3); $sphinx->setLimits(0, 5000); $sphinx->SetSortMode(SPH_SORT_RELEVANCE); // разбор строки запроса if(ctype_digit($query)){ $result = $sphinx->Query($query, 'art'.$GLOBALS['CONFIG']['search_index_prefix']); }else{ $query = preg_replace('/[()*|,.*^"&@#$%]/', ' ', $query); $words = explode(' ', $query); $sphinx->SetMatchMode(SPH_MATCH_BOOLEAN); $sphinx->SetRankingMode(SPH_RANK_BM25); $wo = ''; foreach($words as $k=>$word){ if(strlen($word) > 2){ if($k == 0){ $wo .= '( '.$word.' | '.$word.'* | *'.$word.'* | *'.$word.' )';
public function init() { parent::init(); $this->client = new SphinxClient(); $this->client->setServer($this->server, $this->port); $this->client->setMaxQueryTime($this->maxQueryTime); Yii::trace("weigth: " . print_r($this->fieldWeights, true), 'CEXT.ESphinxSearch.doSearch'); $this->resetCriteria(); }
$tpl_values = array(); $tpl_values['page'] = $page; if ($query || $extsearch) { $tpl_values['query'] = htmlspecialchars($query); $tpl_values['extsearch'] = $extsearch; $tpl_values['nodirs'] = $nodirs; $categories = Searcher::getCategories($category, true); $tpl_values['categories'] = $categories; $tpl_values['days'] = $days; $tpl_values['minsize'] = $minsize; if ($query) { $searcher = new SphinxClient(); $searcher->setServer("localhost", 3312); $searcher->setMatchMode(SPH_MATCH_ALL); $searcher->setSortMode(SPH_SORT_RELEVANCE); $searcher->setMaxQueryTime(3000); $min = ($page - 1) * RPP; $max = $min + RPP; //max+1 $out_array = array(); //TTHS $prev_instanses_count = 0; $start = max(0, $min - $prev_instanses_count); $len = min(RPP, max(1, $max - $prev_instanses_count)); $searcher->setLimits($start, $len); $tths_result = $searcher->query($query, "dc_tths dc_tths_delta"); $total_tths = $tths_result['total']; if ($total_tths && is_array($tths_result['matches']) && count($out_array) < RPP) { $tths = Searcher::getTTHs(array_keys($tths_result['matches'])); $out_array = array_merge($out_array, $tths); }
/** * @brief 위치 기반 Sphinx 검색 부분 (외부/내부 호출용..) * @param $document_srl 문서 번호 * @param $lat 위도 * @param $lon 경도 * @return 검색된 결과 리스트 */ function getSphinxSearchedResult($document_srl, $lat, $lon) { $s = new SphinxClient(); $oModuleModel =& getModel('module'); $config = $oModuleModel->getModuleConfig('aroundmap'); $s->setServer($config->serverName, $config->serverPort); $s->setLimits(0, 10); $s->setMatchMode(SPH_MATCH_ALL); $s->SetSortMode(SPH_SORT_EXTENDED, '@geodist ASC'); $s->setFilter("document_srl", array($document_srl), true); $s->SetFilterFloatRange("@geodist", 0, 10000); $s->setMaxQueryTime(3); $s->setGeoAnchor("lat", "lon", (double) deg2rad($lat), (double) deg2rad($lon)); $result = $s->query("", "idx_aroundmap"); $ret = array(); if ($result[total_found] > 0) { $ret = $result[matches]; } return $ret; }
/** * Provides search functionality through Sphinx * @param int $id The pagination $id */ public function actionSearch($id = 1) { $this->setPageTitle(Yii::t('ciims.controllers.Site', '{{app_name}} | {{label}}', array('{{app_name}}' => Cii::getConfig('name', Yii::app()->name), '{{label}}' => Yii::t('ciims.controllers.Site', 'Search')))); $this->layout = '//layouts/default'; $data = array(); $pages = array(); $itemCount = 0; $pageSize = Cii::getConfig('searchPaginationSize', 10); if (Cii::get($_GET, 'q', "") != "") { $criteria = Content::model()->getBaseCriteria(); if (strpos($_GET['q'], 'user_id') !== false) { $criteria->addCondition('author_id = :author_id'); $criteria->params = array(':author_id' => str_replace('user_id:', '', $_GET['q'])); } else { // Load the search data Yii::import('ext.sphinx.SphinxClient'); $sphinx = new SphinxClient(); $sphinx->setServer(Cii::getConfig('sphinxHost'), (int) Cii::getConfig('sphinxPort')); $sphinx->setMatchMode(SPH_MATCH_EXTENDED2); $sphinx->setMaxQueryTime(15); $result = $sphinx->query(Cii::get($_GET, 'q', NULL), Cii::getConfig('sphinxSource')); $criteria->addInCondition('id', array_keys(isset($result['matches']) ? $result['matches'] : array())); } $criteria->addCondition('password = ""'); $criteria->limit = $pageSize; $criteria->order = 'id DESC'; $itemCount = Content::model()->count($criteria); $pages = new CPagination($itemCount); $pages->pageSize = $pageSize; $criteria->offset = $criteria->limit * $pages->getCurrentPage(); $data = Content::model()->findAll($criteria); $pages->applyLimit($criteria); } $this->render('search', array('url' => 'search', 'id' => $id, 'data' => $data, 'itemCount' => $itemCount, 'pages' => $pages)); }
/** * Runs a search against sphinx * * @param array $args * @return array Sphinx result set */ public function search_posts($args) { $options = $this->get_options(); $defaults = array('search_using' => 'any', 'sort' => 'match', 'paged' => 1, 'posts_per_page' => 0, 'showposts' => 0); $args = wp_parse_args($args, $defaults); $sphinx = new SphinxClient(); $sphinx->setServer($options['server'], $options['port']); $search = $args['s']; switch ($args['search_using']) { case 'all': $sphinx->setMatchMode(SPH_MATCH_ALL); break; case 'exact': $sphinx->setMatchMode(SPH_MATCH_PHRASE); break; default: $sphinx->setMatchMode(SPH_MATCH_ANY); } switch ($args['sort']) { case 'date': $sphinx->setSortMode(SPH_SORT_ATTR_DESC, 'date_added'); break; case 'title': $sphinx->setSortMode(SPH_SORT_ATTR_ASC, 'title'); break; default: $sphinx->setSortMode(SPH_SORT_RELEVANCE); } $page = isset($args['paged']) && intval($args['paged']) > 0 ? intval($args['paged']) : 1; $per_page = max(array($args['posts_per_page'], $args['showposts'])); if ($per_page < 1) { $per_page = get_option('posts_per_page'); } $sphinx->setLimits(($page - 1) * $per_page, $per_page); $sphinx->setMaxQueryTime(intval($options['timeout'])); $result = $sphinx->query($search, $options['index']); $this->last_error = $sphinx->getLastError(); $this->last_warning = $sphinx->getLastWarning(); return $result; }