本文整理汇总了PHP中SphinxClient::query方法的典型用法代码示例。如果您正苦于以下问题:PHP SphinxClient::query方法的具体用法?PHP SphinxClient::query怎么用?PHP SphinxClient::query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SphinxClient
的用法示例。
在下文中一共展示了SphinxClient::query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: searchTasks
/**
*
* @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);
}
示例2: search
/**
* 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;
}
示例3: search
/**
* 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;
}
示例4: executeSearch
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');
}
示例5: search
/**
* 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);
}
示例6: sphinxSearch
/**
* 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));
}
示例7: foreach
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']);
示例8: search
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 '';
}
示例9: getRelaCateCommon
/**
* 关键词获取普通产品获取相关分类
* @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;
}
示例10: array
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;
}
示例11: function
* @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);
}
示例12: _query
/**
* Отправляет подготовленный запрос на сфинкс, и преобразует ответ в нужный вид.
*
* @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;
}
示例13: getSphinxSearchedResult
/**
* @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;
}
示例14: timer
$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'];
//页数
示例15: SphinxClient
$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;