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; }
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; }
while ($member = DB::fetch($query)) { $uids[] = $member['uid']; } if (count($uids) == 0) { $uids = array(0); } } elseif ($srchuid) { $uids = array($srchuid); } if (is_array($uids) && count($uids) > 0) { $s->setFilter('authorid', $uids, false); } if ($srchtxt) { if (preg_match("/\".*\"/", $srchtxt)) { $spx_matchmode = "PHRASE"; $s->setMatchMode(SPH_MATCH_PHRASE); } elseif (preg_match("(AND|\\+|&|\\s)", $srchtxt) && !preg_match("(OR|\\|)", $srchtxt)) { $srchtxt = preg_replace("/( AND |&| )/is", "+", $srchtxt); $spx_matchmode = "ALL"; $s->setMatchMode(SPH_MATCH_ALL); } else { $srchtxt = preg_replace("/( OR |\\|)/is", "+", $srchtxt); $spx_matchmode = 'ANY'; $s->setMatchMode(SPH_MATCH_ANY); } $srchtxt = str_replace('*', '%', addcslashes($srchtxt, '%_')); foreach (explode('+', $srchtxt) as $text) { $text = trim($text); if ($text) { $sqltxtsrch .= $andor; $sqltxtsrch .= $srchtype == 'fulltext' ? "(p.message LIKE '%" . str_replace('_', '\\_', $text) . "%' OR p.subject LIKE '%{$text}%')" : "t.subject LIKE '%{$text}%'";
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); }
public function search(Request $request) { //$keyword = '服务器'; //$keywords = $requests->get('keywords'); //$requests = $request; //return $requests->get('keywords')->toString(); $keyword = $request->get('keywords'); //$keyword = $keywords ? addslashes($keywords) : addslashes($_REQUEST['keywords']); //header("content-type:text/html;charset=utf-8"); // include('/home/tmp/tool/coreseek-3.2.14/csft-3.2.14/api/sphinxapi.php'); $s = new \SphinxClient(); $s->setServer("localhost", 9312); $s->setArrayResult(true); // $s->setSelect(); $s->setMatchMode(SPH_MATCH_ALL); $result = $searchList = array(); if ($keyword) { $result = $s->query($keyword, 'test1'); // 获取检索到的文章id $idArr = array(); $data = $titleArr = array(); if (isset($result['matches']) && is_array($result['matches'])) { foreach ($result['matches'] as $k => $v) { $idArr[] = $v['attrs']['article_id']; } $idStr = implode(',', $idArr); // 查找文章 $data['articles'] = \DB::table('blog_articles')->whereRaw('id in (' . $idStr . ')')->get(); $contentArr = \DB::table('blog_content')->whereRaw('article_id in (' . $idStr . ')')->get(); if ($contentArr) { $newContentArr = array(); foreach ($contentArr as $k => $v) { $newContentArr[$v->article_id] = $v->content; } $contentArr = $newContentArr; unset($newContentArr); } if ($data['articles']) { foreach ($data['articles'] as $k => $v) { $searchList[$k]['id'] = $v->id; $searchList[$k]['title'] = $v->title; $searchList[$k]['content'] = $contentArr[$v->id]; } } //var_dump($searchList);exit(); return view('articles.search', compact('searchList')); } } else { $searchList[0]['message'] = '请输入要查询的关键词~'; return; } return view('articles.search', compact('searchList')); //var_dump(rand(1000,9999)); //return ''; }
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; }
/** * Method to fetch all Sphinx results for a certain search phrase * * @param string $text The search phrase * @param string $phrase String how to match the phrase * @param string $ordering String describing the ordering * * @return array */ protected function getSphinxResults($text, $phrase = '', $ordering = '') { $host = $this->params->get('host', 'localhost'); $port = $this->params->get('port', 9312); $index = $this->params->get('index'); switch ($phrase) { case 'exact': $matchMode = SPH_MATCH_PHRASE; break; case 'all': $matchMode = SPH_MATCH_ALL; break; case 'any': default: $matchMode = SPH_MATCH_ANY; break; } $s = new SphinxClient(); $s->setServer($host, $port); $s->setMatchMode($matchMode); $s->setLimits(50); $result = $s->query($text, $index); return $result; }
/** * @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; }
/** * 全文搜索 * */ protected function full_search($search_txt, $type) { $conf = C('fullindexer'); $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); $res = $cl->Query($search_txt, $conf[$type]); if ($res) { if (is_array($res['matches'])) { foreach ($res['matches'] as $value) { $matchs_id[] = $value['id']; } } } return is_array($matchs_id) ? implode(',', $matchs_id) : ''; }
<?php phpinfo(); die; $sphinx = new \SphinxClient(); $sphinx->SetServer('10.80.1.114', 9312); $sphinx->SetConnectTimeout(1); $sphinx->SetArrayResult(true); $sphinx->SetRankingMode(SPH_RANK_PROXIMITY_BM25); $sphinx->setLimits(0, 10, 10000); $sphinx->setMatchMode(SPH_MATCH_BOOLEAN); $sphinx->SetSortMode(SPH_SORT_EXTENDED, "sales_volume DESC"); $sphinx->SetFilter('spec_value_id', ['409']); //$sphinx->setIndexWeights(array(100, 1)); if (isset($param['catArray']) && !empty($param['catArray'])) { $sphinx->SetFilter('gc_id', $param['catArray']); } if (isset($param['styleArray']) && !empty($param['styleArray'])) { $sphinx->SetFilter('style_id', $param['styleArray']); } if (isset($param['brandArray']) && !empty($param['brandArray'])) { $sphinx->SetFilter('brand_id', $param['brandArray']); } $sphinx->SetGroupBy('goods_id', SPH_GROUPBY_ATTR, 'sales_volume DESC'); $res = $sphinx->Query('', 'sku_spec'); echo '<pre>'; var_dump($res); die;
/** * 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; }
6、对查询关键字做特殊处理(标红) 7、匹配模式 8、权重排序 9、排除一些影响元素 10、添加新词 11、实时索引 12、删除数据 13、sphinx分页 */ header("content-type:text/html;charset=utf-8"); include './sphinxapi.php'; $key = $_GET['keyword']; $sp = new SphinxClient(); $sp->setServer('localhost', 9312); //改变关键字匹配模式 SPH_MATCH_EXTENDED2支持权重排序 $sp->setMatchMode(SPH_MATCH_EXTENDED2); //改变搜索排序模式 sphinx自带id weight 前面加@ 和表关联的字段不用加,优先级前后关系 $sp->setSortMode(SPH_SORT_EXTENDED, 'weight desc @weight desc'); //筛选指定字段的指定值保留,其他不显示 $sp->setFilter('status', array(1)); //分页 $sp->setLimits(4, 4); //搜索根据相关索引 $result = $sp->query($key, 'ind_post ind_post_new'); echo "<pre>"; print_r($result['matches']); $ids = implode(",", array_keys($result['matches'])); mysql_connect("localhost", "root", "123"); mysql_select_db("test"); mysql_set_charset("utf8"); echo $sql = "select * from post where id in (" . $ids . ") order by field(id," . $ids . ")";
/* Codeine * @author bergstein@trickyplan.com * @description Sphinx Driver * @package Codeine * @version 8.x */ setFn('Query', function ($Call) { $Data = null; // Собственно поиск $Sphinx = new SphinxClient(); if ($Sphinx->setServer($Call['Server'], $Call['Port'])) { // ищем хотя бы 1 слово из поисковой фразы // FIXME Добавить опций $Sphinx->setLimits($Call['Limits']['From'], $Call['Limits']['To'], $Call['Limits']['To']); if ($Sphinx->setMatchMode(SPH_MATCH_ANY)) { // поисковый запрос if ($Result = $Sphinx->query($Call['Query'], strtolower($Call['Entity']))) { if ($Result['total'] > 0) { $Data = []; foreach ($Result['matches'] as $ID => $Match) { $Data[$ID] = $Match['weight']; } } } else { $Call = F::Hook('Sphinx.FailedQuery', $Call); } } else { $Call = F::Hook('Sphinx.FailedMode', $Call); } } else {
/** * Отправляет подготовленный запрос на сфинкс, и преобразует ответ в нужный вид. * * @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; }
/** * 全文搜索 * */ 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; }
$T = new Blitz(); $T->load(file_get_contents('tpl/index.tpl')); $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']));
/** * Set the desired match mode. * * @param int $mode The matching mode to be used. */ public function setMatchMode($mode) { $this->sphinx->setMatchMode($mode); }
/** * @brief reset search criteria to default * @details reset conditions and set default search options */ public function resetCriteria() { if (is_object($this->criteria)) { $this->lastCriteria = clone $this->criteria; } else { $this->lastCriteria = new stdClass(); } $this->criteria = new stdClass(); $this->criteria->query = ''; $this->client->resetFilters(); $this->client->resetGroupBy(); $this->client->setArrayResult(false); $this->client->setMatchMode($this->matchMode); // $this->client->setRankingMode($this->rankMode); $this->client->setSortMode(SPH_SORT_RELEVANCE, '@relevance DESC'); $this->client->setLimits(0, 1000000, 10000); if (!empty($this->fieldWeights)) { $this->client->setFieldWeights($this->fieldWeights); } }