/** * 获取竞品信息 * @author zhangxiao@dachuwang.com */ public function get_list($friend_id = null, $city_id = null, $key, $key_word = null, $cate_name = null, $offset = 0, $page_size = 10) { $key = $key ?: $this->input->get_post('search_key', TRUE); $key_word = $key_word ?: $this->input->get_post('search_value', TRUE); $cate_name = $cate_name ?: $this->input->get_post('cate_name', TRUE); $friend_id = $friend_id ?: $this->input->get_post('friend_id', TRUE); $city_id = $city_id ?: $this->input->get_post('city_id', TRUE); //使用sphinx $s = new SphinxClient(); $s->setServer(C('service.spider'), 9312); $s->setMatchMode(SPH_MATCH_EXTENDED2); $s->setLimits($offset, $page_size, 100000); $s->setMaxQueryTime(30); //筛选友商城市 if ($city_id != C('open_cities.quanguo.id')) { $s->setFilter('city_id', array($city_id)); } //筛选友商站点 if ($friend_id != C('anti_sites.all.id')) { $s->setFilter('site_id', array($friend_id)); } $s->SetSortMode(SPH_SORT_EXTENDED, "product_id asc"); $fields = ''; //筛选关键字 if ($key_word) { if ($key == 'product_name') { $fields .= '@title "' . $key_word . '" '; } elseif ($key == 'product_id') { $s->setFilter('product_id', array($key_word)); } elseif ($key == 'sku_number') { $auto_ids = $this->_get_product_by_sku_num($key_word); if ($auto_ids) { $s->setFilter('auto_id', $auto_ids); } else { return array('total' => 0, 'data' => []); } } } //筛选友商品类名称 if ($cate_name) { $fields .= '@category_name "' . $cate_name . '" '; } $result = $s->query($fields, 'anti_products'); if (isset($result['matches'])) { $list = array_column($result['matches'], 'attrs'); } else { $list = array(); } $final_list = $this->_assemble_sku_num($list); $return = array('total' => $result['total'], 'data' => $final_list); return $return; }
/** * @{inheritDoc} */ public function where_equals($property, $value) { if (is_int($value)) { $this->client->setFilter($property, array($value)); } return $this; }
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; }
/** * Set the desired search filter. * * @param string $attribute The attribute to filter. * @param array $values The values to filter. * @param bool $exclude Is this an exclusion filter? */ public function setFilter($attribute, $values, $exclude = false) { $this->sphinx->setFilter($attribute, $values, $exclude); }
/** * ¬озвращает список публичных типовых услуг по заданным услови¤м и пагинацией * * @return array */ public function getList($excluded_ids = array()) { $criteria = array($this->category_id, $this->city_id, $this->country_id, $this->keywords, $this->limit, $this->offset, $this->price_ranges, $this->price_max, $this->order, $excluded_ids, $this->user_id); $membuf = new memBuff(); $memkey = __METHOD__ . '#' . md5(serialize($criteria)); if (false !== ($result = $membuf->get($memkey)) && is_release()) { return $result; } $sort = $this->getSort(); # @see http://sphinxsearch.com/forum/view.html?id=11538 about city = x or country = y $sphinxClient = new SphinxClient(); $sphinxClient->SetServer(SEARCHHOST, SEARCHPORT); $sphinxClient->SetLimits($this->offset, $this->limit, 20000); $sphinxClient->SetSortMode(SPH_SORT_EXTENDED, $sort); $sphinxClient->SetFieldWeights(array('title' => 2, 'extra_title' => 1)); //$sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25); $selectExpression = '*'; // все колонки if ($this->user_id) { $selectExpression .= ", IF(user_id = {$this->user_id}, 1, 0) as match_user"; $sphinxClient->setFilter('match_user', array(1)); } if ($this->category_id) { $selectExpression .= ", IF(category_id = {$this->category_id} or category_parent_id = {$this->category_id}, 1, 0) as match_category"; $sphinxClient->setFilter('match_category', array(1)); } if ($this->country_id) { $selectExpression .= ", IF(user_country_id = {$this->country_id} or country_id = {$this->country_id}, 1, 0) as match_country"; $sphinxClient->setFilter('match_country', array(1)); } if ($this->city_id) { $selectExpression .= ", IF(user_city_id = {$this->city_id} or city_id = {$this->city_id}, 1, 0) as match_city"; $sphinxClient->setFilter('match_city', array(1)); } if (count($this->price_ranges)) { $match_price_exprs = array(); foreach ($this->getPriceRanges() as $i => $price_range) { if (!isset($this->price_ranges[$i])) { continue; } $match_price_exprs[] = "price_{$i} = 1"; } $match_price_exprs = implode(' or ', $match_price_exprs); $selectExpression .= ", IF({$match_price_exprs}, 1, 0) as match_price"; $sphinxClient->setFilter('match_price', array(1)); } if ($this->price_max > 0) { $selectExpression .= ", IF(price <= {$this->price_max}, 1, 0) as match_price_max"; $sphinxClient->setFilter('match_price_max', array(1)); } $searchString = ''; if (!empty($this->keywords)) { $keywords = implode(' ', array_filter(preg_split('/\\s*,\\s*/', $this->keywords))); $searchString = trim($keywords); //$searchString = $this->GetSphinxKeyword($searchString); $sphinxClient->SetMatchMode(SPH_MATCH_ANY); //SPH_MATCH_EXTENDED2); } if (count($excluded_ids)) { $sphinxClient->setFilter('tservice_id', $excluded_ids, true); } $sphinxClient->SetSelect($selectExpression); $queryResult = $sphinxClient->query($searchString, "tservices;delta_tservices"); //echo '<pre>error: ', $sphinxClient->GetLastError(), '</pre>'; //echo '<pre>warn : ', $sphinxClient->GetLastWarning(), '</pre>'; $list = array(); $total = 0; if (isset($queryResult['matches'])) { foreach ($queryResult['matches'] as $id => $row) { $row['attrs']['id'] = $id; $list[] = $row['attrs']; } $total = $queryResult['total_found'] < $queryResult['total'] ? $queryResult['total_found'] : $queryResult['total']; } $result = array('list' => $list, 'total' => $total); if ($this->_ttl) { $membuf->set($memkey, $result, $this->_ttl); } return $result; }
} else { $uids = array(); if ($srchuname) { $srchuname = str_replace('*', '%', addcslashes($srchuname, '%_')); $query = DB::query("SELECT uid FROM " . DB::table('common_member') . " WHERE username LIKE '" . str_replace('_', '\\_', $srchuname) . "' LIMIT 50"); while ($member = DB::fetch($query)) { $uids[] = $member['uid']; } if (count($uids) == 0) { $uids = array(0); } } elseif ($srchuid) { $uids = array($srchuid); } if (is_array($uids) && count($uids) > 0) { $s->setFilter('authorid', $uids, false); } if ($srchtxt) { if (preg_match("/\".*\"/", $srchtxt)) { $spx_matchmode = "PHRASE"; $s->setMatchMode(SPH_MATCH_PHRASE); } elseif (preg_match("(AND|\\+|&|\\s)", $srchtxt) && !preg_match("(OR|\\|)", $srchtxt)) { $srchtxt = preg_replace("/( AND |&| )/is", "+", $srchtxt); $spx_matchmode = "ALL"; $s->setMatchMode(SPH_MATCH_ALL); } else { $srchtxt = preg_replace("/( OR |\\|)/is", "+", $srchtxt); $spx_matchmode = 'ANY'; $s->setMatchMode(SPH_MATCH_ANY); } $srchtxt = str_replace('*', '%', addcslashes($srchtxt, '%_'));
/** * Binds the filter to a SphinxClient instance * * @param \SphinxClient $sphinx * * @return FilterAttribute */ function bindToSphinx(\SphinxClient $sphinx) { $sphinx->setFilter($this->name, $this->values, $this->exclude); return $this; }
/** * @brief 위치 기반 Sphinx 검색 부분 (외부/내부 호출용..) * @param $document_srl 문서 번호 * @param $lat 위도 * @param $lon 경도 * @return 검색된 결과 리스트 */ function getSphinxSearchedResult($document_srl, $lat, $lon) { $s = new SphinxClient(); $oModuleModel =& getModel('module'); $config = $oModuleModel->getModuleConfig('aroundmap'); $s->setServer($config->serverName, $config->serverPort); $s->setLimits(0, 10); $s->setMatchMode(SPH_MATCH_ALL); $s->SetSortMode(SPH_SORT_EXTENDED, '@geodist ASC'); $s->setFilter("document_srl", array($document_srl), true); $s->SetFilterFloatRange("@geodist", 0, 10000); $s->setMaxQueryTime(3); $s->setGeoAnchor("lat", "lon", (double) deg2rad($lat), (double) deg2rad($lon)); $result = $s->query("", "idx_aroundmap"); $ret = array(); if ($result[total_found] > 0) { $ret = $result[matches]; } return $ret; }
10、添加新词 11、实时索引 12、删除数据 13、sphinx分页 */ header("content-type:text/html;charset=utf-8"); include './sphinxapi.php'; $key = $_GET['keyword']; $sp = new SphinxClient(); $sp->setServer('localhost', 9312); //改变关键字匹配模式 SPH_MATCH_EXTENDED2支持权重排序 $sp->setMatchMode(SPH_MATCH_EXTENDED2); //改变搜索排序模式 sphinx自带id weight 前面加@ 和表关联的字段不用加,优先级前后关系 $sp->setSortMode(SPH_SORT_EXTENDED, 'weight desc @weight desc'); //筛选指定字段的指定值保留,其他不显示 $sp->setFilter('status', array(1)); //分页 $sp->setLimits(4, 4); //搜索根据相关索引 $result = $sp->query($key, 'ind_post ind_post_new'); echo "<pre>"; print_r($result['matches']); $ids = implode(",", array_keys($result['matches'])); mysql_connect("localhost", "root", "123"); mysql_select_db("test"); mysql_set_charset("utf8"); echo $sql = "select * from post where id in (" . $ids . ") order by field(id," . $ids . ")"; $res = mysql_query($sql); $posts = array(); if ($res !== false && mysql_num_rows($res) > 0) { while ($rows = mysql_fetch_assoc($res)) {
function getRecipes($advanced) { include __ROOT__ . "sphinx/api.php"; $cl = new SphinxClient(); $cl->SetServer("localhost", 9312); $l = isset($advanced['limit']) ? $advanced['limit'] : 10; $limit = isset($advanced['page']) ? (int) $advanced['page'] * $l : 0; $cl->setLimits($limit, $l + 1); $lang_id = 0; if ($advanced['favorites'] == 1 && VF::app()->user->isAuth()) { $ids_a = array(); $ids = VF::app()->database->sql("SELECT recipe_id FROM recipes_likes WHERE user_id = " . VF::app()->user->getId())->queryAll(); foreach ($ids as $i) { $ids_a[] = $i['recipe_id']; } if (empty($ids_a)) { return array(); } $cl->setFilter('id_attr', $ids_a); } else { if (isset($advanced['lang_id'])) { $lang_id = $advanced['lang_id']; } else { $lang_id = VF::app()->lang_id; } } if ($advanced['country_id'] > 0) { $cl->setFilter('country_id', array($advanced['country_id'])); } if ($advanced['category_id'] > 0) { $cl->setFilter('category_id', array($advanced['category_id'])); $lang_id = 0; } if ($lang_id > 0) { $cl->setFilter('lang_id', array($lang_id)); } if (!empty($advanced['ingredient_id'])) { $ids_a = array(); $a = explode(",", $advanced['ingredient_id']); if (count($a) > 1) { $sql = "SELECT recipe_id, count(Distinct ingredient_id)\n FROM recipes2ingredients\n WHERE ingredient_ID in (" . $advanced['ingredient_id'] . ")\n GROUP BY recipe_id\n HAVING count(Distinct ingredient_id) = " . count($a); } else { $sql = "SELECT recipe_id FROM recipes2ingredients WHERE ingredient_id = " . $advanced['ingredient_id'] . " LIMIT 300"; } $ids = VF::app()->database->sql($sql)->queryAll(); foreach ($ids as $i) { $ids_a[] = $i['recipe_id']; } $cl->setFilter('id_attr', $ids_a); } if (!empty($advanced['query'])) { $results = $cl->Query($advanced['query']); // поисковый запрос } else { $cl->SetMatchMode(SPH_MATCH_FULLSCAN); // ищем хотя бы 1 слово из поисковой фразы $cl->setSortMode(SPH_SORT_ATTR_DESC, 'date_created'); $results = $cl->Query('*'); // поисковый запрос } $this->total_found = $results['total_found']; $arr = array(); if (!empty($results['matches'])) { foreach ($results['matches'] as $r) { $r['attrs']['id'] = $r['attrs']['id_attr']; $arr[] = $r['attrs']; } } return $arr; }