private function get_sugg_trigrams($word, SearchEngineOptions $options) { $trigrams = $this->BuildTrigrams($word); $query = "\"{$trigrams}\"/1"; $len = strlen($word); $this->resetSphinx(); $this->suggestionClient->SetMatchMode(SPH_MATCH_EXTENDED2); $this->suggestionClient->SetRankingMode(SPH_RANK_WORDCOUNT); $this->suggestionClient->SetFilterRange("len", $len - 2, $len + 4); $this->suggestionClient->SetSortMode(SPH_SORT_EXTENDED, "@weight DESC"); $this->suggestionClient->SetLimits(0, 10); $indexes = []; foreach ($options->getDataboxes() as $databox) { $indexes[] = 'suggest' . $this->CRCdatabox($databox); } $index = implode(',', $indexes); $res = $this->suggestionClient->Query($query, $index); if ($this->suggestionClient->Status() === false) { return []; } if (!$res || !isset($res["matches"])) { return []; } $words = []; foreach ($res["matches"] as $match) { $words[] = $match['attrs']['keyword']; } return $words; }
protected function applyRanges(array $ranges, $exclude = false) { $exclude = (bool) $exclude; foreach ($ranges as $field => $range) { $isFloat = is_float($range['max']) || is_float($range['min']); if ($isFloat) { $this->sphinxClient->SetFilterRange($field, (double) $range['min'], (double) $range['max'], $exclude); } else { $this->sphinxClient->SetFilterRange($field, (int) $range['min'], (int) $range['max'], $exclude); } } }
function MakeSuggestion($keyword) { $trigrams = BuildTrigrams($keyword); $query = "\"{$trigrams}\"/1"; $len = strlen($keyword); $delta = LENGTH_THRESHOLD; $cl = new SphinxClient(); $cl->SetMatchMode(SPH_MATCH_EXTENDED2); $cl->SetRankingMode(SPH_RANK_WORDCOUNT); $cl->SetFilterRange("len", $len - $delta, $len + $delta); $cl->SetSelect("*, @weight+{$delta}-abs(len-{$len}) AS myrank"); $cl->SetSortMode(SPH_SORT_EXTENDED, "myrank DESC, freq DESC"); $cl->SetArrayResult(true); // pull top-N best trigram matches and run them through Levenshtein $cl->SetLimits(0, TOP_COUNT); $res = $cl->Query($query, "suggest"); if (!$res || !$res["matches"]) { return false; } if (SUGGEST_DEBUG) { print "--- DEBUG START ---\n"; foreach ($res["matches"] as $match) { $w = $match["attrs"]["keyword"]; $myrank = @$match["attrs"]["myrank"]; if ($myrank) { $myrank = ", myrank={$myrank}"; } // FIXME? add costs? // FIXME! does not work with UTF-8.. THIS! IS!! PHP!!! $levdist = levenshtein($keyword, $w); print "id={$match['id']}, weight={$match['weight']}, freq={$match[attrs][freq]}{$myrank}, word={$w}, levdist={$levdist}\n"; } print "--- DEBUG END ---\n"; } // further restrict trigram matches with a sane Levenshtein distance limit foreach ($res["matches"] as $match) { $suggested = $match["attrs"]["keyword"]; if (levenshtein($keyword, $suggested) <= LEVENSHTEIN_THRESHOLD) { return $suggested; } } return $keyword; }
public function getResultByTag($keyword = "", $offset = 0, $limit = 0, $searchParams = array()) { $sphinx = $this->config->item('sphinx'); $query = array(); $cl = new SphinxClient(); $cl->SetServer($sphinx['ip'], $sphinx['port']); // 注意这里的主机 $cl->SetConnectTimeout($sphinx['timeout']); $cl->SetArrayResult(true); // $cl->SetIDRange(89,90);//过滤ID if (isset($searchParams['provice_sid']) && $searchParams['provice_sid']) { $cl->setFilter('provice_sid', array($searchParams['provice_sid'])); } if (isset($searchParams['city_sid']) && $searchParams['city_sid']) { $cl->setFilter('city_sid', array($searchParams['city_sid'])); } if (isset($searchParams['piccode']) && $searchParams['piccode']) { $cl->setFilter('piccode', array($searchParams['piccode'])); } if (isset($searchParams['recent']) && $searchParams['recent']) { $cl->SetFilterRange('createtime', time() - 86400 * 30, time()); //近期1个月 } if (isset($searchParams['searchtype']) && $searchParams['searchtype']) { //精确:模糊 $searchtype = SPH_MATCH_ALL; } else { $searchtype = SPH_MATCH_ANY; } $cl->SetLimits($offset, $limit); $cl->SetMatchMode($searchtype); // 使用多字段模式 $cl->SetSortMode(SPH_SORT_EXTENDED, "@weight desc,@id desc"); $index = "*"; $query = $cl->Query($keyword, $index); $cl->close(); return $query; }
function actionIndex() { $this->_pathway->addStep('检索下载'); $type = $this->_context->type; if ($type == 1) { $this->_pathway->addStep('视频资料'); } else { if ($type == 2) { $this->_pathway->addStep('音频资料'); } else { if ($type == 3) { $this->_pathway->addStep('图片资料'); } else { if ($type == 4) { $this->_pathway->addStep('富媒体资料'); } else { $type = 0; } } } } $this->_view['type'] = $type; require Q::ini('appini/search/sphinxApi'); $host = Q::ini('appini/search/sphinxHost'); $port = Q::ini('appini/search/sphinxPort'); $limit = Q::ini('appini/search/sphinxLimit'); $level = $this->_view['currentUser']['level_id']; $group_id = $this->_view['currentUser']['group_id']; $page = intval($this->_context->page); if ($page < 1) { $page = 1; } $query = $this->_view['query'] = $this->_context->query; $s = new SphinxClient(); $s->SetServer($host, $port); $s->SetConnectTimeout(10); $s->SetWeights(array(100, 1)); if ($type >= 1 && $type <= 4) { $s->SetFilter('type', array($type)); } $s->SetFilter('status', array(2)); //0:新节目;1:待审核;2:已发布;3:打回;4:删除. $s->SetFilterRange('level', 0, $level); $s->SetLimits(($page - 1) * $limit, $limit, 1000); $s->SetArrayResult(true); $s->SetMatchMode(SPH_MATCH_EXTENDED); //设置匹配模式为Sphinx内部语言表达式 $s->SetSortMode(SPH_SORT_EXPR, '@id'); //设置排序模式 $result = $s->Query("{$query} @groups '(,{$group_id},)|(all)'"); if ($result) { //获得文件 if (isset($result['matches'])) { $ids = array(); foreach ($result['matches'] as $v) { $ids[] = $v['id']; } $files = Files::find('id in (?)', $ids)->order('id desc')->getAll(); $this->_view['files'] = $files; } $result['start'] = ($page - 1) * $limit + 1 > $result['total'] ? $result['total'] : ($page - 1) * $limit + 1; $result['end'] = $result['start'] + $limit - 1 > $result['total'] ? $result['total'] : $result['start'] + $limit - 1; $this->_view['result'] = $result; //生成页码控制 $pagination = array(); $pagination['record_count'] = $result['total']; $pagination['page_count'] = ceil($result['total'] / $limit); $pagination['first'] = 1; $pagination['last'] = $pagination['page_count']; if ($pagination['last'] < $pagination['first']) { $pagination['last'] = $pagination['first']; } if ($page >= $pagination['page_count'] + 1) { $page = $pagination['last']; } if ($page < 1) { $page = $pagination['first']; } if ($page < $pagination['last'] - 1) { $pagination['next'] = $page + 1; } else { $pagination['next'] = $pagination['last']; } if ($page > 1) { $pagination['prev'] = $page - 1; } else { $pagination['prev'] = $pagination['first']; } $pagination['current'] = $page; $pagination['page_size'] = $limit; $pagination['page_base'] = 1; $this->_view['pagination'] = $pagination; } // $categoryId = $this->_context->category_id; // $categoryId = isset($categoryId) ? $categoryId : 1; // $category = Category::find()->getById($categoryId); // $this->_view['category'] = $category; // $categoryIds = Category::getChildrenIds($categoryId); // if(count($categoryIds)){//所有编目文件 // // 分页查询内容列表 // $page = intval($this->_context->page); // if ($page < 1) $page = 1; // $select = Files::find('category_id in (?) and type=? and upload_username=? and status=2 and (groups=\'\' or groups like \'%,?,%\') and level <= ?', $categoryIds, $type, $this->_view['currentUser']['username'], $this->_view['currentUser']['group_id'], $this->_view['currentUser']['level_id'])->order('upload_at desc'); // $select->limitPage($page, 12); // // 将分页信息和查询到的数据传递到视图 // $this->_view['pagination'] = $select->getPagination(); // $this->_view['files'] = $select->getAll(); // } }
<?php require "sphinxapi.php"; $cl = new SphinxClient(); $cl->SetFilterRange('attr', 10, 20, true); $cl->Query('query');
/** * 功能描述 获取筛选 * @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; }
/** * Applies ranged filter. * * @param \SphinxClient $sphinxClient * * @return static * @throws LogicException */ protected function applyRangedFilter(\SphinxClient $sphinxClient) { if ($this->getConvertedDefaultMin() > $this->getConvertedDefaultMax()) { throw new LogicException('Default min value must not be greater than default max value.'); } $bounds = $this->getBoundsForRangedFilter(); $sphinxClient->SetFilterRange($this->getFieldName(), $bounds[0], $bounds[1], $this->isExclude()); return $this; }
$groupby = $args[++$i]; } else { if ($arg == "-gs" || $arg == "--groupsort") { $groupsort = $args[++$i]; } else { if ($arg == "-d" || $arg == "--distinct") { $distinct = $args[++$i]; } else { if ($arg == "-l" || $arg == "--limit") { $limit = (int) $args[++$i]; } else { if ($arg == "--select") { $select = $args[++$i]; } else { if ($arg == "-fr" || $arg == "--filterrange") { $cl->SetFilterRange($args[++$i], $args[++$i], $args[++$i]); } else { if ($arg == "-r") { $arg = strtolower($args[++$i]); if ($arg == "bm25") { $ranker = SPH_RANK_BM25; } if ($arg == "none") { $ranker = SPH_RANK_NONE; } if ($arg == "wordcount") { $ranker = SPH_RANK_WORDCOUNT; } if ($arg == "fieldmask") { $ranker = SPH_RANK_FIELDMASK; }
/** * 关键词获取普通产品获取相关分类 * @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; }
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; }
function sphinx_search_action($arrSearch) { global $PHORUM; // No pecl class, try php version if (!class_exists('SphinxClient')) { // loads from php include_path require_once 'sphinxapi.php'; } // these are the index-names set in sphinx.conf - one for searching messages, the other for searching by authors only // both contain an additional index for the deltas - changes done after the last full reindex $index_name_msg = 'phorum5_msg_d phorum5_msg'; $index_name_author = 'phorum5_author phorum5_author_d'; // excerpts_index is just one index as that function only accepts one, it used for determining charsets / mapping tables, nothing more $excerpts_index = 'phorum5_msg'; $index = $index_name_msg; if ($arrSearch['match_type'] == 'ALL') { $match_mode = SPH_MATCH_ALL; } elseif ($arrSearch['match_type'] == 'ANY') { $match_mode = SPH_MATCH_ANY; } elseif ($arrSearch['match_type'] == 'PHRASE') { $match_mode = SPH_MATCH_PHRASE; } elseif ($arrSearch['match_type'] == 'AUTHOR') { $match_mode = SPH_MATCH_PHRASE; $index = $index_name_author; } else { // Return search control to Phorum in case the search type isn't handled by the module. return $arrSearch; } if (empty($arrSearch['search']) && !empty($arrSearch['author'])) { $arrSearch['search'] = $arrSearch['author']; $index = $index_name_author; } $sphinx = new SphinxClient(); $sphinx->SetServer($PHORUM['mod_sphinx_search']['hostname'], $PHORUM['mod_sphinx_search']['port']); $sphinx->SetMatchMode($match_mode); // set the limits for paging $sphinx->SetLimits($arrSearch['offset'], $arrSearch['length']); // set the timeframe to search if ($arrSearch['match_dates'] > 0) { $min_ts = time() - 86400 * $arrSearch['match_dates']; $max_ts = time(); $sphinx->SetFilterRange('datestamp', $min_ts, $max_ts); } // Check what forums the active Phorum user can read. $allowed_forums = phorum_api_user_check_access(PHORUM_USER_ALLOW_READ, PHORUM_ACCESS_LIST); // If the user is not allowed to search any forum or the current // active forum, then return the emtpy search results array. if (empty($allowed_forums) || $PHORUM['forum_id'] > 0 && !in_array($PHORUM['forum_id'], $allowed_forums)) { $arrSearch['results'] = array(); $arrSearch['totals'] = 0; $arrSearch['continue'] = 0; $arrSearch['raw_body'] = 1; return $arrSearch; } // Prepare forum_id restriction. $search_forums = array(); foreach (explode(',', $arrSearch['match_forum']) as $forum_id) { if ($forum_id == 'ALL') { $search_forums = $allowed_forums; break; } if (isset($allowed_forums[$forum_id])) { $search_forums[] = $forum_id; } } $sphinx->SetFilter('forum_id', $search_forums); // set the sort-mode $sphinx->SetSortMode(SPH_SORT_ATTR_DESC, 'datestamp'); // do the actual query $results = $sphinx->Query($arrSearch['search'], $index); $res = $sphinx->GetLastWarning(); if ($res) { error_log("sphinx_search.php: WARNING: {$res}"); } $res = $sphinx->GetLastError(); if ($res) { error_log("sphinx_search.php: ERROR: {$res}"); } // if no messages were found, then return empty handed. if (!isset($results['matches'])) { $arrSearch['results'] = array(); $arrSearch['totals'] = 0; $arrSearch['continue'] = 0; $arrSearch['raw_body'] = 1; return $arrSearch; } $search_msg_ids = $results['matches']; // get the messages we found $found_messages = phorum_db_get_message(array_keys($search_msg_ids), 'message_id', true); // sort them in reverse order of the message_id to automagically sort them by date desc this way krsort($found_messages); reset($found_messages); // prepare the array for building highlighted excerpts $docs = array(); foreach ($found_messages as $id => $data) { // remove hidden text in the output - only added by the hidden_msg module $data['body'] = preg_replace("/(\\[hide=([\\#a-z0-9]+?)\\](.+?)\\[\\/hide\\])/is", '', $data['body']); $docs[] = htmlspecialchars(phorum_strip_body($data['body'])); } $words = ''; if (!empty($results['words'])) { $words = implode(' ', array_keys($results['words'])); } $opts = array('chunk_separator' => ' [...] '); // build highlighted excerpts $highlighted = $sphinx->BuildExcerpts($docs, $excerpts_index, $words, $opts); $res = $sphinx->GetLastWarning(); if ($res) { error_log("sphinx_search.php: WARNING: {$res}"); } $res = $sphinx->GetLastError(); if ($res) { error_log("sphinx_search.php: ERROR: {$res}"); } $cnt = 0; foreach ($found_messages as $id => $content) { $found_messages[$id]['short_body'] = $highlighted[$cnt]; $cnt++; } $arrSearch['results'] = $found_messages; // we need the total results $arrSearch['totals'] = $results['total_found']; if ($arrSearch['totals'] > 1000) { $arrSearch['totals'] = 1000; } // don't run the default search $arrSearch['continue'] = 0; // tell it to leave the body alone $arrSearch['raw_body'] = 1; return $arrSearch; }
<?php require "sphinxapi.php"; $cl = new SphinxClient(); $cl->SetFilterRange('attr1', -10, 20); $cl->SetFilterRange('attr2', -1099511627770, 1099511627780); $cl->Query('query');
/** * Calls SphinxClient::SetFilterRange * @param $attribute * @param $min * @param $max * @param bool $exclude */ public function setFilterRange($attribute, $min, $max, $exclude = false) { $this->client->SetFilterRange($attribute, $min, $max, $exclude); }
/** * 特殊的搜索,用于供应商查询收录,产品查询收录等 * * @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; }
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; }
<?php require "sphinxapi.php"; $cl = new SphinxClient(); $cl->SetFilterRange('attr2', 30, 40); $cl->SetFilterRange('attr1', 10, 20); $cl->Query('query');
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; }
function range($attribute, $min, $max, $exclude = FALSE) { $this->sphinx->SetFilterRange($attribute, $min, $max, $exclude); return $this; }
<?php require "spec/fixtures/sphinxapi.php"; $cl = new SphinxClient(); $cl->SetFilterRange('attr1', -10, 20); $cl->SetFilterRange('attr2', '-1099511627770', '1099511627780'); $cl->Query('query');
private function receiveText($object) { $keyword = trim($object->Content); //多客服人工回复模式 if (strstr($keyword, "您好") || strstr($keyword, "你好") || strstr($keyword, "在吗")) { // $result = $this->transmitService($object); $content = $this->get_rebot($keyword); $content = $content . " [跟我说话的时候,请加上 @赛酷 ]"; } else { if (strstr($keyword, "@赛酷")) { //接入机器人 $keyword = str_replace("@赛酷", "", $keyword); $content = $this->get_rebot($keyword); } else { if (strstr($keyword, "多图文")) { $content = array(); $content[] = array("Title" => "视频:门里门外", "Description" => "常言道:家家有本难念的经", "PicUrl" => "http://img1.saiku.com.cn/static/images/recommend/20140707093925_764.jpg", "Url" => "http://www.saiku.com.cn/v/Ja3.html"); $content[] = array("Title" => "视频:《寻梅》", "Description" => "梅飘香,雪皑皑,寻香觅花花未开,伫立风中默等待", "PicUrl" => "http://img1.saiku.com.cn/static/images/recommend/20140707094122_926.jpg", "Url" => "http://www.saiku.com.cn/v/nqa.html"); $content[] = array("Title" => "忽然之间-莫文蔚- 天梯:赛酷'唱'响未来歌唱大赛", "Description" => "哈哈第一次进录音棚录制了一首很喜欢的歌:忽然之间。希望大家喜欢~", "PicUrl" => "http://img1.saiku.com.cn/thumb/d/images/video/20140701/825/1,h_150,w_220.jpg", "Url" => "http://www.saiku.com.cn/v/sing/eDn.html"); } else { if (strstr($keyword, "图文") || strstr($keyword, "单图文")) { $content = array(); $content[] = array("Title" => "忽然之间-莫文蔚- 天梯:赛酷'唱'响未来歌唱大赛 ", "Description" => "哈哈第一次进录音棚录制了一首很喜欢的歌:忽然之间。希望大家喜欢~", "PicUrl" => "http://img1.saiku.com.cn/thumb/d/images/video/20140701/825/1,h_150,w_220.jpg", "Url" => "http://www.saiku.com.cn/v/sing/eDn.html"); } else { if (stristr($keyword, "tp#")) { //星光少年-作品投票 $regex = '/^tp#([\\d]+)$/i'; $matches = array(); $wid = 0; if (preg_match($regex, $keyword, $matches)) { $wid = intval($matches[1]); } if ($wid > 0) { $this->load->model('youngstar/youngstar_vote_model', 'youngstar_vote_m'); $wx_username = $this->username; $log_id = $this->youngstar_vote_m->init_wx_vote($wx_username, $wid); $post = array('weixin' => $wx_username, 'wid' => $wid); $res = rcurl(self::WWW_URL . '/youngstar/weixin/vote', $post); $res = json_decode($res, true); if (is_array($res)) { if ($res['status'] > 0) { //投票成功 $content = "投票成功!"; } else { $content = $res['msg']; } } else { $content = "请稍后...投票ING."; } } else { $content = "你投票的编辑文字有误,请重新发送。如tp#199."; } } else { //作品搜索 $this->load->helper('sphinxapi_helper'); $cl = new SphinxClient(); $cl->SetServer(SPHINX_HOST, SPHINX_PORT); $cl->SetMatchMode(SPH_MATCH_BOOLEAN); #设置全文检索模式 $word = $keyword; #关键词 $result = array(); $cl->SetFilter('is_del', array(0)); #false允许true拒绝 $cl->SetFilter('type', array(1)); $cl->SetFilterRange('addtime', $min = 0, time(), $exclude = false); $cl->SetLimits(0, 5, 100); $ret = $cl->Query("@(title,description) {$word} ", "works_index"); $content = array(); if ($ret['total']) { $this->load->model('video_mod'); $idarr = array(); foreach ($ret['matches'] as $id => $info) { array_push($idarr, $info['attrs']['wid']); } $ids = implode("','", $idarr); $where = " WHERE v.id in ('{$ids}')"; $video = $this->video_mod->getDataAll($where, 0, 5, ' v.`adddate` desc '); if (!empty($video)) { foreach ($video as $v) { $params = array('id' => $v['id']); if (isset($v['path'])) { $params['path'] = $v['path']; } $img_params = array('pic_name' => '1.jpg', 'pic_path' => $v['pic_path'], 'w' => 220, 'h' => 150); $content[] = array("Title" => $v['title'] . "." . $v['longtitle'], "Description" => $v['description'], "PicUrl" => img_url_path('video', $img_params), "Url" => $this->config->item("base_url") . build_uri('video', $params)); } } } } } } } if (is_array($content)) { if (isset($content[0]['PicUrl'])) { $result = $this->transmitNews($object, $content); } else { if (isset($content['MusicUrl'])) { $result = $this->transmitMusic($object, $content); } } } else { $result = $this->transmitText($object, $content); } } return $result; }
/** * 从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); }
<?php require "sphinxapi.php"; $cl = new SphinxClient(); $cl->SetFilterRange('attr1', 10, 20, true); $cl->SetFilter('attr3', array(30, 40, 50)); $cl->SetFilterRange('attr1', 60, 70); $cl->SetFilter('attr2', array(80, 90, 100), true); $cl->Query('query');
} if (isset($_REQUEST['language'])) { $r2 = $mdb->queryFirstRow("SELECT id, name FROM media_language WHERE name=%s", $_REQUEST["language"]); $language = $r2["id"]; //set language if ($language == "") { echo json_encode(array("result" => null, "status" => false, "error" => "请求的语种不存在")); exit; } $sphinx->SetFilter('language', array($language)); } if (isset($_REQUEST['words'])) { if (intval($_REQUEST['words']) < 9) { $sphinx->SetFilter('words', array(intval($_REQUEST['words']))); } else { $sphinx->SetFilterRange('words', 9, 100); } } $sphinx->SetSortMode(SPH_SORT_EXTENDED, "lang_part ASC, words ASC, header_sort ASC, count DESC"); //索引源是配置文件中的 index 类,如果有多个索引源可使用,号隔开:'email,diary' 或者使用'*'号代表全部索引源 $result = $sphinx->query($key_word, 'media'); // echo '<pre>'; // print_r($result); // echo '</pre>'; if (!isset($result['matches'])) { include_once '_list.php'; exit; // $finalResult = array( // "songs" => array(), // "page" => 0, // "total" => 0,
fwrite($file, $client->BuildKeywords("pat", "people", true)); fclose($file); // filter_array $client->SetFilter("field", array(1, 2, 3)); $file = fopen("spec/fixtures/data/filter_array.bin", "w"); fwrite($file, $client->FilterOutput()); fclose($file); $client->ResetFilters(); // filter_array_exclude $client->SetFilter("field", array(1, 2, 3), true); $file = fopen("spec/fixtures/data/filter_array_exclude.bin", "w"); fwrite($file, $client->FilterOutput()); fclose($file); $client->ResetFilters(); // filter_range $client->SetFilterRange("field", 1, 3); $file = fopen("spec/fixtures/data/filter_range.bin", "w"); fwrite($file, $client->FilterOutput()); fclose($file); $client->ResetFilters(); // filter_range_exclude $client->SetFilterRange("field", 1, 3, true); $file = fopen("spec/fixtures/data/filter_range_exclude.bin", "w"); fwrite($file, $client->FilterOutput()); fclose($file); $client->ResetFilters(); // filter_floats $client->SetFilterFloatRange("field", 5.4, 13.5); $file = fopen("spec/fixtures/data/filter_floats.bin", "w"); fwrite($file, $client->FilterOutput()); fclose($file);
/** * set filter attr * 设置过滤属性 * @param $filters * $filters = array( * 0=>array("field" => "gender","val" => array(1),"exclude" => false), * 1=>array("field" => "age","val" => 23,"val2" => 30,"exclude" => false), * 2=>array("field" => "username","str" => array("*****@*****.**","*****@*****.**"),"exclude" => false), * ); */ private function setFilters($filters) { if (!is_array($filters) && empty($filters)) { $this->halt('The argv must be an array and not null.', 1002); } foreach ($filters as $k => $v) { if (!isset($v['exclude']) || !$v['exclude']) { $v['exclude'] = false; } if (isset($v['val']) && is_array($v['val'])) { parent::SetFilter($v['field'], $v['val'], $v['exclude']); } else { if (isset($v['val2']) && $v['val2']) { if ($v['val'] > $v['val2']) { $t = $v['val2']; $v['val2'] = $v['val']; $v['val'] = $t; } parent::SetFilterRange($v['field'], $v['val'], $v['val2'], $v['exclude']); } else { if (isset($v['str']) && $v['str']) { if (isset($v['str']) && !empty($v['str'])) { $str_arr = array(); foreach ($v['str'] as $val) { $str_arr[] = sprintf("%u", crc32($val)); } parent::SetFilter($v['field'], $str_arr, $v['exclude']); } } } } } }
<?php require "spec/fixtures/sphinxapi.php"; $cl = new SphinxClient(); $cl->SetFilterRange('attr', 10, 20); $cl->Query('query');
$sc->SetLimits($limits[0], $limits[1], isset($limits[2]) ? $limits[2] : 0, isset($limits[3]) ? $limits[3] : 0); } } // filter } elseif (strpos($arg, '=') !== false) { list($attr, $value) = explode('=', $arg); $exclude = false; // exclude if (substr($attr, -1) == '!') { $attr = substr($attr, 0, -1); $exclude = true; } // range if (strpos($value, ':') !== false) { list($min, $max) = explode(':', $value); $sc->SetFilterRange($attr, $min, $max, $exclude); // list/single } else { if (strpos($value, ',') !== false) { $values = array_filter(array_map('trim', explode(',', $value))); } else { $values = array(trim($value)); } $sc->SetFilter($attr, $values, $exclude); } // index } elseif (!$index) { $index = trim($arg); // query } else { $query = trim($arg);
public function index() { C('TOKEN_ON', false); $seo = seo(); $this->assign("seo", $seo); if (isset($_GET['q'])) { G('search'); //关键字 $q = Input::forSearch(safe_replace($this->_get("q"))); $q = htmlspecialchars(strip_tags($q)); //时间范围 $time = $this->_get("time"); //模型 $mid = (int) $this->_get("modelid"); //栏目 $catid = (int) $this->_get("catid"); //排序 $order = array("adddate" => "DESC", "searchid" => "DESC"); //搜索历史记录 $shistory = cookie("shistory"); if (!$shistory) { $shistory = array(); } $model = F("Model"); $category = F("Category"); if (trim($_GET['q']) == '') { header('Location: ' . U("Search/Index/index")); exit; } array_unshift($shistory, $q); $shistory = array_slice(array_unique($shistory), 0, 10); //加入搜索历史 cookie("shistory", $shistory); $where = array(); //每页显示条数 $pagesize = $this->config['pagesize'] ? $this->config['pagesize'] : 10; //缓存时间 $cachetime = (int) $this->config['cachetime']; //按时间搜索 if ($time == 'day') { //一天 $search_time = time() - 86400; $where['adddate'] = array("GT", $search_time); } elseif ($time == 'week') { //一周 $search_time = time() - 604800; $where['adddate'] = array("GT", $search_time); } elseif ($time == 'month') { //一月 $search_time = time() - 2592000; $where['adddate'] = array("GT", $search_time); } elseif ($time == 'year') { //一年 $search_time = time() - 31536000; $where['adddate'] = array("GT", $search_time); } else { $search_time = 0; } //可用数据源 $this->config['modelid'] = $this->config['modelid'] ? $this->config['modelid'] : array(); //按模型搜索 if ($mid && in_array($mid, $this->config['modelid'])) { $where['modelid'] = array("EQ", (int) $mid); } //按栏目搜索 if ($catid) { //不支持多栏目搜索,和父栏目搜索。 $where['catid'] = array("EQ", (int) $catid); } //分页模板 $TP = '共有{recordcount}条信息 {pageindex}/{pagecount} {first}{prev}{liststart}{list}{listend}{next}{last}'; //如果开启sphinx if ($this->config['sphinxenable']) { import("Sphinxapi", APP_PATH . C("APP_GROUP_PATH") . '/Search/Class/'); $sphinxhost = $this->config['sphinxhost']; $sphinxport = $this->config['sphinxport']; $cl = new SphinxClient(); //设置searchd的主机名和TCP端口 $cl->SetServer($sphinxhost, $sphinxport); //设置连接超时 $cl->SetConnectTimeout(1); //控制搜索结果集的返回格式 $cl->SetArrayResult(true); //设置全文查询的匹配模式 api http://docs.php.net/manual/zh/sphinxclient.setmatchmode.php $cl->SetMatchMode(SPH_MATCH_EXTENDED2); //设置排名模式 api http://docs.php.net/manual/zh/sphinxclient.setrankingmode.php $cl->SetRankingMode(SPH_RANK_PROXIMITY_BM25); //按一种类似SQL的方式将列组合起来,升序或降序排列。用weight是权重排序 $cl->SetSortMode(SPH_SORT_EXTENDED, "@weight desc"); //设置返回结果集偏移量和数目 $page = (int) $this->_get(C("VAR_PAGE")); $page = $page < 1 ? 1 : $page; $offset = $pagesize * ($page - 1); $cl->SetLimits($offset, $pagesize, $pagesize > 1000 ? $pagesize : 1000); if (in_array($time, array("day", "week", "month", "year"))) { //过滤时间 $cl->SetFilterRange('adddate', $search_time, time(), false); } if ($mid && in_array($mid, $this->config['modelid'])) { //过滤模型 $cl->SetFilter('modelid', (int) $mid); } if ($catid) { //过滤栏目 $cl->SetFilter('catid', (int) $catid); } //执行搜索 api http://docs.php.net/manual/zh/sphinxclient.query.php $res = $cl->Query($q, "*"); //信息总数 $count = $res['total']; //如果结果不为空 if (!empty($res['matches'])) { $result_sphinx = $res['matches']; } $result = array(); //数组重新组合 foreach ($result_sphinx as $k => $v) { $result[$k] = array("searchid" => $v['id'], "adddate" => $v['attrs']['adddate'], "catid" => $v['attrs']['catid'], "id" => $v['attrs']['id'], "modelid" => $v['attrs']['modelid']); } $words = array(); //搜索关键字 foreach ($res['words'] as $k => $v) { $words[] = $k; } $page = page($count, $pagesize); $page->SetPager('default', $TP, array("listlong" => "6", "first" => "首页", "last" => "尾页", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => "")); $this->assign("Page", $page->show('default')); } else { import("Segment", APP_PATH . C("APP_GROUP_PATH") . '/Search/Class/'); $Segment = new Segment(); //分词结果 $segment_q = $Segment->get_keyword($Segment->split_result($q)); $words = explode(" ", $segment_q); if (!empty($segment_q)) { $where['_string'] = " MATCH (`data`) AGAINST ('{$segment_q}' IN BOOLEAN MODE) "; } else { //这种搜索最不行 $where['data'] = array('like', "%{$q}%"); } //查询结果缓存 if ($cachetime) { //统计 $count = M("Search")->cache(true, $cachetime)->where($where)->count(); $page = page($count, $pagesize); $result = M("Search")->cache(true, $cachetime)->where($where)->limit($page->firstRow . ',' . $page->listRows)->order($order)->select(); } else { $count = M("Search")->where($where)->count(); $page = $this->page($count, $pagesize); $result = M("Search")->where($where)->limit($page->firstRow . ',' . $page->listRows)->order($order)->select(); } $page->SetPager('default', $TP, array("listlong" => "6", "first" => "首页", "last" => "尾页", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => "")); $this->assign("Page", $page->show('default')); } //搜索结果处理 if ($result && is_array($result)) { foreach ($result as $k => $r) { $modelid = $r['modelid']; $id = $r['id']; $tablename = ucwords($model[$modelid]['tablename']); if ($tablename) { $result[$k] = M($tablename)->where(array("id" => $id))->find(); } } } //搜索记录 if (strlen($q) < 17 && strlen($q) > 1 && $result) { $res = M("SearchKeyword")->where(array('keyword' => $q))->find(); if ($res) { //关键词搜索数+1 M("SearchKeyword")->where(array('keyword' => $q))->setInc("searchnums"); } else { //关键词转换为拼音 load("@.iconvfunc"); $pinyin = gbk_to_pinyin(iconv('utf-8', 'gbk//IGNORE', $q)); if (is_array($pinyin)) { $pinyin = implode('', $pinyin); } M("SearchKeyword")->add(array('keyword' => $q, 'searchnums' => 1, 'data' => $segment_q, 'pinyin' => $pinyin)); } } //相关搜索功能 if ($this->config['relationenble']) { $map = array(); //相关搜索 if (!empty($segment_q)) { $relation_q = str_replace(' ', '%', $segment_q); } else { $relation_q = $q; } $map['_string'] = " MATCH (`data`) AGAINST ('%{$relation_q}%' IN BOOLEAN MODE) "; $relation = M("SearchKeyword")->where($map)->select(); $this->assign("relation", $relation); } foreach ($this->config['modelid'] as $modelid) { $source[$modelid] = array("name" => $model[$modelid]['name'], "modelid" => $modelid); } //搜索结果 $this->assign("result", $result); //运行时间 $search_time = G('search', 'end', 6); $this->assign("count", $count ? $count : 0); $this->assign("search_time", $search_time); $this->assign("keyword", $q); $this->assign("category", $category); $this->assign("source", $source); $this->assign("time", $time); $this->assign("modelid", $mid); $this->assign("shistory", $shistory); //分词后的搜索关键字 $this->assign("words", $words); $this->display("search"); } else { $this->display(); } }
$out_array = array(); //TTHS $prev_instanses_count = 0; $start = max(0, $min - $prev_instanses_count); $len = min(RPP, max(1, $max - $prev_instanses_count)); $searcher->setLimits($start, $len); $tths_result = $searcher->query($query, "dc_tths dc_tths_delta"); $total_tths = $tths_result['total']; if ($total_tths && is_array($tths_result['matches']) && count($out_array) < RPP) { $tths = Searcher::getTTHs(array_keys($tths_result['matches'])); $out_array = array_merge($out_array, $tths); } if (!$nodirs) { //DIRS if ($days) { $searcher->SetFilterRange("starttime", 0, time() - $days * 24 * 60 * 60, true); //exclude too old results } $prev_instanses_count += $total_tths; $start = max(0, $min - $prev_instanses_count); $len = min(RPP, max(1, $max - $prev_instanses_count)); $searcher->setLimits($start, $len); $dirs_result = $searcher->query($query, "dc_dirs dc_dirs_delta"); $total_dirs = $dirs_result['total']; if ($total_dirs && is_array($dirs_result['matches']) && count($out_array) < RPP) { $dirs = Searcher::getDirs(array_keys($dirs_result['matches'])); $out_array = array_merge($out_array, $dirs); } } $searcher->ResetFilters(); if ($days) {