CakePHP Fulltext search MySQL with rating

核能气质少年 提交于 2019-12-06 04:55:54
Sandeep Kundu

Use like this it will prevent mysql injection too

array("MATCH(User.current_position) AGAINST(? IN BOOLEAN MODE)" => $srch_arr['text'])

Ok, it took me some time... Since, the key issue was to get a rating on the resulting matches, the complicated part in this query was the specific field:

MATCH (title, body) AGAINST ('$search') AS rating

I figured that I should just write that field in the "field" option, in the pagination array. The resulting code was the following:

    $this->paginate = array(
            'limit' => 15,
            'fields' => array('*', "MATCH (data) AGAINST ('$q') AS rating"),
            'conditions' =>  "MATCH(SearchIndex.data) AGAINST('$q' IN BOOLEAN MODE)",
            'order' => array(
                'rating' => 'desc',
            ),
    );
    $paginatedResults = $this->paginate('SearchIndex');

And that worked seamlessly!

I think this is the best way to achieve real search results using Cake. Unless someone has a better alternative :)

Searching phrases in between double quotes will give you the results you should expect!

I have used the above database call by Thomas (thank you) and it does work seamlessly.

However the code:

'conditions' =>  "MATCH(SearchIndex.data) AGAINST('$q' IN BOOLEAN MODE)",

removes the Data Abstraction Layer and opens up your site to SQL injection.

It's probably not quite as good (haven't fully tested it) but try:

'SearchIndex.data LIKE'=>'%'.$search.'%'

I hope this is helpful in someway.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!