Home php教程 php手册 实现一个简单的mysql带权重的中文全文搜索

实现一个简单的mysql带权重的中文全文搜索

Jun 13, 2016 am 09:29 AM
android

实现一个简单的mysql带权重的中文全文搜索自己在写一个web,希望对数据库做全文检索。但是google了解到,由于中文分词的缘故,mysql只支持英文的全文搜索,想支持中文的,需要各种插件or实现一些比较复杂的机制,而买的虚拟主机并不支持这些复杂的东西。仔细想了下,因为自己需求的功能也比较简单,主要是2个字段的搜索,且数据量不大,即便增加几个字段,需要多运行几个select也不会对速度有太大影响,所以通过一些work around实现了需求。

Step 1:用locate进行简单的搜索
Locate可以判断子串是否在子乱
有两个column,一个name,一个description.
所以可以用LOCATE>0去判断是否关键字在其中出现了。
其实就是
SELECT * FROM table WHERE LOCATE(key, 'name')>0 OR LOCATE(key, 'description);
这样,我们就简单实现了对某个key在两个域的搜索

Step 2:搜索多个关键字
通常,搜索都是有多个关键字,所以我们需要对每个关键字,执行下Step1的查询。(当然,也可以合成一个,这里偷懒每次只查询1个关键字)
然后,我们再将每次查询出的数组都合并,这样就得到了一个最终的集合。

php代码如下:

<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li>function selectlocate($tarcols,$skey){<br /> </li><li>$where ="";<br /></li><li>$connector = " ";<br /></li><li>global $count;<br /></li><li>foreach($tarcols as $tarcol ){<br /></li><li>$where .= $connector;<br /></li><li>$where .= "LOCATE('$skey', $tarcol) != 0  ";<br /></li><li>if($connector == " "){<br /></li><li>$connector = " OR ";<br /></li><li>}<br /></li><li>}<br /></li><li><br /></li><li>$sql = "SELECT * FROM pets_table WHERE $where";<br /></li><li>$result = mysql_query($sql);<br /></li><li>$ret = Array();<br /></li><li>while($item = mysql_fetch_array($result, MYSQL_ASSOC)){<br /></li><li>$count ++;<br /></li><li>$ret[] = $item;<br /></li><li>}<br /></li><li>return $ret;<br /></li><li>} </li></ol>
Copy after login
Step 3:匹配的权重
上面Step2的结果,其实是无序的。通常,如果我们搜索一个字段:
1.如果这个字段和关键字完全相同,那么一般来讲,可能这个结果应该是相关度最高的
2.如果他只是其其中出现了一次,相关度就最低。
3.如果他出现的次数比在其他row中出现的次数高,那么他的相关度就比2中的结果高
所以,搜索的时候依据这个顺序考虑权重,
a.如果完全相等,权重为1000
b.如果出现1次,权重为10,出现n次
c.权重为n*10
每次搜索出来的结果附加上权重----》然后合并相同项----》并把权重累加
最后按权重排序,即可得到一个有排序的搜索结果。

以下是两种1关键字对应1个字段(上面的代码是1关键字多个字段)查询的代码(不包含合并两个数组的代码,相关的代码在Step4中),只需遍历每个关键字和字段,就能完成搜索

<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li>$count = 0;<br /> </li><li>function selectequal($col,$skey){<br /></li><li>$connector = " ";<br /></li><li>global $count;<br /></li><li>$sql = "SELECT * FROM pets_table WHERE LOWER($col)=LOWER('$skey')";<br /></li><li>$result = mysql_query($sql);<br /></li><li>$ret = Array();<br /></li><li>while($item = mysql_fetch_array($result, MYSQL_ASSOC)){<br /></li><li>$count ++;<br /></li><li>$item["weight"] = 1000;<br /></li><li>$ret[] = $item;<br /></li><li>}<br /></li><li>return $ret;<br /></li><li>}<br /></li><li>function selectlocate($col,$skey){<br /></li><li>global $count;<br /></li><li>$sql = "SELECT *,(LENGTH(description) - LENGTH(REPLACE(description, '$skey', '')))/LENGTH('$skey') *10 as weight FROM pets_table WHERE LOCATE(LOWER('$skey'),LOWER($col))>0";<br /></li><li>$result = mysql_query($sql);<br /></li><li>$ret = Array();<br /></li><li>while($item = mysql_fetch_array($result, MYSQL_ASSOC)){<br /></li><li>$count ++;<br /></li><li>$ret[] = $item;<br /></li><li>}<br /></li><li>return $ret;<br /></li><li>} </li></ol>
Copy after login



Step 4: 字段的权重
在我的需求中,显然name这个字段比description更重要,所以在匹配时,对name字段的结果应该有所倾斜,所以,又可以增加一个对字段的权重系数。

1.如果是在name域的匹配,设系数为10;
2.如果是在description匹配,设系数为1;

将Step 3每次计算得出的权重,再乘上这个系数,就可以得到一个新的,更有效的权重值。
最后按权重排序,即可得到一个最有相关度排序的搜索结果

其他的细节:
如果一个关键字已经满足了equal条件,那么再使用locate条件的时候会依然返回一个结果,所以在使用locate条件的时候,过滤掉equal的情况

<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li><?php<br /> </li><li>$count = 0;<br /></li><li>function selectequal($col,$val,$skey){<br /></li><li>$connector = " ";<br /></li><li>global $count;<br /></li><li>$sql = "SELECT * FROM pets_table WHERE LOWER($col)=LOWER('$skey')";<br /></li><li>$result = mysql_query($sql);<br /></li><li>$ret = Array();<br /></li><li>while($item = mysql_fetch_array($result, MYSQL_ASSOC)){<br /></li><li>$count ++;<br /></li><li>$item["weight"] = 1000*$val;<br /></li><li>$ret[] = $item;<br /></li><li>}<br /></li><li>return $ret;<br /></li><li>}<br /></li><li>function selectlocate($col,$val,$skey){<br /></li><li>global $count;<br /></li><li>$sql = "SELECT *,(LENGTH(description) - LENGTH(REPLACE(description, '$skey', '')))/LENGTH('$skey') *10*$val as weight FROM pets_table WHERE LOCATE(LOWER('$skey'),LOWER($col))>0 AND LOWER($col)!=LOWER('$skey')";<br /></li><li>$result = mysql_query($sql);<br /></li><li>$ret = Array();<br /></li><li>while($item = mysql_fetch_array($result, MYSQL_ASSOC)){<br /></li><li>$count ++;<br /></li><li>$ret[] = $item;<br /></li><li>}<br /></li><li>return $ret;<br /></li><li>}<br /></li><li>function cleanarr($arr){<br /></li><li>global $count;<br /></li><li>$tmp = Array();<br /></li><li>$tmpall = Array();<br /></li><li>foreach($arr as $item){<br /></li><li>if(array_key_exists($item['uid'], $tmp)){<br /></li><li>$tmp[$item['uid']]+=$item["weight"];<br /></li><li>}<br /></li><li>else{<br /></li><li>$tmp[$item['uid']] = $item["weight"];<br /></li><li>$tmpall[$item['uid']] = $item;<br /></li><li>}<br /></li><li>}<br /></li><li><br /></li><li>//sort by weight in descending order <br /></li><li>arsort($tmp);<br /></li><li><br /></li><li>$ret = Array();<br /></li><li><br /></li><li>//rebuildthe return arary<br /></li><li>$count = 0;<br /></li><li>foreach($tmp as $k=>$v){<br /></li><li>$count++;<br /></li><li>$tmpall[$k]['weight']=$v;<br /></li><li>$ret[]=$tmpall[$k];<br /></li><li>}<br /></li><li>return $ret;<br /></li><li>}<br /></li><li><br /></li><li>require_once("consvr.php");<br /></li><li><br /></li><li><br /></li><li>$colshash = array("name"=>10,"description"=>1);<br /></li><li>$ret = Array();<br /></li><li>$keywords=explode(" ", $keywords);<br /></li><li>$cols = array_keys($colshash);<br /></li><li>foreach($keywords as $keyword){<br /></li><li>foreach($colshash as $col=>$val){<br /></li><li>$ret = array_merge($ret,selectequal($col,$val, $keyword));<br /></li><li>$ret = array_merge($ret,selectlocate($col,$val, $keyword));<br /></li><li>}<br /></li><li><br /></li><li>}<br /></li><li>$ret = cleanarr($ret);<br /></li><li>$ret = array('msg' => "Success", 'count'=>$count,'children' => $ret, 'query'=>"COMPLEX:NOT READABLE");<br /></li><li>echo json_encode($ret);<br /></li><li>mysql_close();<br /></li><li><br /></li><li>?> </li></ol>
Copy after login











Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:23 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Sep 11, 2024 am 06:37 AM

OnLeaks has now partnered with Android Headlines to provide a first look at the Galaxy S25 Ultra, a few days after a failed attempt to generate upwards of $4,000 from his X (formerly Twitter) followers. For context, the render images embedded below h

IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size Sep 07, 2024 am 06:35 AM

Alongside announcing two new smartphones, TCL has also announced a new Android tablet called the NXTPAPER 14, and its massive screen size is one of its selling points. The NXTPAPER 14 features version 3.0 of TCL's signature brand of matte LCD panels

Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Sep 07, 2024 am 06:39 AM

The Vivo Y300 Pro just got fully revealed, and it's one of the slimmest mid-range Android phones with a large battery. To be exact, the smartphone is only 7.69 mm thick but features a 6,500 mAh battery. This is the same capacity as the recently launc

Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Sep 12, 2024 pm 09:21 PM

Samsung has not offered any hints yet about when it will update its Fan Edition (FE) smartphone series. As it stands, the Galaxy S23 FE remains the company's most recent edition, having been presented at the start of October 2023. However, plenty of

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:22 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

iQOO Z9 Turbo Plus: Reservations begin for the potentially beefed-up series flagship iQOO Z9 Turbo Plus: Reservations begin for the potentially beefed-up series flagship Sep 10, 2024 am 06:45 AM

OnePlus'sister brand iQOO has a 2023-4 product cycle that might be nearlyover; nevertheless, the brand has declared that it is not done with itsZ9series just yet. Its final, and possibly highest-end,Turbo+variant has just beenannouncedas predicted. T

See all articles