header

A sql search algorithm



I had the opportunity to do a simple search algorithm for my work. We have a fairly small database of text based certifications which need to be searched. If someone were to search for “radeon ati” it should show all of the certifications that match that string in any way.

Our database is MySQL, and PHP is the frontend, so you can find the respective MySQL functions at http://www.mysql.com and the PHP functions at http://www.php.net/.

If someone inserted into the form “radeon ati”, I would get that text and run it through this function:

function split_spaces($in){
    $tmp = explode(" ", $in);
    $tmp = implode("%' AND N.CardName LIKE '%", $tmp);
    return $tmp;
}

Then calling that function inside of my query:

...
AND ( N.CardName LIKE '%".$this->strip_spaces($q)."%' )
...

leading to the final result becoming something similar to

...
AND ( N.CardName LIKE '%radeon%' AND N.CardName LIKE '%ati%' )
...

This leads to a much more efficient search “engine” than simply feeding in the entire string inside the LIKE ‘%%’ clause.



6 Comments »

  1. gravatar

    Shadow Said,

    May 23, 2007 @ 1:16 pm

    You would get a considerable increment of performance if you switch the bunch of LIKEs with a regular expression.

  2. gravatar

    Raybdbomb Said,

    May 23, 2007 @ 7:19 pm

    How, with SQL?

  3. gravatar

    Ste Said,

    September 3, 2007 @ 6:12 am

    use the REGEXP to search instead of LIKE – you can use regular expressions with that

  4. gravatar

    Funmarkaz Said,

    August 28, 2009 @ 9:09 pm

    Can REGEXP be used with MATCH?

  5. gravatar

    Raybdbomb Said,

    August 29, 2009 @ 12:31 pm

    No experience with it, sorry! Check out mysql’s guides.

  6. gravatar

    Tanay Said,

    December 23, 2010 @ 5:27 am

    Thank you so much. I applied it in SQLite for my Android app.

RSS feed for comments on this post · TrackBack URI

Leave a Comment

blogtimes