//使用sphinx进行全文检索
function search_by_sphinx($keywords,$offset,$limit) {include_once app_path() . '/mylibs/sphinxapi.php';$client = new \SphinxClient();$host = "127.0.0.1";$port = 9312;$client->SetServer ( $host, $port );$client->SetConnectTimeout ( 1 );$client->SetArrayResult ( true );$client->SetLimits($offset,$limit);//$client->SetSortMode(SPH_SORT_ATTR_DESC,'view_count');$index_name = "index_demo";$keywords_clean = $keywords;$words_list_new = array();// | 表示或的意思$words_list = explode('|',$keywords);foreach ($words_list as $value) {if (mb_trim($value) == '') continue;if (mb_strlen($value) > 2) {//超过2个字符,使用模糊匹配$words_list_new[] = '(' . $value . ')';} else {//小于等于两个字符,使用必须包含符号;双引号表示必须包含;$words_list_new[] = '("' . $value . '")';}}//重新用空格分割$keywords_clean = implode('|',$words_list_new);$keywords = $keywords_clean;//全文检索$r = $client->Query($search_str,$index_name);$total = $r['total'];$total_found = $r['total_found'];$matches = $r['matches'];//组合一下结果$list_arr = array();$list_arr['total'] = $total;$list_arr['total_found'] = $total_found;$list_arr['matches'] = $matches;return $list_arr;
}
PHP使用Sphinx查询速度很快,结果也匹配的很不错,算是轻量级的解决方案。
目前,古诗句网和广场舞网站都用的不错,接下来有很多地方都能用到。