php mysql 分詞 模糊查詢 並根據分詞匹配度排序
阿新 • • 發佈:2018-09-07
close desc highlight this then 中文 sql 一個數 exec
中文分詞用 SCWS 的api
http://www.xunsearch.com/scws/api.php
1.php中用 curl獲取分詞結果
protected function http_curl($url,$type="get",$res="json",$arr=array()){ $ch =curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); if($type=="post"){ curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,$arr); } curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_0); $output = curl_exec($ch); curl_close($ch); if($res=="json"){ return json_decode($output,true); }else{ return $output; } }
protected function get_fenci($str){ $url="http://www.xunsearch.com/scws/api.php"; $type="post"; $arr=array( ‘data‘=>$str, ‘respond‘=>"json", ); $res= $this->http_curl($url,$type,"json",$arr); return $res; }
2.根據分詞循環sql where語句
foreach ($fenci as $k => $v) { if(empty($where)){ $where.="name LIKE ‘%{$v}%‘"; }else{ $where.=" OR name LIKE ‘%{$v}%‘"; } }
3.根據分詞循環sql order語句
用CASE WHEN THEN ELSE END 語句;
排序也是通過模糊查詢,分別匹配詞組,如果匹配到就定義一個數值,這些數值相加,詞匹配到的越多,相加值的結果越大,越靠前值也越大,結果就相當於匹配度了, 然後進行降序排序;
protected function fenci_order($fenci){ $order_str; foreach ($fenci as $k => $v) { if(empty($order_str)){ $order_str.="(CASE WHEN name LIKE ‘%".$v."%‘ THEN ".(1000-10*$k)." ELSE 0 END)"; }else{ $order_str.=" + (CASE WHEN name LIKE ‘%".$v."%‘ THEN ".(1000-10*$k)." ELSE 0 END)"; } } $order_str=$order_str." DESC"; // echo count($fenci); return $order_str; }
php mysql 分詞 模糊查詢 並根據分詞匹配度排序