/** * * @param string $query * @return array of integers - taskIds */ public static function searchTasks($query) { $fieldWeights = array('description' => 10, 'note' => 6); $indexName = 'plancake_tasks'; $client = new SphinxClient(); // $client->SetServer (sfConfig::get('app_sphinx_host'), sfConfig::get('app_sphinx_port')); $client->SetFilter("author_id", array(PcUserPeer::getLoggedInUser()->getId())); $client->SetConnectTimeout(1); $client->SetMatchMode(SPH_MATCH_ANY); $client->SetSortMode(SPH_SORT_RELEVANCE); $client->SetRankingMode(SPH_RANK_PROXIMITY_BM25); $client->SetArrayResult(true); $client->SetFieldWeights($fieldWeights); $client->setLimits(0, 100); $results = $client->query($client->EscapeString($query), $indexName); if ($results === false) { $error = "Sphinx Error - " . $client->GetLastError(); sfErrorNotifier::alert($error); } $ids = array(); if (isset($results['matches']) && count($results['matches'])) { foreach ($results['matches'] as $match) { $ids[] = $match['id']; } } return PcTaskPeer::retrieveByPKs($ids); }
/** * Search for the specified query string. * * @param string $query The query string that we are searching for. * @param array $indexes The indexes to perform the search on. * @param array $options The options for the query. * @param bool $escapeQuery Should the query string be escaped? * * @return array The results of the search. */ public function search($query, array $indexes, array $options = array(), $escapeQuery = true) { if ($escapeQuery) { $query = $this->sphinx->escapeString($query); } /** * Build the list of indexes to be queried. */ $indexNames = ''; foreach ($indexes as &$label) { if (isset($this->indexes[$label])) { $indexNames .= $this->indexes[$label] . ' '; } } /** * If no valid indexes were specified, return an empty result set. * * FIXME: This should probably throw an exception. */ if (empty($indexNames)) { return array(); } /** * Set the offset and limit for the returned results. */ if (isset($options['result_offset']) && isset($options['result_limit'])) { $this->sphinx->setLimits($options['result_offset'], $options['result_limit']); } /** * Weight the individual fields. */ if (isset($options['field_weights'])) { $this->sphinx->setFieldWeights($options['field_weights']); } /** * Perform the query. */ $start = round(microtime(true) * 1000); $results = $this->sphinx->query($query, $indexNames); if ($results['status'] === SEARCHD_ERROR) { throw new \RuntimeException(sprintf('Searching index "%s" for "%s" failed with error "%s".', $label, $query, $this->sphinx->getLastError())); } if ($results['status'] === SEARCHD_RETRY) { throw new \RuntimeException(sprintf('Searching index "%s" for "%s" failed with retry "%s".', $label, $query, $this->sphinx->getLastError())); } $end = round(microtime(true) * 1000) - $start; $event = new SearchEvent($query, $indexes, $end); $this->dispatcher->dispatch("sphinx.event.search", $event); return $results; }
/** * Search for the specified query string. * * @param string $query The query string that we are searching for. * @param array $indexes The indexes to perform the search on. * * @return array The results of the search. * * $indexes should look like: * * $indexes = array( * 'IndexLabel' => array( * 'result_offset' => (int), // optional unless result_limit is set * 'result_limit' => (int), // optional unless result_offset is set * 'field_weights' => array( // optional * 'FieldName' => (int), * ..., * ), * ), * ..., * ); */ public function search($query, array $indexes, $escapeQuery = true) { if ($escapeQuery) { $query = $this->sphinx->escapeString($query); } $results = array(); foreach ($indexes as $label => $options) { /** * Ensure that the label corresponds to a defined index. */ if (!isset($this->indexes[$label])) { continue; } /** * Set the offset and limit for the returned results. */ if (isset($options['result_offset']) && isset($options['result_limit'])) { $this->sphinx->setLimits($options['result_offset'], $options['result_limit']); } /** * Weight the individual fields. */ if (isset($options['field_weights'])) { $this->sphinx->setFieldWeights($options['field_weights']); } /** * Perform the query. */ $results[$label] = $this->sphinx->query($query, implode(' ', $this->indexes[$label]["index"])); if ($results[$label]['status'] !== SEARCHD_OK) { throw new \RuntimeException(sprintf('Searching index "%s" for "%s" failed with error "%s".', $label, $query, $this->sphinx->getLastError())); } } /** * If only one index was searched, return that index's results directly. */ if (count($indexes) === 1 && count($results) === 1) { $results = reset($results); } /** * FIXME: Throw an exception if $results is empty? */ return $results; }
public function executeSearch(sfWebRequest $request) { $q = $request->getParameter('q'); include '/home/jackbravo/work/sphinx-0.9.9-rc1/api/sphinxapi.php'; $s = new SphinxClient(); $result = $s->query($q); if ($result['total'] > 0) { $query = Doctrine::getTable('Issue')->findIdsQuery(array_keys($result['matches'])); } else { $query = Doctrine::getTable('Issue')->findNullQuery(); } $pager = new sfDoctrinePager('Issue', sfConfig::get('app_max_issues_on_index')); $pager->setQuery($query); $pager->setPage($request->getParameter('page', 1)); $pager->setTableMethod('getListQuery'); $pager->init(); $this->filter = $this->getFilter($request); $this->pager = $pager; $this->from_search = $q; $this->setTemplate('index'); }
/** * Search for the specified query string. * * @param string $query The query string that we are searching for. * @param array $indexes The indexes to perform the search on. * * @return ResultCollection The results of the search. * * $indexes should have the format: * * $indexes = array( * 'IndexLabel' => array( * 'result_offset' => (int), * 'result_limit' => (int) * ), * ..., * ); */ public function search($query, array $indexes) { // $query = $this->sphinx->escapeString($query); $results = array(); foreach ($indexes as $label => $options) { /** * Ensure that the label corresponds to a defined index. */ if (!isset($this->indexes[$label])) { continue; } /** * Set the offset and limit for the returned results. */ if (isset($options['result_offset']) && isset($options['result_limit']) && is_numeric($options['result_offset']) && is_numeric($options['result_limit'])) { $this->sphinx->setLimits($options['result_offset'], $options['result_limit']); } /** * Weight the individual fields. */ if (!empty($this->indexes[$label]['field_weights'])) { $this->sphinx->setFieldWeights($this->indexes[$label]['field_weights']); } /** * Perform the query. */ $results[$label] = $this->sphinx->query($query, implode(' ', $this->indexes[$label]["index"])); if ($this->sphinx->IsConnectError()) { throw new ConnectionException(sprintf('Searching index "%s" for "%s" failed with error "%s".', $label, $query, $this->sphinx->getLastError())); } elseif ($results[$label]['status'] !== SEARCHD_OK) { throw new \RuntimeException(sprintf('Searching index "%s" for "%s" failed with error "%s".', $label, $query, $this->sphinx->getLastError())); } } /** * FIXME: Throw an exception if $results is empty? */ return new ResultCollection($results, $this->mapping, $this->em); }
/** * 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)); }
if (!empty($srchfid) && $srchfid != 'all') { foreach ($srchfid as $forum) { if ($forum = intval(trim($forum))) { $sp_fids[] = $forum; } } !empty($sp_fids) && $cl->setfilter('fid', $sp_fids); } //分页 $sp_page = isset($page) ? abs((int) $page) : 1; $sp_page = max(1, $sp_page); $sp_perpage = 10; $sp_start = ($page - 1) * $sp_perpage; $sp_total_result = 100; $cl->setlimits($sp_start, $sp_perpage); $res = $cl->query($sp_keyword, $sp_index); //* 显示sphinx错误信息,用于调试 if ($cl->GetLastWarning()) { var_dump($res); die("WARNING: " . $cl->GetLastWarning() . "\n\n"); } //*/ if (empty($res['matches'])) { include template('search_threads'); exit; } //分页 $query_string = 'search.php?' . preg_replace('|&page=\\d+|', '', $_SERVER['QUERY_STRING']); $multipage = multi($res['total'], $sp_perpage, $sp_page, $query_string); //从数据获取信息 $sp_res_keys = array_keys($res['matches']);
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 ''; }
/** * 关键词获取普通产品获取相关分类 * @param array $splitKeywords * @return array */ public function getRelaCateCommon($splitKeywords, $cateid = 0, $limit = 20) { $sphinxConfig = $this->di["config"]["prosearchd"]; $sphinx = new \SphinxClient(); $sphinx->SetServer($sphinxConfig['host'], intval($sphinxConfig['port'])); $sphinx->SetSelect("id, cate3"); $sphinx->SetFilter("cate3", array(1270), true); if ($cateid) { $sphinx->SetFilter("cate3", array($cateid), false); } $sphinx->SetFilterRange("id", 1, 900000000, false); $sphinx->SetLimits(0, $limit, $limit); $sphinx->SetGroupBy('cate3', SPH_GROUPBY_ATTR, "@count desc"); $batchResult = $sphinx->query($splitKeywords, "product_distri"); $error = $sphinx->getLastError(); if ($error) { return array(); } $result = $this->fomatSphinxData($batchResult); if (empty($result) || !is_array($result)) { $result = array(); } return $result; }
break; default: $sphinx->SetFilter('nation', array(0)); $sphinx->SetFilter('sex', array(0)); } } if (isset($_REQUEST['words'])) { if (intval($_REQUEST['words']) < 9) { $sphinx->SetFilter('words', array(intval($_REQUEST['words']))); } else { $sphinx->SetFilterRange('words', 9, 100); } } $sphinx->SetSortMode(SPH_SORT_EXTENDED, "count DESC,order ASC"); //索引源是配置文件中的 index 类,如果有多个索引源可使用,号隔开:'email,diary' 或者使用'*'号代表全部索引源 $result = $sphinx->query($key_word, 'singer'); // echo '<pre>'; // print_r($result); // echo '</pre>'; if (!isset($result['matches'])) { include_once '_list.php'; exit; // $finalResult = array( // "artists" => array(), // "page" => 0, // "total" => 0, // "totalNumber" => 0 // ); // formatResult($finalResult); // exit; }
* @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 { $Call = F::Hook('Sphinx.CantConnect', $Call); }
/** * Отправляет подготовленный запрос на сфинкс, и преобразует ответ в нужный вид. * * @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; }
/** * @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; }
$Timer1 = new timer(); //计时器 $Timer1->start(); $sphinx = new SphinxClient(); $sphinx->SetServer("localhost", 9312); if ($irmod == '1') { $sphinx->SetMatchMode(SPH_MATCH_EXTENDED2); } // else if($irmod == '2') // $sphinx->SetMatchMode(SPH_MATCH_PHRASE); #$sphinx->SetSortMode(SPH_SORT_RELEVANCE); // $sphinx->SetSortMode(SPH_SORT_EXTENDED,"@weight DESC");########### $sphinx->SetSortMode(SPH_SORT_EXPR, "hits*0.1+@weight*5"); $sphinx->setLimits(0, 1000, 1000); $sphinx->SetIndexWeights(array("title" => 50, "keywords" => 10, "description" => 5)); $result = $sphinx->query($keyword, "mysql"); echo "<pre>"; // print_r($result); echo "</pre>"; $ids = join(",", array_keys($result['matches'])); $row_num = $result['total']; $Timer1->stop(); if ($row_num <= 0) { echo " <font style='font-weight:bold;color:#f00;'>没有您想要的结果...</font>"; } else { # $Timer2=new timer(); # $Timer2->start();//////////////// $gPageSize = 10; //每页显示记录数 $page = $_GET['page']; //页数
$sphinx = new SphinxClient(); $sphinx->SetServer(SPHINX_HOST, SPHINX_PORT); $sphinx->SetArrayResult(true); $sphinx->SetLimits($pageNum * $number, $number, 5000); $sphinx->SetMaxQueryTime(10); $sphinx->SetMatchMode(SPH_MATCH_EXTENDED2); $sphinx->SetFilter('enabled', array(1)); if (isset($_REQUEST['words'])) { if (intval($_REQUEST['words']) < 9) { $sphinx->SetFilter('words', array(intval($_REQUEST['words']))); } else { $sphinx->SetFilterRange('words', 9, 100); } } $sphinx->SetSortMode(SPH_SORT_EXTENDED, "words ASC, count DESC, head ASC"); $result = $sphinx->query(implode(' | ', $key_word), 'music'); if (!isset($result['matches'])) { include_once '_music.php'; exit; // $finalResult = array( // "songs" => array(), // "page" => 0, // "total" => 0, // "totalNumber" => 0 // ); // formatResult($finalResult); // exit; } $countValue = $result['total']; if ($countValue == 0) { $pageCount = 0;
/** * 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; }
$sphinx = new SphinxClient(); $sphinx->SetServer(SPHINX_HOST, SPHINX_PORT); $sphinx->SetArrayResult(true); $sphinx->SetLimits($pageNum * $number, $number, 5000); $sphinx->SetMaxQueryTime(10); $sphinx->SetMatchMode(SPH_MATCH_EXTENDED2); $sphinx->SetFilter('enabled', array(1)); if (isset($_REQUEST['words'])) { if (intval($_REQUEST['words']) < 9) { $sphinx->SetFilter('words', array(intval($_REQUEST['words']))); } else { $sphinx->SetFilterRange('words', 9, 100); } } $sphinx->SetSortMode(SPH_SORT_EXTENDED, "words ASC, count DESC, head ASC"); $result = $sphinx->query($key_word, 'music'); if (!isset($result['matches'])) { include_once '_list.php'; exit; // $finalResult = array( // "songs" => array(), // "page" => 0, // "total" => 0, // "totalNumber" => 0 // ); // formatResult($finalResult); // exit; } $countValue = $result['total']; if ($countValue == 0) { $pageCount = 0;
/** * 检索关键词是否在库中存在 * @param type $splitKeywords */ public function sphinxKeyword($splitKeywords) { $sphinxKeywords = $this->getSplitWd($splitKeywords); $sphinxConfig = array("host" => "172.17.17.105", "port" => 9020); $sphinx = new \SphinxClient(); $sphinx->SetServer($sphinxConfig['host'], intval($sphinxConfig['port'])); $sphinx->SetSelect("id"); $sphinx->SetLimits(0, 1, 1); $batchResult = $sphinx->query($sphinxKeywords, "product_distri"); if (isset($batchResult["total_found"]) && $batchResult["total_found"] > 0) { return true; } return false; }
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); } if (!$nodirs) { //DIRS if ($days) { $searcher->SetFilterRange("starttime", 0, time() - $days * 24 * 60 * 60, true); //exclude too old results } $prev_instanses_count += $total_tths; $start = max(0, $min - $prev_instanses_count); $len = min(RPP, max(1, $max - $prev_instanses_count)); $searcher->setLimits($start, $len);
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 ($language == "") { echo json_encode(array("result" => null, "status" => false, "error" => "请求的语种不存在")); exit; } $sphinx->SetFilter('language', array($language)); } if (isset($_REQUEST['words'])) { if (intval($_REQUEST['words']) < 9) { $sphinx->SetFilter('words', array(intval($_REQUEST['words']))); } else { $sphinx->SetFilterRange('words', 9, 100); } } $sphinx->SetSortMode(SPH_SORT_EXTENDED, "lang_part ASC, words ASC, header_sort ASC, count DESC"); //索引源是配置文件中的 index 类,如果有多个索引源可使用,号隔开:'email,diary' 或者使用'*'号代表全部索引源 $result = $sphinx->query($key_word, 'media'); // echo '<pre>'; // print_r($result); // echo '</pre>'; if (!isset($result['matches'])) { include_once '_list.php'; exit; // $finalResult = array( // "songs" => array(), // "page" => 0, // "total" => 0, // "totalNumber" => 0 // ); // formatResult($finalResult); // exit; }
$spx_timemix = 0; $spx_timemax = TIMESTAMP - $srchfrom; } else { $spx_timemix = TIMESTAMP - $srchfrom; $spx_timemax = TIMESTAMP; } $s->setFilterRange('lastpost', $spx_timemix, $spx_timemax, false); } if (!empty($specials)) { $s->setFilter('special', explode(",", $special), false); } $keywords = str_replace('%', '+', $srchtxt) . (trim($srchuname) ? '+' . str_replace('%', '+', $srchuname) : ''); $expiration = TIMESTAMP + $cachelife_text; } if ($srchtype == "fulltext") { $result = $s->query("'" . $srchtxt . "'", $_G['setting']['sphinxmsgindex']); } else { $result = $s->query($srchtxt, $_G['setting']['sphinxsubindex']); } $tids = array(); if ($result) { if (is_array($result['matches'])) { foreach ($result['matches'] as $value) { if ($value['attrs']['tid']) { $tids[$value['attrs']['tid']] = $value['attrs']['tid']; } } } } if (count($tids) == 0) { $ids = 0;
<?php header("Content-Type:text/html;charset=utf-8"); $keyword = $_POST['key']; //$keyword = "李文凯"; $sphinx = new SphinxClient(); #创建sphinx对象 $sphinx->SetServer("localhost", 9312); #建立连接,第一个参数sphinx服务器地址,第二个sphinx监听端口 $result = $sphinx->query($keyword,"main"); //var_dump($result); $ids = array_keys($result['matches']); //var_dump($ids); $ids = join(",",$ids); //连接数据库 $conn = mysql_connect("localhost","root","root3306"); //选择数据库 mysql_select_db("test"); //设置字符集 mysql_set_charset("utf8"); //准备sql语句 $sql = "select id,title,content from post where id in(".$ids.")"; //发送sql语句 $result = mysql_query($sql); //处理结果皆
$sphinx->SetLimits($pageNum * $number, $number, 20000); $sphinx->SetMaxQueryTime(10); $sphinx->SetMatchMode(SPH_MATCH_EXTENDED2); $sphinx->SetFilter('enabled', array(1)); if (isset($_REQUEST['words'])) { if (intval($_REQUEST['words']) < 9) { $sphinx->SetFilter('words', array(intval($_REQUEST['words']))); } else { $sphinx->SetFilterRange('words', 9, 100); } } $sphinx->SetSortMode(SPH_SORT_EXTENDED, "lang_part ASC, words ASC, header_sort ASC, count DESC"); if (isset($_REQUEST["sid"])) { $key_word[] = '(@artist_sid_1 ' . intval($_REQUEST['sid']) . ' | @artist_sid_2 ' . intval($_REQUEST['sid']) . ')'; } $result = $sphinx->query(implode(' | ', $key_word), 'media'); if (!isset($result['matches'])) { include_once '_song.php'; exit; // $finalResult = array( // "songs" => array(), // "page" => 0, // "total" => 0, // "totalNumber" => 0 // ); // formatResult($finalResult); // exit; } $countValue = $result['total']; if ($countValue == 0) { $pageCount = 0;
<?php /** * sphinx链接测试 */ $offset = 0; $limit = 30; include_once "sphinxapi.php"; $sphinx = new SphinxClient(); $sphinx->setServer('192.168.2.188', 9319); $sphinx->SetMatchMode(SPH_MATCH_EXTENDED2); $sphinx->SetSortMode(SPH_SORT_EXTENDED, "newstime DESC"); $sphinx->SetFilter('checked', array(1)); $sphinx->SetLimits($offset * 30, $limit, 1000); $res = $sphinx->query("", 'd_hangyenews,m_hangyenews'); echo "<pre>"; var_dump($sphinx); echo "\n"; var_dump($res); exit;
/** * ¬озвращает список публичных типовых услуг по заданным услови¤м и пагинацией * * @return array */ public function getList($excluded_ids = array()) { $criteria = array($this->category_id, $this->city_id, $this->country_id, $this->keywords, $this->limit, $this->offset, $this->price_ranges, $this->price_max, $this->order, $excluded_ids, $this->user_id); $membuf = new memBuff(); $memkey = __METHOD__ . '#' . md5(serialize($criteria)); if (false !== ($result = $membuf->get($memkey)) && is_release()) { return $result; } $sort = $this->getSort(); # @see http://sphinxsearch.com/forum/view.html?id=11538 about city = x or country = y $sphinxClient = new SphinxClient(); $sphinxClient->SetServer(SEARCHHOST, SEARCHPORT); $sphinxClient->SetLimits($this->offset, $this->limit, 20000); $sphinxClient->SetSortMode(SPH_SORT_EXTENDED, $sort); $sphinxClient->SetFieldWeights(array('title' => 2, 'extra_title' => 1)); //$sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25); $selectExpression = '*'; // все колонки if ($this->user_id) { $selectExpression .= ", IF(user_id = {$this->user_id}, 1, 0) as match_user"; $sphinxClient->setFilter('match_user', array(1)); } if ($this->category_id) { $selectExpression .= ", IF(category_id = {$this->category_id} or category_parent_id = {$this->category_id}, 1, 0) as match_category"; $sphinxClient->setFilter('match_category', array(1)); } if ($this->country_id) { $selectExpression .= ", IF(user_country_id = {$this->country_id} or country_id = {$this->country_id}, 1, 0) as match_country"; $sphinxClient->setFilter('match_country', array(1)); } if ($this->city_id) { $selectExpression .= ", IF(user_city_id = {$this->city_id} or city_id = {$this->city_id}, 1, 0) as match_city"; $sphinxClient->setFilter('match_city', array(1)); } if (count($this->price_ranges)) { $match_price_exprs = array(); foreach ($this->getPriceRanges() as $i => $price_range) { if (!isset($this->price_ranges[$i])) { continue; } $match_price_exprs[] = "price_{$i} = 1"; } $match_price_exprs = implode(' or ', $match_price_exprs); $selectExpression .= ", IF({$match_price_exprs}, 1, 0) as match_price"; $sphinxClient->setFilter('match_price', array(1)); } if ($this->price_max > 0) { $selectExpression .= ", IF(price <= {$this->price_max}, 1, 0) as match_price_max"; $sphinxClient->setFilter('match_price_max', array(1)); } $searchString = ''; if (!empty($this->keywords)) { $keywords = implode(' ', array_filter(preg_split('/\\s*,\\s*/', $this->keywords))); $searchString = trim($keywords); //$searchString = $this->GetSphinxKeyword($searchString); $sphinxClient->SetMatchMode(SPH_MATCH_ANY); //SPH_MATCH_EXTENDED2); } if (count($excluded_ids)) { $sphinxClient->setFilter('tservice_id', $excluded_ids, true); } $sphinxClient->SetSelect($selectExpression); $queryResult = $sphinxClient->query($searchString, "tservices;delta_tservices"); //echo '<pre>error: ', $sphinxClient->GetLastError(), '</pre>'; //echo '<pre>warn : ', $sphinxClient->GetLastWarning(), '</pre>'; $list = array(); $total = 0; if (isset($queryResult['matches'])) { foreach ($queryResult['matches'] as $id => $row) { $row['attrs']['id'] = $id; $list[] = $row['attrs']; } $total = $queryResult['total_found'] < $queryResult['total'] ? $queryResult['total_found'] : $queryResult['total']; } $result = array('list' => $list, 'total' => $total); if ($this->_ttl) { $membuf->set($memkey, $result, $this->_ttl); } return $result; }
*/ 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 . ")"; $res = mysql_query($sql); $posts = array(); if ($res !== false && mysql_num_rows($res) > 0) { while ($rows = mysql_fetch_assoc($res)) { $posts[] = $rows; } } //print_r($posts);
/** * 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 Performs actual query through Sphinx Connector * @details Profiles $this->client->query($query, $index); * @param string $index * @param string $query * @param string $comment * @return array */ protected function doSearch($index, $query = '', $comment = '') { if (!$index) { throw new DGSphinxSearchException('Index search criteria invalid'); } if ($this->enableResultTrace) { Yii::trace("Query '{$query}' is performed for index '{$index}'", 'CEXT.DGSphinxSearch.doSearch'); } if ($this->enableProfiling) { Yii::beginProfile("Search query: '{$query}' in index: '{$index}'", 'CEXT.DGSphinxSearch.doSearch'); } $res = $this->client->query($query, $index, $comment); if ($this->getLastError()) { throw new DGSphinxSearchException($this->getLastError()); } if ($this->enableProfiling) { Yii::endProfile("Search query: '{$query}' in index: '{$index}'", 'CEXT.DGSphinxSearch.doSearch'); } if ($this->enableResultTrace) { Yii::trace("Query result: " . substr(print_r($res, true), 500), 'CEXT.DGSphinxSearch.doSearch'); } if (!isset($res['matches'])) { $res['matches'] = array(); } $this->resetCriteria(); return $res; }