/** * Reset settings sphinx */ public function resetClient() { $this->_client->resetFilters(); $this->_client->resetGroupBy(); $this->_client->setArrayResult(false); //DEPRECATED: Do not call this method or, even better, use SphinxQL instead of an API //$this->_client->setMatchMode(SPH_MATCH_EXTENDED2); $this->_client->setLimits(0, 20, 1000, 0); $this->_client->setFieldWeights(array()); $this->_client->setSortMode(SPH_SORT_RELEVANCE, ''); $this->_client->_error = ''; $this->_client->_warning = ''; }
/** * * @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); }
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; }
/** * 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; }
public function __construct($query) { $this->query = $query; $max_results = intval(SphinxSearch_Config_Plugin::getValue("results", "maxresults")); $this->limit = $max_results; $SphinxClient = new SphinxClient(); $this->SphinxClient = $SphinxClient; $SphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2); $SphinxClient->SetSortMode(SPH_SORT_EXTENDED, "@weight DESC"); $SphinxClient->setServer("localhost", SphinxSearch_Config_Plugin::getValue("searchd", "port")); // Sphinx Client is to always return everything - it's just IDs // Paginator is then to cast the necessary Items, this can be done // with offset/limit $SphinxClient->setLimits(0, $max_results, $max_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; }
/** * Отправляет подготовленный запрос на сфинкс, и преобразует ответ в нужный вид. * * @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; }
public function getSphinxAdapter() { require_once Mage::getBaseDir('lib') . DIRECTORY_SEPARATOR . 'sphinxapi.php'; // Connect to our Sphinx Search Engine and run our queries $sphinx = new SphinxClient(); $host = Mage::getStoreConfig('sphinxsearch/server/host'); $port = Mage::getStoreConfig('sphinxsearch/server/port'); if (empty($host)) { return $sphinx; } if (empty($port)) { $port = 9312; } $sphinx->SetServer($host, $port); $sphinx->SetMatchMode(SPH_MATCH_EXTENDED2); $sphinx->setFieldWeights(array('name' => 7, 'category' => 1, 'name_attributes' => 1, 'data_index' => 3)); $sphinx->setLimits(0, 200, 1000, 5000); // SPH_RANK_PROXIMITY_BM25 ist default $sphinx->SetRankingMode(SPH_RANK_SPH04, ""); // 2nd parameter is rank expr? return $sphinx; }
/** * 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); }
} $cl = new SphinxClient(); // 返回结果设置 $cl->SetServer('192.168.25.129', 9312); $cl->SetConnectTimeout(3); $cl->SetArrayResult(true); // 设置是否全文匹配 if (!empty($_GET) && !empty($_GET['f'])) { $cl->SetMatchMode(SPH_MATCH_ANY); } if (!empty($_GET) && !empty($_GET['p'])) { $p = !intval(trim($_GET['p'])) == 0 ? intval(trim($_GET['p'])) - 1 : 0; $p = $p * 20; // 我在sed.conf 设置了最大返回结果数1000。但是我在生成页码的时候最多生成20页,我想能满足大部分搜索需求了。 // 以下语句表示从P参数偏移开始每次返回20条。 $cl->setLimits($p, 20); } else { $cl->setLimits(0, 20); } $res = $cl->Query("{$Keywords}", "*"); //var_dump($res); @mysql_connect("localhost", "test", "mima"); //数据库账号密码 mysql_select_db("test"); //数据库库名名 mysql_query("set names utf8"); $tables = ['spdb1', 'spdb2', 'spdb3', 'spdb4', 'spdb5']; //把表名放入数组 function getResult($id, $table) { $sql = "select username,email,password,salt,site from {$table} where id = " . $id;
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) { $spx_timemix = 0; $spx_timemax = TIMESTAMP - $srchfrom;
function getRecipes($advanced) { include __ROOT__ . "sphinx/api.php"; $cl = new SphinxClient(); $cl->SetServer("localhost", 9312); $l = isset($advanced['limit']) ? $advanced['limit'] : 10; $limit = isset($advanced['page']) ? (int) $advanced['page'] * $l : 0; $cl->setLimits($limit, $l + 1); $lang_id = 0; if ($advanced['favorites'] == 1 && VF::app()->user->isAuth()) { $ids_a = array(); $ids = VF::app()->database->sql("SELECT recipe_id FROM recipes_likes WHERE user_id = " . VF::app()->user->getId())->queryAll(); foreach ($ids as $i) { $ids_a[] = $i['recipe_id']; } if (empty($ids_a)) { return array(); } $cl->setFilter('id_attr', $ids_a); } else { if (isset($advanced['lang_id'])) { $lang_id = $advanced['lang_id']; } else { $lang_id = VF::app()->lang_id; } } if ($advanced['country_id'] > 0) { $cl->setFilter('country_id', array($advanced['country_id'])); } if ($advanced['category_id'] > 0) { $cl->setFilter('category_id', array($advanced['category_id'])); $lang_id = 0; } if ($lang_id > 0) { $cl->setFilter('lang_id', array($lang_id)); } if (!empty($advanced['ingredient_id'])) { $ids_a = array(); $a = explode(",", $advanced['ingredient_id']); if (count($a) > 1) { $sql = "SELECT recipe_id, count(Distinct ingredient_id)\n FROM recipes2ingredients\n WHERE ingredient_ID in (" . $advanced['ingredient_id'] . ")\n GROUP BY recipe_id\n HAVING count(Distinct ingredient_id) = " . count($a); } else { $sql = "SELECT recipe_id FROM recipes2ingredients WHERE ingredient_id = " . $advanced['ingredient_id'] . " LIMIT 300"; } $ids = VF::app()->database->sql($sql)->queryAll(); foreach ($ids as $i) { $ids_a[] = $i['recipe_id']; } $cl->setFilter('id_attr', $ids_a); } if (!empty($advanced['query'])) { $results = $cl->Query($advanced['query']); // поисковый запрос } else { $cl->SetMatchMode(SPH_MATCH_FULLSCAN); // ищем хотя бы 1 слово из поисковой фразы $cl->setSortMode(SPH_SORT_ATTR_DESC, 'date_created'); $results = $cl->Query('*'); // поисковый запрос } $this->total_found = $results['total_found']; $arr = array(); if (!empty($results['matches'])) { foreach ($results['matches'] as $r) { $r['attrs']['id'] = $r['attrs']['id_attr']; $arr[] = $r['attrs']; } } return $arr; }
<?php /* 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); }
/** * @param \SphinxClient $sphinx */ public function bindToSphinx(\SphinxClient $sphinx) { $sphinx->setLimits($this->getOffset(), $this->getLimit(), $this->getMaxResults()); }
/** * 全文搜索 * */ 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) : ''; }
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); $res = $sphinx->Query('( ' . $w . ' | ' . $w . '* | *' . $w . '* | *' . $w . ' ) ', 'name' . $GLOBALS['CONFIG']['search_index_prefix']);
/** * @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); } }
$smarty->assign('beizhuxinxi_www_68ecshop_com', '关键词<font color=#cc0000>' . $_REQUEST['keyword_zm'] . '</font>搜索结果为零,<br>但是我们为您匹配到了相关关键词<font color=#cc0000>' . $_REQUEST['keywords'] . '</font>,下面是它的查询结果!'); } /* 代码添加_END By www.68ecshop.com */ $max_page = $count > 0 ? ceil($count / $size) : 1; if ($page > $max_page) { $page = $max_page; } /* 查询商品 */ $sql = "SELECT g.goods_id, g.goods_name, g.market_price, g.click_count, g.goods_number, g.is_new, g.is_best, g.is_hot, g.shop_price AS org_price, " . "IFNULL(mp.user_price, g.shop_price * '{$_SESSION['discount']}') AS shop_price, " . "g.promote_price, g.promote_start_date, g.promote_end_date, g.goods_thumb, g.goods_img, g.goods_brief, g.goods_type " . "FROM " . $ecs->table('goods') . " AS g " . "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp " . "ON mp.goods_id = g.goods_id AND mp.user_rank = '{$_SESSION['user_rank']}' " . "WHERE g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 {$attr_in} {$categories} " . "AND (( 1 " . $keywords . $brand . $min_price . $max_price . $intro . $outstock . " ) " . $tag_where . " ) " . "ORDER BY {$sort} {$order}"; } /* fulltext_search_add_START_www.68ecshop.com */ if ($_CFG['fulltext_search'] == '1') { require ROOT_PATH . "includes/sphinxapi.php"; $s = new SphinxClient(); $s->SetServer('localhost', 9312); $s->setLimits(0, 1000); //$s->SetMatchMode ( SPH_MATCH_ANY); // 分词 $result = $s->Query($_REQUEST['keywords'], 'goods'); if ($result) { $idarray = array_keys($result['matches']); if (empty($idarray)) { $idarray = array(); foreach ($replacef_www_68ecshop_com as $key => $value) { $result = $s->Query($value, 'goods'); $idss = array_keys($result['matches']); if (empty($idss)) { $idss = array(); } $idarray = array_merge($idarray, $idss); } }
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 . ")"; $res = mysql_query($sql); $posts = array(); if ($res !== false && mysql_num_rows($res) > 0) { while ($rows = mysql_fetch_assoc($res)) { $posts[] = $rows; }
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.' )'; }else{
private static function searchObjects($query, $class_name, $params = array()) { if (trim($query) == "") { return array(); } $class_name = strtolower($class_name); $sphinx_config = SphinxSearch_Config::getInstance(); $SphinxClient = new SphinxClient(); $SphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2); $SphinxClient->setServer("localhost", intval(SphinxSearch_Config_Plugin::getValue("searchd", "port"))); if (array_key_exists("language", $params)) { $language = $params["language"]; } else { $locale = Zend_Registry::get("Zend_Locale"); $language = $locale->getLanguage(); } if (array_key_exists("orderKey", $params)) { $order = "ASC"; if (array_key_exists("order", $params)) { $order = $params["order"] == "DESC" ? "DESC" : "ASC"; } $SphinxClient->SetSortMode(SPH_SORT_EXPR, $params["orderKey"] . " " . $order); } $max_results = 1000; // TODO intval(SphinxSearch_Config_Plugin::getValue($config->maxresults); if (array_key_exists("max_results", $params)) { $max_results = intval($params["max_results"]); if ($max_results < 1) { $max_results = 20; } // Sphinx default actually } $offset = 0; if (array_key_exists("offset", $params)) { $offset = intval($params["offset"]); } $SphinxClient->setLimits($offset, $max_results, $max_results); $class_config = $sphinx_config->getClassesAsArray(); // The configuration $field_weights = array(); foreach ($class_config[$class_name] as $field_name => $field_config) { if (array_key_exists("weight", $field_config)) { $field_weights[$field_name] = $field_config["weight"]; } } if (sizeof($field_weights) > 0) { $SphinxClient->setFieldWeights($field_weights); } $index = "idx_" . $class_name; $object_class = Object_Class::getByName($class_name); if (!$object_class) { throw new SphinxSearch_Exception("Class \"" . $class_name . "\" not found."); } if ($object_class->getFieldDefinition("localizedfields")) { $locale = Zend_Registry::get("Zend_Locale"); $language = $locale->getLanguage(); $index .= "_" . $language; } $search_result = $SphinxClient->Query($query, $index); if ($search_result === false) { throw new Exception($SphinxClient->GetLastError()); } return $search_result; }
$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); } 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));
/** * @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; }
/** * 全文搜索 * */ 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; }
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; }
/** * 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; }