RunQueries() 공개 메소드

connect to searchd, run queries batch, and return an array of result sets
public RunQueries ( )
예제 #1
0
 protected function execute()
 {
     $sph = $this->sphinxClient->RunQueries();
     if ($error = $this->sphinxClient->GetLastError()) {
         throw new ESphinxException($error);
     }
     if ($error = $this->sphinxClient->GetLastWarning()) {
         throw new ESphinxException($error);
     }
     if (!is_array($sph)) {
         throw new ESphinxException("Sphinx client returns result not array");
     }
     $results = array();
     foreach ($sph as $result) {
         if (isset($result['error']) && strlen($result['error'])) {
             throw new ESphinxException($result['error']);
         }
         $results[] = new ESphinxResult($result);
     }
     return $results;
 }
예제 #2
0
<?php

require "spec/fixtures/sphinxapi.php";
$cl = new SphinxClient();
$cl->SetRetries(10, 20);
$cl->AddQuery('test1');
$cl->SetGroupBy('attr', SPH_GROUPBY_DAY);
$cl->AddQuery('test2');
$cl->RunQueries();
예제 #3
0
파일: locum-client.php 프로젝트: aadl/locum
 /**
  * Does an index search via Sphinx and returns the results
  *
  * @param string $type Search type.  Valid types are: author, title, series, subject, keyword (default)
  * @param string $term Search term/phrase
  * @param int $limit Number of results to return
  * @param int $offset Where to begin result set -- for pagination purposes
  * @param array $sort_array Numerically keyed array of sort parameters.  Valid options are: newest, oldest
  * @param array $location_array Numerically keyed array of location params.  NOT IMPLEMENTED YET
  * @param array $facet_args String-keyed array of facet parameters. See code below for array structure
  * @return array String-keyed result set
  */
 public function search($type, $term, $limit, $offset, $sort_opt = NULL, $format_array = array(), $location_array = array(), $facet_args = array(), $override_search_filter = FALSE, $limit_available = FALSE, $show_inactive = FALSE)
 {
     if (is_callable(array(__CLASS__ . '_hook', __FUNCTION__))) {
         eval('$hook = new ' . __CLASS__ . '_hook;');
         return $hook->{__FUNCTION__}($type, $term, $limit, $offset, $sort_opt, $format_array, $location_array, $facet_args, $override_search_filter, $limit_available);
     }
     require_once $this->locum_config['sphinx_config']['api_path'] . '/sphinxapi.php';
     $db =& MDB2::connect($this->dsn);
     $term_arr = explode('?', trim(preg_replace('/\\//', ' ', $term)));
     $term = trim($term_arr[0]);
     if ($term == '*' || $term == '**') {
         $term = '';
     } else {
         $term_prestrip = $term;
         //$term = preg_replace('/[^A-Za-z0-9*\- ]/iD', '', $term);
         $term = preg_replace('/\\*\\*/', '*', $term);
         //fix for how iii used to do wildcards
     }
     $final_result_set['term'] = $term;
     $final_result_set['type'] = trim($type);
     $cl = new SphinxClient();
     $cl->SetServer($this->locum_config['sphinx_config']['server_addr'], (int) $this->locum_config['sphinx_config']['server_port']);
     // Defaults to 'keyword', non-boolean
     $bool = FALSE;
     $cl->SetMatchMode(SPH_MATCH_ALL);
     if (!$term) {
         // Searches for everything (usually for browsing purposes--Hot/New Items, etc..)
         $cl->SetMatchMode(SPH_MATCH_EXTENDED2);
     } else {
         $picturebook = array('picturebook', 'picture book');
         $picbk_search = '(@callnum ^E)';
         $term = str_ireplace($picturebook, $picbk_search, $term);
         if ($type == 'keyword') {
             // Custom fiction and non-fiction search
             $nonfic_search = ' (@callnum "0*" | @callnum "1*" | @callnum "2*" | @callnum "3*" | @callnum "4*" | @callnum "5*" | @callnum "6*" | @callnum "7*" | @callnum "8*" | @callnum "9*")';
             $fiction_search = ' (@title fiction | @subjects fiction | @callnum mystery | @callnum fantasy | @callnum fiction | @callnum western | @callnum romance)';
             if (stripos($term, 'nonfiction') !== FALSE) {
                 $term = '@@relaxed ' . str_ireplace('nonfiction', '', $term) . $nonfic_search;
             } else {
                 if (strpos($term, 'non-fiction') !== FALSE) {
                     $term = '@@relaxed ' . str_ireplace('non-fiction', '', $term) . $nonfic_search;
                 } else {
                     if (strpos($term, 'fiction') !== FALSE) {
                         $term = '@@relaxed ' . str_ireplace('fiction', '', $term) . $fiction_search;
                     }
                 }
             }
         }
         // Is it a boolean search?
         if (preg_match("/ \\| /i", $term) || preg_match("/ \\-/i", $term) || preg_match("/ \\!/i", $term)) {
             $cl->SetMatchMode(SPH_MATCH_BOOLEAN);
             $bool = TRUE;
         }
         if (preg_match("/ OR /i", $term)) {
             $cl->SetMatchMode(SPH_MATCH_BOOLEAN);
             $term = preg_replace('/ OR /i', ' | ', $term);
             $bool = TRUE;
         }
         // Is it a phrase search?
         if (preg_match("/\"/i", $term) || preg_match("/\\@/i", $term)) {
             $cl->SetMatchMode(SPH_MATCH_EXTENDED2);
             $bool = TRUE;
         }
     }
     // Set up for the various search types
     switch ($type) {
         case 'author':
             $cl->SetFieldWeights(array('author' => 50, 'addl_author' => 30));
             $idx = 'bib_items_author';
             break;
         case 'title':
             $cl->SetFieldWeights(array('title' => 50, 'title_medium' => 50, 'series' => 30));
             $idx = 'bib_items_title';
             break;
         case 'series':
             $cl->SetFieldWeights(array('title' => 5, 'series' => 80));
             $idx = 'bib_items_title';
             break;
         case 'subject':
             $idx = 'bib_items_subject';
             break;
         case 'callnum':
             $cl->SetFieldWeights(array('callnum' => 100));
             $idx = 'bib_items_callnum';
             //$cl->SetMatchMode(SPH_MATCH_ANY);
             break;
         case 'tags':
             $cl->SetFieldWeights(array('tag_idx' => 100));
             $idx = 'bib_items_tags';
             //$cl->SetMatchMode(SPH_MATCH_PHRASE);
             break;
         case 'reviews':
             $cl->SetFieldWeights(array('review_idx' => 100));
             $idx = 'bib_items_reviews';
             break;
         case 'keyword':
         default:
             $cl->SetFieldWeights(array('title' => 400, 'title_medium' => 30, 'author' => 70, 'addl_author' => 40, 'tag_idx' => 25, 'series' => 25, 'review_idx' => 10, 'notes' => 10, 'subjects' => 5));
             $idx = 'bib_items_keyword';
             break;
     }
     // Filter out the records we don't want shown, per locum.ini
     if (!$override_search_filter) {
         if (trim($this->locum_config['location_limits']['no_search'])) {
             $cfg_filter_arr = $this->csv_parser($this->locum_config['location_limits']['no_search']);
             foreach ($cfg_filter_arr as $cfg_filter) {
                 $cfg_filter_vals[] = $this->string_poly($cfg_filter);
             }
             $cl->SetFilter('loc_code', $cfg_filter_vals, TRUE);
         }
     }
     // Valid sort types are 'newest' and 'oldest'.  Default is relevance.
     switch ($sort_opt) {
         case 'newest':
             $cl->SetSortMode(SPH_SORT_EXTENDED, 'pub_year DESC, @relevance DESC');
             break;
         case 'oldest':
             $cl->SetSortMode(SPH_SORT_EXTENDED, 'pub_year ASC, @relevance DESC');
             break;
         case 'catalog_newest':
             $cl->SetSortMode(SPH_SORT_EXTENDED, 'bib_created DESC, @relevance DESC');
             break;
         case 'catalog_oldest':
             $cl->SetSortMode(SPH_SORT_EXTENDED, 'bib_created ASC, @relevance DESC');
             break;
         case 'title':
             $cl->SetSortMode(SPH_SORT_ATTR_ASC, 'title_ord');
             break;
         case 'author':
             $cl->SetSortMode(SPH_SORT_EXTENDED, 'author_null ASC, author_ord ASC');
             break;
         case 'top_rated':
             $cl->SetSortMode(SPH_SORT_ATTR_DESC, 'rating_idx');
             break;
         case 'popular_week':
             $cl->SetSortMode(SPH_SORT_ATTR_DESC, 'hold_count_week');
             break;
         case 'popular_month':
             $cl->SetSortMode(SPH_SORT_ATTR_DESC, 'hold_count_month');
             break;
         case 'popular_year':
             $cl->SetSortMode(SPH_SORT_ATTR_DESC, 'hold_count_year');
             break;
         case 'popular_total':
             $cl->SetSortMode(SPH_SORT_ATTR_DESC, 'hold_count_total');
             break;
         case 'atoz':
             $cl->SetSortMode(SPH_SORT_ATTR_ASC, 'title_ord');
             break;
         case 'ztoa':
             $cl->SetSortMode(SPH_SORT_ATTR_DESC, 'title_ord');
             break;
         default:
             $cl->SetSortMode(SPH_SORT_EXPR, "@weight + (hold_count_total)*0.02");
             break;
     }
     // Filter by material types
     if (is_array($format_array)) {
         foreach ($format_array as $format) {
             if (strtolower($format) != 'all') {
                 $filter_arr_mat[] = $this->string_poly(trim($format));
             }
         }
         if (count($filter_arr_mat)) {
             $cl->SetFilter('mat_code', $filter_arr_mat);
         }
     }
     // Filter by location
     if (count($location_array)) {
         foreach ($location_array as $location) {
             if (strtolower($location) != 'all') {
                 $filter_arr_loc[] = $this->string_poly(trim($location));
             }
         }
         if (count($filter_arr_loc)) {
             $cl->SetFilter('loc_code', $filter_arr_loc);
         }
     }
     // Filter by pub_year
     if ($facet_args['facet_year']) {
         if (strpos($facet_args['facet_year'][0], '-') !== FALSE) {
             $min_year = 1;
             $max_year = 9999;
             $args = explode('-', $facet_args['facet_year'][0]);
             $min_arg = (int) $args[0];
             $max_arg = (int) $args[1];
             if ($min_arg && $min_arg > $min_year) {
                 $min_year = $min_arg;
             }
             if ($max_arg && $max_arg < $max_year) {
                 $max_year = $max_arg;
             }
             $cl->setFilterRange('pub_year', $min_year, $max_year);
         } else {
             $cl->SetFilter('pub_year', $facet_args['facet_year']);
         }
     }
     // Filter by pub_decade
     if ($facet_args['facet_decade']) {
         $cl->SetFilter('pub_decade', $facet_args['facet_decade']);
     }
     // Filter by lexile
     if ($facet_args['facet_lexile']) {
         $cl->SetFilter('lexile', $facet_args['facet_lexile']);
     }
     // Filter by Series
     if (count($facet_args['facet_series'])) {
         foreach ($facet_args['facet_series'] as &$facet_series) {
             $facet_series = $this->string_poly($facet_series);
         }
         $cl->SetFilter('series_attr', $facet_args['facet_series']);
     }
     // Filter by Language
     if (count($facet_args['facet_lang'])) {
         foreach ($facet_args['facet_lang'] as &$facet_lang) {
             $facet_lang = $this->string_poly($facet_lang);
         }
         $cl->SetFilter('lang', $facet_args['facet_lang']);
     }
     // Filter inactive records
     if (!$show_inactive) {
         $cl->SetFilter('active', array('0'), TRUE);
     }
     // Filter by age
     if (count($facet_args['age'])) {
         foreach ($facet_args['age'] as $age_facet) {
             $cl->SetFilter('ages', array($this->string_poly($age_facet)));
         }
     }
     // Filter by availability
     if ($limit_available) {
         $cl->SetFilter('branches', array($this->string_poly($limit_available)));
     }
     $cl->SetRankingMode(SPH_RANK_SPH04);
     $proximity_check = $cl->Query($term, $idx);
     // Quick check on number of results
     // If original match didn't return any results, try a proximity search
     if (empty($proximity_check['matches']) && $bool == FALSE && $term != "*" && $type != "tags") {
         $term = '"' . $term . '"/1';
         $cl->SetMatchMode(SPH_MATCH_EXTENDED);
         $forcedchange = 'yes';
     }
     // Paging/browsing through the result set.
     $sort_limit = 2000;
     if ($offset + $limit > $sort_limit) {
         $sort_limit = $offset + $limit;
     }
     $cl->SetLimits((int) $offset, (int) $limit, (int) $sort_limit);
     // And finally.... we search.
     $cl->AddQuery($term, $idx);
     // CREATE FACETS
     $cl->SetLimits(0, 1000);
     // Up to 1000 facets
     $cl->SetArrayResult(TRUE);
     // Allow duplicate documents in result, for facet grouping
     $cl->SetGroupBy('pub_year', SPH_GROUPBY_ATTR);
     $cl->AddQuery($term, $idx);
     $cl->ResetGroupBy();
     $cl->SetGroupBy('pub_decade', SPH_GROUPBY_ATTR);
     $cl->AddQuery($term, $idx);
     $cl->ResetGroupBy();
     $cl->SetGroupBy('mat_code', SPH_GROUPBY_ATTR, '@count desc');
     $cl->AddQuery($term, $idx);
     $cl->ResetGroupBy();
     $cl->SetGroupBy('branches', SPH_GROUPBY_ATTR, '@count desc');
     $cl->AddQuery($term, $idx);
     $cl->ResetGroupBy();
     $cl->SetGroupBy('ages', SPH_GROUPBY_ATTR, '@count desc');
     $cl->AddQuery($term, $idx);
     $cl->ResetGroupBy();
     $cl->SetGroupBy('lang', SPH_GROUPBY_ATTR, '@count desc');
     $cl->AddQuery($term, $idx);
     $cl->ResetGroupBy();
     $cl->SetGroupBy('series_attr', SPH_GROUPBY_ATTR, '@count desc');
     $cl->AddQuery($term, $idx);
     $cl->ResetGroupBy();
     $cl->SetGroupBy('lexile', SPH_GROUPBY_ATTR);
     $cl->AddQuery($term, $idx);
     $cl->ResetGroupBy();
     $results = $cl->RunQueries();
     // Include descriptors
     $final_result_set['num_hits'] = $results[0]['total_found'];
     if ($results[0]['total'] <= $this->locum_config['api_config']['suggestion_threshold'] || $forcedchange == 'yes') {
         if ($this->locum_config['api_config']['use_yahoo_suggest'] == TRUE) {
             $final_result_set['suggestion'] = $this->yahoo_suggest($term_prestrip);
         }
     }
     // Pull full records out of Couch
     if ($final_result_set['num_hits']) {
         $skip_avail = $this->csv_parser($this->locum_config['format_special']['skip_avail']);
         $bib_hits = array();
         foreach ($results[0]['matches'] as $match) {
             $bib_hits[] = (string) $match['id'];
         }
         $final_result_set['results'] = $this->get_bib_items_arr($bib_hits);
         foreach ($final_result_set['results'] as &$result) {
             $result = $result['value'];
             if ($result['bnum']) {
                 // Get availability (Only cached)
                 $result['status'] = $this->get_item_status($result['bnum'], FALSE, TRUE);
             }
         }
     }
     $final_result_set['facets'] = $this->sphinx_facetizer($results);
     if ($forcedchange == 'yes') {
         $final_result_set['changed'] = 'yes';
     }
     return $final_result_set;
 }
예제 #4
0
 /**
  * 执行批量查询
  *
  * @return array The results of the queries.
  */
 function runQueries()
 {
     return $this->sphinx->RunQueries();
 }
예제 #5
0
function sphinx_do_search($by_date = false, $start = 0, $count = 50)
{
    global $globals;
    $start_time = microtime(true);
    $indices = $_REQUEST['w'] . ' ' . $_REQUEST['w'] . '_delta';
    $cl = new SphinxClient();
    $cl->SetServer($globals['sphinx_server'], $globals['sphinx_port']);
    $cl->SetLimits($start, $count);
    // status, title, tags, url,  content
    $cl->SetWeights(array(0, 4, 2, 1, 1));
    $response = array();
    $queries = array();
    $recorded = array();
    $response['rows'] = 0;
    $response['time'] = 0;
    if (empty($_REQUEST['words'])) {
        return $response;
    }
    $words_array = explode(" ", $_REQUEST['words']);
    $words_count = count($words_array);
    $words = $_REQUEST['words'];
    if ($_REQUEST['t']) {
        $max_date = time();
        $min_date = intval($_REQUEST['t']);
        $cl->SetFilterRange('date', $min_date, $max_date);
    }
    if ($_REQUEST['h']) {
        $max_date = time();
        $min_date = $max_date - intval($_REQUEST['h']) * 3600;
        $cl->SetFilterRange('date', $min_date, $max_date);
    }
    if ($_REQUEST['w'] == 'links' && $_REQUEST['s']) {
        $cl->SetFilter('status', array($_REQUEST['s_id']));
    }
    if ($_REQUEST['u']) {
        $u = new User();
        $u->username = $_REQUEST['u'];
        $u->read();
        $cl->SetFilterRange('user', $u->id, $u->id);
    }
    if ($_REQUEST['w'] == 'links' && $_REQUEST['p']) {
        $f = '@' . $_REQUEST['p'];
    } else {
        $f = '@*';
    }
    if ($by_date || $_REQUEST['o'] == 'date') {
        $cl->SetSortMode(SPH_SORT_ATTR_DESC, 'date');
    } else {
        $cl->SetSortMode(SPH_SORT_TIME_SEGMENTS, 'date');
        //$cl->SetSortMode (SPH_SORT_RELEVANCE);
    }
    $cl->SetMatchMode(SPH_MATCH_EXTENDED2);
    if ($_REQUEST['p'] == 'url') {
        $q = $cl->AddQuery("{$f} \"{$words}\"", $indices);
    } else {
        $q = $cl->AddQuery("{$f} {$words}", $indices);
    }
    array_push($queries, $q);
    // If there are no boolean opertions, add a new search for ANY of the terms
    if (!preg_match('/( and | or | [\\-\\+\\&\\|])/i', $words) && $words_count > 1) {
        $n = 0;
        foreach ($words_array as $w) {
            if ($n > 0) {
                $f .= ' |';
            }
            $f .= " {$w}";
            $n++;
        }
        $q = $cl->AddQuery($f, $indices);
        array_push($queries, $q);
    }
    $results = $cl->RunQueries();
    $n = 0;
    $response['error'] = $results['error'];
    foreach ($queries as $q) {
        $res = $results[$q];
        if (is_array($res["matches"])) {
            $response['rows'] += $res["total_found"];
            // $response['time'] += $res["time"];
            foreach ($res["matches"] as $doc => $docinfo) {
                if (!$recorded[$doc]) {
                    $response['ids'][$n] = $doc;
                    $recorded[$doc] = true;
                    $n++;
                } else {
                    $response['rows']--;
                }
            }
        }
    }
    $response['time'] = microtime(true) - $start_time;
    return $response;
}
예제 #6
0
파일: function.php 프로젝트: 8yong8/vshop
function CsGetData($index = '*', $words = '卫浴', $wheres = '', $orderby = 'id desc', $firstRow = 0, $listRows = 10, $timeout = 1, $host = 'localhost', $port = 9312)
{
    require C('INTERFACE_PATH') . 'coreseek/api/sphinxapi.php';
    $mem = new Memcache();
    $result = $mem->connect('localhost', 11211);
    $mem_key = 'coreseek_config';
    if ($mem->get($mem_key)) {
        $config = $mem->get($mem_key);
    } else {
        $config = (require C('ROOT_SITE_DIR') . 'coreseek_config.php');
        $mem->set($mem_key, $config, 0, 86400 * 365);
    }
    if (date('H') > 5 && date('H') < 6) {
        $host = $config[1]['host'];
        $port = $config[1]['port'];
    } else {
        $host = $config[1]['host'];
        $port = $config[1]['port'];
    }
    $cl = new SphinxClient();
    $cl->SetServer($host, $port);
    $cl->SetArrayResult(true);
    $cl->SetConnectTimeout($timeout);
    if ($wheres) {
        foreach ($wheres as $where) {
            $cl->SetFilter($where['field'], array($where['value']), $where['status']);
        }
    }
    $cl->SetSortMode(SPH_SORT_EXTENDED, $orderby);
    $cl->SetLimits($firstRow, $listRows);
    $cl->AddQuery($words, $index);
    $result = $cl->RunQueries();
    return $result;
}
예제 #7
0
 public function indexAction(Application $application, Template $template)
 {
     $template->setParameter('title', 'Форс-о-метр');
     if (array_key_exists('query', $_GET)) {
         $query = $this['query'] = $_GET['query'];
         $search = new SphinxClient();
         $search->SetServer('localhost', 3312);
         $search->SetGroupBy('created_at', SPH_GROUPBY_MONTH);
         // Полный поиск (запрос):
         $search->ResetFilters();
         $search->SetMatchMode(SPH_MATCH_PHRASE);
         $search->AddQuery($query, 'forceometer');
         // Поиск уникальных в месяц (запрос):
         $search->ResetFilters();
         $search->SetMatchMode(SPH_MATCH_PHRASE);
         $search->SetFilter('uniq_m', array(1));
         $search->AddQuery($query, 'forceometer');
         // Поиск уникальных вообще (запрос):
         $search->ResetFilters();
         $search->SetMatchMode(SPH_MATCH_PHRASE);
         $search->SetFilter('uniq_f', array(1));
         $search->AddQuery($query, 'forceometer');
         $query_result = $search->RunQueries();
         // Поиск уникальных постеров месяца (вообще):
         $search->ResetFilters();
         $search->SetMatchMode(SPH_MATCH_FULLSCAN);
         $search->SetFilter('uniq_m', array(1));
         $bare_query = $search->Query('', 'forceometer');
         /*
         		    $search -> ResetFilters();
                     $search -> SetMatchMode(SPH_MATCH_FULLSCAN);
                     $bare_query2 = $search -> Query('', 'forceometer');
         */
         if (!$query_result || $query_result[0]['total_found'] == 0) {
             $this['not_found'] = 1;
             return true;
         }
         $result = array('posts' => array(), 'posters' => array(), 'uniq_m' => array(), 'uniq_f' => array());
         for ($y = 2009; $y <= date('Y'); $y++) {
             for ($m = 1; $m <= 12; $m++) {
                 // Пропуск несуществующих дат и текущего месяца:
                 if ($y == 2009 && $m < 3) {
                     continue;
                 }
                 if ($y == date('Y') && $m >= date('m')) {
                     break;
                 }
                 $stamp = $y . '-' . ($m < 10 ? '0' . $m : $m) . '-01';
                 $result['posts'][$stamp] = 0;
                 $result['posters'][$stamp] = 0;
                 $result['uniq_m'][$stamp] = 0;
                 $result['uniq_f'][$stamp] = 0;
             }
         }
         // Проходим результаты:
         if ($query_result[0]['matches']) {
             foreach ($query_result[0]['matches'] as $match) {
                 $date = $match['attrs']['@groupby'];
                 $stamp = substr($date, 0, 4) . '-' . substr($date, 4, 2) . '-01';
                 if (array_key_exists($stamp, $result['posts'])) {
                     $result['posts'][$stamp] = $match['attrs']['@count'];
                 }
             }
         }
         if ($bare_query['matches']) {
             foreach ($bare_query['matches'] as $match) {
                 $date = $match['attrs']['@groupby'];
                 $stamp = substr($date, 0, 4) . '-' . substr($date, 4, 2) . '-01';
                 if (array_key_exists($stamp, $result['posters'])) {
                     $result['posters'][$stamp] = $match['attrs']['@count'];
                 }
             }
         }
         if ($query_result[1]['matches']) {
             foreach ($query_result[1]['matches'] as $match) {
                 $date = $match['attrs']['@groupby'];
                 $stamp = substr($date, 0, 4) . '-' . substr($date, 4, 2) . '-01';
                 if (array_key_exists($stamp, $result['uniq_m'])) {
                     $result['uniq_m'][$stamp] = $match['attrs']['@count'];
                 }
             }
         }
         /*
                     if ($bare_query2['matches']) {
                         foreach($bare_query2['matches'] as $match) {
                             $date = $match['attrs']['@groupby'];
                             $stamp = substr($date, 0, 4) .'-'. substr($date, 4, 2) .'-01';
         
                             if (array_key_exists($stamp, $result['uniq_f']))
                                 $result['uniq_f'][$stamp] = $match['attrs']['@count'];
                         }
                     }*/
         foreach ($result['posts'] as $date => $count) {
             if ($count == 0) {
                 unset($result['posts'][$date]);
                 unset($result['posters'][$date]);
                 unset($result['uniq_f'][$date]);
                 unset($result['uniq_m'][$date]);
             }
         }
         $this['results'] = json_encode($result);
         unset($result);
         return true;
     }
     return true;
 }
예제 #8
0
 /**
  * 从sphinx获取数据 不带分组筛选
  * @author 吕小虎
  * @datetime
  * @return
  */
 public function sphinx($data)
 {
     $this->data = $data;
     //分词
     $this->data['split'] = \Xz\Func\Common\Tools::curlGetContentMs($this->di['config']->base->split . '/wd/' . urlencode($this->data['wd']), 50);
     if (empty($this->data['split'])) {
         $this->data['split'] = $data['wd'];
     }
     $sphinxConfig = $this->di["config"]["combusinessearchsphinxdist"];
     $sphinx = new \SphinxClient();
     $sphinx->SetServer($sphinxConfig['host'], intval($sphinxConfig['port']));
     //        $sphinx->SetServer('172.17.17.103', 9111);
     $indexTable = $sphinxConfig->table;
     $gcdweight = "weight()+IF(hasgccid>0, 100, 0) as cbweight";
     $fieldStr = "id, comname, legal, areaid, uptime,{$gcdweight}";
     $sphinx->SetSelect($fieldStr);
     //排序 有gccid的靠前
     if (isset($data['order']) && !empty($data['order'])) {
         $sphinx->SetSortMode(SPH_SORT_EXTENDED, $data['order']);
     } else {
         $sphinx->SetSortMode(SPH_SORT_EXTENDED, 'cbweight DESC');
     }
     //搜某个字段
     $t = isset($this->data['t']) ? trim($this->data['t']) : '';
     //搜索类型 app/common
     $type = isset($this->data['type']) ? $this->data['type'] : 'common';
     //一级分类筛选
     if (!empty($this->data['cate1id']) && intval($this->data['cate1id']) > 0) {
         $sphinx->SetFilter('cate1', array(intval($this->data['cate1id'])), false);
     }
     //二级分类筛选
     if (!empty($this->data['cate2id']) && intval($this->data['cate2id']) > 0) {
         $sphinx->SetFilter('cate2', array(intval($this->data['cate2id'])), false);
     }
     //地区筛选
     if (!empty($this->data['areaid']) && intval($this->data['areaid']) > 0) {
         if ($this->data['areaid'] % 10000 == 0) {
             $start = intval($this->data['areaid'] / 10000) * 10000;
             $end = $start + 9999;
             $sphinx->SetFilterRange('areaid', $start, $end, false);
         } elseif ($this->data['areaid'] % 100 == 0) {
             $start = intval($this->data['areaid'] / 100) * 100;
             $end = $start + 99;
             $sphinx->SetFilterRange('areaid', $start, $end, false);
         } else {
             $sphinx->SetFilter('areaid', array(intval($this->data['areaid'])));
         }
     }
     //成立时间筛选
     if (isset($this->data['foundstart']) && $this->data['foundstart'] > 0) {
         $start = intval($this->data['foundstart']);
         $end = isset($this->data['foundend']) && $this->data['foundend'] > $this->data['foundstart'] ? intval($this->data['foundend']) : time();
         $sphinx->SetFilterRange('startdate', $start, $end, false);
     }
     //成立时间筛选
     if (isset($this->data['busstart']) && $this->data['busstart'] > 0) {
         $start = intval($this->data['busstart']);
         $end = isset($this->data['busend']) && $this->data['busend'] > $this->data['busstart'] ? intval($this->data['busend']) : time();
         $sphinx->SetFilterRange('businessstart', $start, $end, false);
     }
     //注册资本
     if (isset($this->data['regcapstart']) && $this->data['regcapstart'] > 0) {
         $start = intval($this->data['regcapstart']);
         $end = isset($this->data['regcapend']) && $this->data['regcapend'] > $this->data['regcapstart'] ? intval($this->data['regcapend']) : 100000000;
         $sphinx->SetFilterRange('regcapital', $start, $end, false);
     }
     //企业状态
     if (isset($this->data['state']) && $this->data['state'] > 0) {
         if ($this->data['state'] == 10) {
             //有效企业
             $sphinx->SetFilterRange('intstate', 0, 10, false);
         } elseif ($this->data['state'] == 20) {
             //无效企业
             $sphinx->SetFilterRange('intstate', 11, 20, false);
         } else {
             $sphinx->SetFilter('intstate', array(intval($this->data['state'])), false);
         }
     }
     $offset = isset($this->data['offset']) ? intval($this->data['offset']) : 0;
     $limit = isset($this->data['limit']) ? intval($this->data['limit']) : 200;
     $max = isset($this->data['max']) ? intval($this->data['max']) : 200;
     $sphinx->SetLimits($offset, $limit, $max);
     //企业名称和企业法人搜索  企业注册号搜索
     if (!empty($this->data['wd'])) {
         //处理搜索词
         $keyArr = explode(' ', $this->data['split']);
         $keyArr = array_filter($keyArr);
         $keyStr = '';
         if (is_array($keyArr) && !empty($keyArr)) {
             foreach ($keyArr as $value) {
                 $keyStr .= '"' . $value . '" ';
             }
         }
         if (is_numeric($this->data['wd']) && mb_strlen($this->data['wd'], 'UTF-8') == 15) {
             //注册号全匹配搜索
             $sphinx->AddQuery('@regno ' . $this->data['wd'], $indexTable);
         } elseif ($t == 'legal') {
             //企业名称和法人搜索
             $sphinx->AddQuery('@legal ' . $this->data['wd'], $indexTable);
         } else {
             //企业名称和法人搜索
             $sphinx->AddQuery('@(comname,legal) ' . $keyStr, $indexTable);
         }
     } else {
         $sphinx->AddQuery('', $indexTable);
     }
     $batchResult = $sphinx->RunQueries();
     $error = $sphinx->getLastError();
     if ($error) {
         $result['data'] = array();
         $result['total_found'] = 0;
         $result['time'] = 0;
         return $result;
     }
     $result = array();
     if (is_array($batchResult) && count($batchResult) > 0) {
         $result['data'] = $batchResult[0];
         $result['total_found'] = $result['data']['total_found'];
         $result['time'] = $result['data']['time'];
     }
     $result['split'] = $this->data['split'];
     $cidArr = array();
     if (isset($result['data']['matches'])) {
         foreach ($result['data']['matches'] as $k => $v) {
             $cidArr[] = $v['attrs']['id'];
         }
     }
     $result['data'] = $cidArr;
     return $this->outputData($result);
 }
예제 #9
0
function sphinx_get_search_link($by_date = false, $start = 0, $count = 50)
{
    global $globals;
    $cl = new SphinxClient();
    $cl->SetServer($globals['sphinx_server'], $globals['sphinx_port']);
    $cl->SetLimits($start, $count);
    // status, title, tags, url,  content
    $cl->SetWeights(array(0, 4, 2, 1, 1));
    $response = array();
    $queries = array();
    $recorded = array();
    $response['rows'] = 0;
    $response['time'] = 0;
    $words = $_REQUEST['q'] = trim(substr(strip_tags($_REQUEST['q']), 0, 250));
    if (empty($words)) {
        return $response;
    }
    if (preg_match('/^ *(\\w+): *(.*)/', $words, $matches)) {
        $prefix = $matches[1];
        $words = $matches[2];
    }
    if (preg_match('/^http[s]*/', $prefix)) {
        // It's an url search
        $words = "{$prefix}:{$words}";
        $prefix = false;
        $field = 'url';
    }
    if ($prefix) {
        switch ($prefix) {
            case 'date':
                $by_date = true;
                break;
            case 'url':
                $field = 'url';
                break;
            case 'title':
                $field = 'title';
                break;
            case 'tag':
            case 'tags':
                $field = 'tags';
                break;
        }
    }
    $words_count = count(explode(" ", $words));
    if ($field) {
        $cl->SetSortMode(SPH_SORT_ATTR_DESC, 'date');
        $cl->SetMatchMode(SPH_MATCH_EXTENDED);
        $q = $cl->AddQuery("@{$field} \"{$words}\"", 'main delta');
        array_push($queries, $q);
    } elseif ($words_count < 2 || $by_date) {
        $cl->SetSortMode(SPH_SORT_ATTR_DESC, 'date');
        $cl->SetMatchMode(SPH_MATCH_ALL);
        $q = $cl->AddQuery($words, 'main delta');
        array_push($queries, $q);
    } else {
        if ($words_count > 2) {
            $cl->SetMatchMode(SPH_MATCH_PHRASE);
            //$cl->SetSortMode (SPH_SORT_ATTR_DESC, 'date');
            $cl->SetSortMode(SPH_SORT_RELEVANCE);
            $q = $cl->AddQuery($words, 'main delta');
            array_push($queries, $q);
        }
        $cl->SetMatchMode(SPH_MATCH_ALL);
        $cl->SetSortMode(SPH_SORT_ATTR_DESC, 'date');
        //$cl->SetSortMode (SPH_SORT_RELEVANCE);
        $q = $cl->AddQuery($words, 'main delta');
        array_push($queries, $q);
        $cl->SetMatchMode(SPH_MATCH_ANY);
        $cl->SetSortMode(SPH_SORT_RELEVANCE);
        $q = $cl->AddQuery($words, 'main delta');
        array_push($queries, $q);
    }
    $results = $cl->RunQueries();
    $n = 0;
    $response['error'] = $results['error'];
    foreach ($queries as $q) {
        $res = $results[$q];
        if (is_array($res["matches"])) {
            $response['rows'] += $res["total_found"];
            $response['time'] += $res["time"];
            foreach ($res["matches"] as $doc => $docinfo) {
                if (!$recorded[$doc]) {
                    $response['ids'][$n] = $doc;
                    $recorded[$doc] = true;
                    $n++;
                } else {
                    $response['rows']--;
                }
            }
        }
    }
    return $response;
}
예제 #10
0
 protected function QuerySearch($index, $sort, $order, $port = 9312, $host = 'localhost')
 {
     $sphinx = new SphinxClient();
     $sphinx->SetServer($host, $port);
     $sphinx->SetConnectTimeout(1);
     $sphinx->SetArrayResult(true);
     $sphinx->SetLimits(0, static::LIMIT_SEARCH);
     $sphinx->SetMatchMode(SPH_MATCH_EXTENDED2);
     $sphinx->SetSortMode($order, $sort);
     // Limit results to a certain period
     if (!is_null($this->search_range)) {
         $sphinx->SetFilterRange($sort, time() - $this->search_range, time());
     }
     // Check for multi-query search
     if (is_array($this->search)) {
         foreach ($this->search as $query) {
             if (!empty($query)) {
                 $sphinx->AddQuery($this->FilterSearch($query), $index);
             }
         }
         $result = $sphinx->RunQueries();
     } else {
         $result = $sphinx->Query($this->FilterSearch($this->search), $index);
     }
     if ($result === false) {
         throw new ErrorException('Search failed: ' . $sphinx->GetLastError());
     }
     // Return result
     $ids = array();
     $ids[] = 0;
     // Make IN() valid even if Sphinx returned nothing
     if (is_array($this->search)) {
         // Merge results from multi-query search
         foreach ($result as $r) {
             if (isset($r['matches'])) {
                 foreach ($r['matches'] as $match) {
                     $ids[] = $match['id'];
                 }
             }
         }
     } elseif (isset($result['matches'])) {
         foreach ($result['matches'] as $match) {
             $ids[] = $match['id'];
         }
     }
     return $ids;
 }
예제 #11
0
 /**
  * 特殊的搜索,用于供应商查询收录,产品查询收录等
  *
  * @Author   tianyunzi
  * @DateTime 2015-12-23T15:16:46+0800
  * @param    [type]                   $data [description]
  * @return   [type]                         [description]
  */
 public function fromSpecialSphinx($data)
 {
     $this->data = $data;
     $this->data["split"] = "@comname " . $this->data["wd"];
     $sphinxConfig = $this->di["config"]["prosearchd"];
     $sphinx = new \SphinxClient();
     $sphinx->SetServer($sphinxConfig['host'], intval($sphinxConfig['port']));
     //$sphinx->SetMatchMode(SPH_MATCH_EXTENDED2);
     $indexTable = "product_distri";
     //TODO 索引范围
     if (isset($this->data["cate1"]) && $this->data["cate1"] > 0) {
         $indexTable = "product_distri_" . $this->data["cate1"];
     }
     if (!isset($this->data['cateid']) && isset($this->data['cate3'])) {
         $this->data['cateid'] = $this->data['cate3'];
     }
     $sphinx->SetSelect("id, cid, brand, feature, province, city");
     if (isset($this->data["pid"]) && $this->data["pid"] > 0) {
         $this->data["split"] = "";
         $sphinx->SetFilter("id", array($this->data["pid"]), false);
     }
     if (isset($this->data["cid"]) && $this->data["cid"] > 0) {
         $this->data["split"] = "";
         $sphinx->SetFilter("cid", array($this->data["cid"]), false);
     }
     if (!empty($this->data['cateid']) && intval($this->data['cateid']) > 0) {
         $sphinx->SetFilter('cate3', array(intval($this->data['cateid'])), false);
     }
     if (!empty($this->data['brand']) && intval($this->data['brand']) > 0) {
         $sphinx->SetFilter('brand', array(intval($this->data['brand'])), false);
     }
     if (!empty($this->data['province']) && intval($this->data['province']) > 0) {
         $sphinx->SetFilter('province', array(intval($this->data['province'])), false);
     }
     if (!empty($this->data['city']) && intval($this->data['city']) > 0) {
         $sphinx->SetFilter('city', array(intval($this->data['city'])), false);
     }
     if (!empty($this->data['iscertify']) && intval($this->data['iscertify']) > 0) {
         $sphinx->SetFilter('is_gccertify', array(intval($this->data['iscertify'])), false);
     }
     if (!empty($this->data['isprice']) && intval($this->data['isprice']) > 0) {
         $sphinx->SetFilterRange('price', 1, 9999999, false);
     }
     if (!empty($this->data['feature'])) {
         $featureArr = explode('_', $this->data['feature']);
         foreach ($featureArr as $value) {
             $sphinx->SetFilter('feature', array(intval($value)), false);
         }
     }
     if (!empty($this->data['sort'])) {
         switch ($this->data['sort']) {
             case 1:
                 $sphinx->SetSortMode(SPH_SORT_EXTENDED, 'tradenum DESC');
                 break;
             case 2:
                 $sphinx->SetSortMode(SPH_SORT_EXTENDED, 'visitnum DESC');
                 //访问量/热度
                 break;
             case 3:
                 $sphinx->SetSortMode(SPH_SORT_EXTENDED, 'price DESC');
                 break;
             case 4:
                 $sphinx->SetSortMode(SPH_SORT_EXTENDED, 'price ASC');
                 break;
             case 6:
                 $sphinx->SetSortMode(SPH_SORT_EXTENDED, 'integral DESC');
                 break;
             default:
                 $sphinx->SetSortMode(SPH_SORT_EXTENDED, 'id DESC');
                 break;
         }
     } else {
         $sphinx->SetSortMode(SPH_SORT_EXTENDED, 'id DESC');
     }
     if (isset($this->data['pid']) && $this->data['pid'] > 0) {
         $sphinx->SetLimits(0, 1, 1);
     } else {
         $sphinx->SetLimits(0, 200, 200);
     }
     $sphinx->AddQuery($this->data['split'], $indexTable);
     $sphinx->ResetGroupBy();
     $sphinx->SetGroupBy('feature', SPH_GROUPBY_ATTR, "@count desc");
     $sphinx->SetLimits(0, 20, 20);
     $sphinx->AddQuery($this->data['split'], $indexTable);
     $sphinx->ResetGroupBy();
     if (isset($this->data["pid"]) && $this->data["pid"] > 0) {
         $sphinx->SetLimits(0, 1, 1);
     } else {
         $sphinx->SetLimits(0, 20, 20);
     }
     $sphinx->SetGroupBy('brand', SPH_GROUPBY_ATTR, "@count desc");
     $sphinx->AddQuery($this->data['split'], $indexTable);
     if (!empty($this->data['province'])) {
         //市
         $sphinx->ResetGroupBy();
         $sphinx->SetLimits(0, 20, 20);
         $sphinx->SetGroupBy('city', SPH_GROUPBY_ATTR, "@count desc");
         $sphinx->AddQuery($this->data['split'], $indexTable);
     } else {
         //省
         $sphinx->ResetGroupBy();
         $sphinx->SetLimits(0, 20, 20);
         $sphinx->SetGroupBy('province', SPH_GROUPBY_ATTR, "@count desc");
         $sphinx->AddQuery($this->data['split'], $indexTable);
     }
     $batchResult = $sphinx->RunQueries();
     $error = $sphinx->getLastError();
     if ($error) {
         $result['data'] = array();
         $result['property'] = '[]';
         $result['brand'] = '[]';
         $result['city'] = '[]';
         $result['province'] = '[]';
         $result['total_found'] = 0;
         $result['time'] = 0;
         $result['split'] = $this->data['split'];
         return $result['data'];
     }
     $result = array();
     if (is_array($batchResult) && count($batchResult) > 0) {
         $result['data'] = $batchResult[0];
         $result['property'] = isset($batchResult[1]) ? $batchResult[1] : array();
         $result['brand'] = isset($batchResult[2]) ? $batchResult[2] : array();
         if (!empty($this->data['province'])) {
             $result['city'] = isset($batchResult[3]) ? $batchResult[3] : array();
         } else {
             $result['province'] = isset($batchResult[3]) ? $batchResult[3] : array();
         }
     }
     $resData = array();
     if (isset($result['data']['matches'])) {
         foreach ($result['data']['matches'] as $k => $v) {
             $resData[] = array($k, $v['attrs']['cid']);
         }
     }
     $result['total_found'] = $result['data']['total_found'];
     $result['time'] = $result['data']['time'];
     $result['split'] = $this->data['split'];
     $result['data'] = $resData;
     if (!empty($result['province'])) {
         $province = $this->fomatSphinxData($result['province']);
         $result['province'] = json_encode($province);
     } else {
         $result['province'] = '[]';
     }
     if (!empty($result['city'])) {
         $city = $this->fomatSphinxData($result['city']);
         $result['city'] = json_encode($city);
     } else {
         $result['city'] = '[]';
     }
     if (!empty($result['brand'])) {
         $brand = $this->fomatSphinxData($result['brand']);
         $result['brand'] = json_encode($brand);
     } else {
         $result['brand'] = '[]';
     }
     if (!empty($result['property'])) {
         $property = $this->fomatSphinxData($result['property']);
         $result['property'] = json_encode($property);
     } else {
         $result['property'] = '[]';
     }
     return $result;
 }
예제 #12
0
function sphinxList($filterArr, $page = 0)
{
    $result = array('data' => array(), 'cate4' => array(), 'property' => array(), 'province' => array(), 'city' => array(), 'brand' => array(), 'total_found' => 0, 'time' => 0);
    $perpage = isset($filterArr['perpage']) && $filterArr['perpage'] ? $filterArr['perpage'] : 20;
    $sphinxConfig = array('host' => '172.17.17.105', 'port' => 9020);
    $sphinx = new \SphinxClient();
    $sphinx->SetServer($sphinxConfig['host'], intval($sphinxConfig['port']));
    if (isset($filterArr["has_children"]) && $filterArr["has_children"] == 1) {
        $indexTable = "product_distri_special";
    } elseif (isset($filterArr['cate1']) && $filterArr['cate1']) {
        $indexTable = "product_distri_" . $filterArr["cate1"];
    } else {
        $indexTable = "product_m_distri";
    }
    $gcdweight = "weight()+IF(id>900000000, tradenum*100, 0)+inquirynum*20+star*2+basescore*5+creditscore+IF(is_op=1, all_uv*10+all_pv, 0)+IF(id>900000000, weight()*0.1, 0) as gcpdweight";
    if (isset($filterArr["has_children"]) && $filterArr["has_children"] == 1) {
        $sphinx->SetSelect("id, cid, brand, cate4, feature, province, city, {$gcdweight}");
    } else {
        $sphinx->SetSelect("id, cid, brand, feature, province, city, {$gcdweight}");
    }
    /**************************************** 过滤模块 ******************************************/
    /* 分类过滤 */
    if (isset($filterArr['cate3']) && isset($filterArr['cate2to3'])) {
        $sphinx->SetFilter('cate2', array(intval($filterArr["cate3"])), false);
    } elseif (isset($filterArr['cate3'])) {
        $sphinx->SetFilter('cate3', array(intval($filterArr["cate3"])), false);
    }
    /* 是否通过工厂认证 */
    if (isset($filterArr['filters']['iscertify']) && $filterArr['filters']['iscertify'] > 0) {
        $sphinx->SetFilter('is_gccertify', array($filterArr['filters']['iscertify']), false);
    }
    /* 是否显示价格 */
    if (isset($filterArr['filters']['isprice']) && $filterArr['filters']['isprice'] > 0) {
        $sphinx->SetFilterRange('price', 1, 9999999, false);
    }
    /* 省过滤 */
    if (!empty($filterArr['filters']['province']) && is_numeric($filterArr['filters']['province'])) {
        $sphinx->SetFilter('province', array(intval($filterArr['filters']['province'])), false);
    }
    /* 市过滤 */
    if (!empty($filterArr['filters']['city']) && is_numeric($filterArr['filters']['city'])) {
        $sphinx->SetFilter('city', array(intval($filterArr['filters']['city'])), false);
    }
    /* 品牌过滤 */
    if (isset($filterArr['filters']['brand']) && $filterArr['filters']['brand'] > 0) {
        $sphinx->SetFilter('brand', array(intval($filterArr['filters']['brand'])), false);
    }
    /* 属性过滤 */
    if (isset($filterArr['filters']['feature']) && $filterArr['filters']['feature']) {
        $featureArr = explode('_', $filterArr['filters']['feature']);
        foreach ($featureArr as $value) {
            $sphinx->SetFilter('feature', array(intval($value)), false);
        }
    }
    /***************************************** 过滤结束 ******************************************/
    /***************************************** 排序 *********************************************/
    $sort = isset($filterArr['orders']['sort']) ? $filterArr['orders']['sort'] : '';
    if ($sort && $sort == 1) {
        //销量倒叙排列
        $sphinx->SetSortMode(SPH_SORT_EXTENDED, 'tradenum DESC');
    } elseif ($sort && $sort == 2) {
        //热度倒叙排列
        $sphinx->SetSortMode(SPH_SORT_EXTENDED, 'visitnum DESC');
    } elseif ($sort && $sort == 3) {
        //价格正序排列
        $sphinx->SetSortMode(SPH_SORT_EXTENDED, 'price ASC');
    } elseif ($sort && $sort == 4) {
        //价格倒序排列
        $sphinx->SetSortMode(SPH_SORT_EXTENDED, 'price DESC');
    } elseif ($sort && $sort == 5) {
        //返积分正序排列
        $sphinx->SetSortMode(SPH_SORT_EXTENDED, 'integral DESC');
    } else {
        //默认综合排序
        $sphinx->SetSortMode(SPH_SORT_EXTENDED, 'gcpdweight DESC');
    }
    /*************************************** 排序结束 ********************************************/
    /* limit限制 */
    $sphinx->SetLimits(0, $perpage * 10, $perpage * 10);
    $sphinx->AddQuery("", $indexTable);
    /**************************************** 开始并发查询 **************************************/
    /*#############  属性  ###############*/
    $sphinx->ResetGroupBy();
    $sphinx->SetGroupBy('feature', SPH_GROUPBY_ATTR, "@count desc");
    $sphinx->SetLimits(0, 200, 200);
    $sphinx->AddQuery("", $indexTable);
    /*#############  省  ###############*/
    $sphinx->ResetGroupBy();
    $sphinx->SetGroupBy('province', SPH_GROUPBY_ATTR, "@count desc");
    $sphinx->SetLimits(0, 20, 20);
    $sphinx->AddQuery("", $indexTable);
    /*#############  市  ###############*/
    $sphinx->ResetGroupBy();
    $sphinx->SetGroupBy('city', SPH_GROUPBY_ATTR, "@count desc");
    $sphinx->SetLimits(0, 20, 20);
    $sphinx->AddQuery("", $indexTable);
    /*#############  品牌  ###############*/
    $sphinx->ResetGroupBy();
    $sphinx->SetGroupBy('brand', SPH_GROUPBY_ATTR, "@count desc");
    $sphinx->SetLimits(0, 20, 20);
    $sphinx->AddQuery("", $indexTable);
    /*#############  4级分类  ###############*/
    //有子分类使用特权产品索引,可以对cate4排序
    if (isset($filterArr["has_children"]) && $filterArr["has_children"] == 1) {
        $sphinx->ResetGroupBy();
        $sphinx->SetGroupBy('cate4', SPH_GROUPBY_ATTR, "@count desc");
        $sphinx->SetLimits(0, 20, 20);
        $sphinx->AddQuery("", $indexTable);
    }
    /*#############  执行  ###############*/
    $batchResult = $sphinx->RunQueries();
    /**************************************** 完成并发查询 **************************************/
    /**************************************** 错误验证 **************************************/
    $error = $sphinx->getLastError();
    if ($error) {
        return $result;
    }
    /**************************************** 结果抽取处理 **************************************/
    if (is_array($batchResult) && count($batchResult) > 0) {
        $result['data'] = $batchResult[0];
        $result['property'] = isset($batchResult[1]) ? $batchResult[1] : array();
        $result['province'] = isset($batchResult[2]) ? $batchResult[2] : array();
        $result['city'] = isset($batchResult[3]) ? $batchResult[3] : array();
        $result['brand'] = isset($batchResult[4]) ? $batchResult[4] : array();
        $result["cate4"] = isset($batchResult[5]) ? $batchResult[5] : array();
    } else {
        return $result;
    }
    $resData = array();
    if (!isset($result['data']['matches'])) {
        $result['data']['matches'] = array();
    }
    foreach ($result['data']['matches'] as $k => $v) {
        $resData[] = array($k, $v['attrs']['cid']);
    }
    $result['total_found'] = $result['data']['total_found'];
    $result['time'] = $result['data']['time'];
    $result['data'] = $resData;
    $result['data'] = sortData($result['data']);
    if ($page > 0) {
        $result["data"] = array_slice($result["data"], ($page - 1) * $perpage, $perpage);
    }
    $result["property"] = !empty($result['property']) ? fomatSphinxData($result['property']) : array();
    $result["province"] = !empty($result['province']) ? fomatSphinxData($result['province']) : array();
    $result["city"] = !empty($result['city']) ? fomatSphinxData($result['city']) : array();
    $result["brand"] = !empty($result['brand']) ? fomatSphinxData($result['brand']) : array();
    $result["cate4"] = !empty($result['cate4']) ? fomatSphinxData($result['cate4']) : array();
    $result["property"] = json_encode($result["property"], JSON_UNESCAPED_UNICODE);
    $result["province"] = json_encode($result["province"], JSON_UNESCAPED_UNICODE);
    $result["city"] = json_encode($result["city"], JSON_UNESCAPED_UNICODE);
    $result["brand"] = json_encode($result["brand"], JSON_UNESCAPED_UNICODE);
    $result["cate4"] = json_encode($result["cate4"], JSON_UNESCAPED_UNICODE);
    return $result;
}
예제 #13
0
 /**
  * 功能描述  获取筛选
  * @author 吕小虎
  * @datetime ${DATE} ${TIME}
  * @version
  * @param
  * @return
  */
 public function dataFilterFromSphinx($data)
 {
     $this->data = $data;
     //分词
     $this->data['split'] = \Xz\Func\Common\Tools::curlGetContentMs($this->di['config']->base->split . '/wd/' . urlencode($this->data['wd']), 50);
     if (empty($this->data['split'])) {
         $this->data['split'] = $data['wd'];
     }
     $sphinxConfig = $this->di["config"]["combusinessearchsphinxdist"];
     $sphinx = new \SphinxClient();
     $sphinx->SetServer($sphinxConfig['host'], intval($sphinxConfig['port']));
     $indexTable = $sphinxConfig->table;
     $fieldStr = isset($data['field']) ? implode(',', $data['field']) : "id, comname, legal, areaid, uptime";
     $sphinx->SetSelect($fieldStr);
     //一级分类筛选
     if (!empty($this->data['cate1id']) && intval($this->data['cate1id']) > 0) {
         $sphinx->AddQuery('@cate1', $this->data['cate1id'], $indexTable);
     }
     //二级分类筛选
     if (!empty($this->data['cate2id']) && intval($this->data['cate2id']) > 0) {
         $sphinx->AddQuery('@cate2', $this->data['cate2id'], $indexTable);
     }
     //地区筛选
     if (!empty($this->data['areaid']) && intval($this->data['areaid']) > 0) {
         if ($this->data['areaid'] % 10000 == 0) {
             $start = intval($this->data['areaid'] / 10000) * 10000;
             $end = $start + 9999;
             $sphinx->SetFilterRange('areaid', $start, $end, false);
         } elseif ($this->data['areaid'] % 100 == 0) {
             $start = intval($this->data['areaid'] / 100) * 100;
             $end = $start + 99;
             $sphinx->SetFilterRange('areaid', $start, $end, false);
         } else {
             $sphinx->SetFilter('areaid', intval($this->data['areaid']));
         }
     }
     //企业名称和法人搜索
     $sphinx->SetLimits(0, 1, 1);
     $sphinx->AddQuery('@(comname,legal)' . $this->data['split'], $indexTable);
     $sphinx->ResetGroupBy();
     //分类
     $sphinx->SetLimits(0, 20, 20);
     $sphinx->ResetGroupBy();
     $sphinx->SetGroupBy('cate1', SPH_GROUPBY_ATTR, "@count desc");
     $sphinx->AddQuery('@(comname,legal)' . $this->data['split'], $indexTable);
     $sphinx->SetLimits(0, 20, 20);
     $sphinx->ResetGroupBy();
     $sphinx->SetGroupBy('cate2', SPH_GROUPBY_ATTR, "@count desc");
     $sphinx->AddQuery('@(comname,legal)' . $this->data['split'], $indexTable);
     //地区
     $sphinx->SetLimits(0, 35, 20);
     $sphinx->ResetGroupBy();
     $sphinx->SetGroupBy('areaid', SPH_GROUPBY_ATTR, "@count desc");
     $sphinx->AddQuery('@(comname,legal)' . $this->data['split'], $indexTable);
     $result = array();
     $batchResult = $sphinx->RunQueries();
     //        print_r($batchResult);
     $error = $sphinx->getLastError();
     if ($error) {
         $result = array('cate1' => array(), 'cate2' => array(), 'areaid' => array());
     } else {
         //            $result['data'] = $batchResult[0];
         $result['cate1'] = array();
         if (isset($batchResult[1]['matches']) && is_array($batchResult[1]['matches']) && !empty($batchResult[1]['matches'])) {
             foreach ($batchResult[1]['matches'] as $value) {
                 $result['cate1'][$value['attrs']['@groupby']] = $value['attrs']['@count'];
             }
         }
         $result['cate2'] = array();
         if (isset($batchResult[2]['matches']) && is_array($batchResult[2]['matches']) && !empty($batchResult[2]['matches'])) {
             foreach ($batchResult[2]['matches'] as $value) {
                 $result['cate2'][$value['attrs']['@groupby']] = $value['attrs']['@count'];
             }
         }
         $result['areaid'] = array();
         if (isset($batchResult[3]['matches']) && is_array($batchResult[3]['matches']) && !empty($batchResult[3]['matches'])) {
             foreach ($batchResult[3]['matches'] as $value) {
                 $result['areaid'][$value['attrs']['@groupby']] = $value['attrs']['@count'];
             }
         }
     }
     return $result;
 }
예제 #14
0
 /**
  * RunQueries() + validate.
  *
  * - Single Query: Resultados da Query
  *
  * - Multi Query:  Array de Resultados das Querys
  *
  * Formato de cada Resultado:
  *
  * <code>
  * //Results
  * array(
  *     array(
  *         'id'     => 12345,
  *         'weight' => 30,
  *         'attrs'  => array(...)
  *     ),
  *     array(
  *         'id'     => 23456,
  *         'weight' => 20,
  *         'attrs'  => array(...)
  *     ),
  *     ...
  * );
  * </code>
  *
  * @param \SphinxClient $sphinxClient
  *
  * @throws \Exception
  *
  * @return array
  */
 protected function getResult(\SphinxClient $sphinxClient)
 {
     $result = $sphinxClient->RunQueries();
     if (false === $result) {
         throw new \Exception($sphinxClient->getLastError());
     }
     if ($sphinxClient->GetLastWarning()) {
         throw new \Exception($sphinxClient->GetLastWarning());
     }
     if (false === $result) {
         throw new \Exception($sphinxClient->getLastError());
     }
     if ($sphinxClient->GetLastWarning()) {
         throw new \Exception($sphinxClient->GetLastWarning());
     }
     //Suporte ao formato inicial de unica query
     if (count($result) === 1) {
         return current($result);
     }
     return $result;
 }