/**
  * Connect to sphinx
  */
 public function init()
 {
     if (!class_exists('SphinxClient', false)) {
         include_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'SphinxClient.php';
     }
     $this->_client = new SphinxClient();
     $this->_client->setServer($this->server, $this->port);
     $this->_client->setMaxQueryTime($this->maxQueryTime);
     $this->resetClient();
 }
 /**
  * Constructor.
  *
  * @param string $host The server's host name/IP.
  * @param string $port The port that the server is listening on.
  * @param string $socket The UNIX socket that the server is listening on.
  * @param array $indexes The list of indexes that can be used.
  */
 public function __construct($host = 'localhost', $port = '9312', $socket = null, array $indexes = array())
 {
     $this->host = $host;
     $this->port = $port;
     $this->socket = $socket;
     $this->indexes = $indexes;
     $this->sphinx = new \SphinxClient();
     if ($this->socket !== null) {
         $this->sphinx->setServer($this->socket);
     } else {
         $this->sphinx->setServer($this->host, $this->port);
     }
 }
 /**
  * Constructor.
  *
  * @param string $host The server's host name/IP.
  * @param string $port The port that the server is listening on.
  * @param string $socket The UNIX socket that the server is listening on.
  * @param array $indexes The list of indexes that can be used.
  * @param array $mapping The list of mapping
  * @param \Doctrine\ORM\EntityManager $em  for db query
  */
 public function __construct($host = 'localhost', $port = '9312', $socket = null, array $indexes = array(), array $mapping = array(), EntityManager $em = null)
 {
     $this->host = $host;
     $this->port = $port;
     $this->socket = $socket;
     $this->indexes = $indexes;
     $this->em = $em;
     $this->mapping = new MappingCollection($mapping);
     $this->sphinx = new \SphinxClient();
     if ($this->socket !== null) {
         $this->sphinx->setServer($this->socket);
     } else {
         $this->sphinx->setServer($this->host, $this->port);
     }
 }
예제 #4
0
파일: sphinxha.php 프로젝트: glianyi/MyPHP
 public static function getInstance($sphinxconf, $type = 'media')
 {
     $time = microtime(true);
     $rand = intval(substr($time, 11, 4));
     $num = count($sphinxconf);
     $index = $rand % $num;
     $ret = false;
     if (null == self::$_sphinxpool[$type]) {
         $try_count = 0;
         while ($try_count < 3 && $ret != true) {
             $client = new SphinxClient();
             $index = $index % $num;
             try {
                 $client->setServer($sphinxconf[$index]['host'], $sphinxconf[$index]['port']);
                 self::$_index[$type] = $sphinxconf[$index]['indexer'];
                 $ret = $client->Open();
                 if ($ret == true) {
                     self::$_conf_num[$type] = $index;
                     break;
                 }
                 Systemlog::fatal("sphinx connect fail time:" . $client->_host . " " . $client->_port);
                 $try_count++;
                 $index++;
             } catch (Exception $e) {
                 $index++;
                 $try_count++;
             }
         }
         self::$_sphinxpool[$type] = $client;
     }
     return self::$_sphinxpool[$type];
 }
예제 #5
0
파일: Utils.php 프로젝트: jessesiu/GigaDBV3
 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;
 }
예제 #6
0
파일: Search.php 프로젝트: kastner/pgboard
 function query($query, $index, $offset = 0)
 {
     require_once DIR . "lib/sphinx/sphinxapi.php";
     $sphinx = new SphinxClient();
     $sphinx->setServer(SPHINX_HOST, SPHINX_PORT);
     $sphinx->SetLimits($offset, 100, 10000000);
     $sphinx->SetMatchMode(SPH_MATCH_EXTENDED);
     $sphinx->SetSortMode(SPH_SORT_ATTR_DESC, 'date_posted');
     $res = $sphinx->Query($query, $index);
     return $res;
 }
 /**
  * do driver instance init
  */
 public function setup()
 {
     $settings = $this->getSettings();
     if (empty($settings)) {
         throw new BoxRouteInstanceException('init driver instance failed: empty settings');
     }
     $curInst = new \SphinxClient();
     $curInst->setServer($settings['sphinxHost'], $settings['sphinxPort']);
     !empty($settings['sphinxConnectTimeout']) && $curInst->setConnectTimeout($settings['sphinxConnectTimeout']);
     $this->instance = $curInst;
     $this->isAvailable = $this->instance ? true : false;
 }
예제 #8
0
 /**
  * 获取竞品信息
  * @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;
 }
 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);
 }
예제 #10
0
 public function init()
 {
     parent::init();
     include_once dirname(__FILE__) . '/models/DGSphinxSearchResult.php';
     $this->client = new SphinxClient();
     $this->client->setServer($this->server, $this->port);
     $this->client->setMaxQueryTime($this->maxQueryTime);
     Yii::trace("weigth: " . print_r($this->fieldWeights, true), 'CEXT.DGSphinxSearch.doSearch');
     $this->resetCriteria();
 }
예제 #11
0
<?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);
        }
예제 #12
0
 /**
  * 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;
 }
예제 #13
0
 if (!$srchtxt && !$srchuid && !$srchuname && !$srchfrom && !in_array($srchfilter, array('digest', 'top')) && !is_array($special)) {
     dheader('Location: search.php?mod=forum');
 } elseif (isset($srchfid) && !empty($srchfid) && $srchfid != 'all' && !(is_array($srchfid) && in_array('all', $srchfid)) && empty($forumsarray)) {
     showmessage('search_forum_invalid', 'search.php?mod=forum');
 } elseif (!$fids) {
     showmessage('group_nopermission', NULL, array('grouptitle' => $_G['group']['grouptitle']), array('login' => 1));
 }
 if ($_G['adminid'] != '1' && $_G['setting']['search']['forum']['maxspm']) {
     if (DB::result_first("SELECT COUNT(*) FROM " . DB::table('common_searchindex') . " WHERE srchmod='{$srchmod}' AND dateline>'{$_G['timestamp']}'-60") >= $_G['setting']['search']['forum']['maxspm']) {
         showmessage('search_toomany', 'search.php?mod=forum', array('maxspm' => $_G['setting']['search']['forum']['maxspm']));
     }
 }
 if ($srchtype == 'fulltext' && $_G['setting']['sphinxon']) {
     require_once libfile('class/sphinx');
     $s = new SphinxClient();
     $s->setServer($_G['setting']['sphinxhost'], intval($_G['setting']['sphinxport']));
     $s->setMaxQueryTime(intval($_G['setting']['sphinxmaxquerytime']));
     $s->SetRankingMode($_G['setting']['sphinxrank']);
     $s->setLimits(0, intval($_G['setting']['sphinxlimit']), intval($_G['setting']['sphinxlimit']));
     $s->setGroupBy('tid', SPH_GROUPBY_ATTR);
     if ($srchfilter == 'digest') {
         $s->setFilterRange('digest', 1, 3, false);
     }
     if ($srchfilter == 'top') {
         $s->setFilterRange('displayorder', 1, 2, false);
     } else {
         $s->setFilterRange('displayorder', 0, 2, false);
     }
     if (!empty($srchfrom) && empty($srchtxt) && empty($srchuid) && empty($srchuname)) {
         $expiration = TIMESTAMP + $cachelife_time;
         $keywords = '';
예제 #14
0
<?php

require 'lib/sphinxapi.php';
$searchd = new SphinxClient();
$searchd->setServer("localhost", 9312);
$SPHINX_MAX_MATCHES = 5000000;
// $searchd->setMatchMode(SPH_MATCH_ANY);
// $searchd->setMatchMode(SPH_MATCH_EXTENDED);
// $searchd->setMaxQueryTime(10);
 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 '';
 }
 /**
  * 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;
 }
 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;
 }
예제 #18
0
<?php

/* Sphinx
 * @author bergstein@trickyplan.com
 * @description  
 * @package Sphinx
 * @version 8.x
 */
setFn('Do', function ($Call) {
    $Sphinx = new SphinxClient();
    $Sphinx->setServer('localhost', 9312);
    if (!($Status = $Sphinx->status())) {
        $Call['Output']['Status'][] = ['Type' => 'Block', 'Class' => 'alert alert-danger', 'Value' => '<l>Sphinx.Connect.Failed</l>'];
    } else {
        foreach ($Status as &$Row) {
            $Row[0] = '<l>Sphinx.Status.' . $Row[0] . '</l>';
        }
        $Call['Output']['Status'][] = ['Type' => 'Table', 'Value' => $Status];
    }
    return $Call;
});
setFn('Reindex', function ($Call) {
    $Call['Output']['Content'][] = ['Type' => 'Block', 'Class' => 'alert alert-success', 'Value' => nl2br(shell_exec('indexer --all --rotate'))];
    return $Call;
});
예제 #19
0
파일: info.php 프로젝트: tianyunchong/php
<?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;
예제 #20
0
 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;
 }
예제 #21
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));
 }
예제 #22
0
파일: update.php 프로젝트: pengfen/linux
<?php

//模拟删除信息
include './sphinxapi.php';
$id = 2;
$status = 0;
mysql_connect("localhost", "root", "123");
mysql_select_db("test");
mysql_set_charset("utf8");
echo $sql = "update post set status='{$status}' where id=" . (int) $id;
$res = mysql_query($sql);
$sp = new SphinxClient();
$sp->setServer('localhost', 9312);
$sp->updateAttributes('ind_post', array('status'), array($id => array($status)));
예제 #23
0
 /**
  * @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;
 }
예제 #24
0
 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);
 }
예제 #25
0
 public function init()
 {
     parent::init();
     $this->client = new SphinxClient();
     $this->client->setServer($this->server, $this->port);
     $this->client->setMaxQueryTime($this->maxQueryTime);
     Yii::trace("weigth: " . print_r($this->fieldWeights, true), 'CEXT.ESphinxSearch.doSearch');
     $this->resetCriteria();
 }
예제 #26
0
 /**
  * Отправляет подготовленный запрос на сфинкс, и преобразует ответ в нужный вид.
  *
  * @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;
 }
예제 #27
0
// array for JSON response
error_reporting(E_ALL & ~E_NOTICE);
$response = array();
// include db connect class
require_once __DIR__ . '\\connect.php';
// connecting to db
$db = new DB_CONNECT();
ini_set('default_charset', 'UTF-8');
// check for post data
if (isset($_POST["keyWord"]) || isset($_POST["location"]) || isset($_POST["special"])) {
    $offset = 0;
    $limit = 10;
    $max_matches = 100;
    require_once 'C:\\Sphinx\\api\\sphinxapi.php';
    $s = new SphinxClient();
    $s->setServer("127.0.0.1", 9312);
    $s->setMatchMode(SPH_MATCH_EXTENDED2);
    if (isset($_POST['offset'])) {
        $offset = $_POST['offset'];
    }
    //$sortMode='ratepoint';
    if (isset($_POST["sortMode"])) {
        $sortMode = $_POST["sortMode"];
        $s->setSortMode(SPH_SORT_ATTR_DESC, $sortMode);
    }
    $s->SetLimits((int) $offset, (int) $limit, (int) $limit > $max_matches ? (int) $limit : (int) $max_matches);
    if (isset($_POST["keyWord"]) && isset($_POST["location"]) && isset($_POST["special"])) {
        $keyWord = $_POST['keyWord'];
        $location = $_POST['location'];
        $special = $_POST['special'];
        $result = $s->Query("@(JobName,Company) {$keyWord} @location {$location} @(Requirement,Tags) {$special}");
예제 #28
0
파일: index.php 프로젝트: kupnu4x/dcsearch
$nodirs = isset($_GET['nodirs']) ? (bool) $_GET['nodirs'] : false;
$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) {
예제 #29
0
파일: search.php 프로젝트: momoim/momo-api
 /**
  * 
  * sphinx instance
  */
 private function sphinx_instance()
 {
     $sphinx = new SphinxClient();
     $sphinx->setServer(Kohana::config('uap.sphinx_host'), Kohana::config('uap.sphinx_port'));
     if (!$sphinx->open()) {
         $this->send_response(400, NULL, '400111:cannot connect to sphinx daemon' . $sphinx->GetLastError());
     }
     return $sphinx;
 }