Perform a MySQL search by relevance in PHP
If you have a database with multiple entries that are similar and you'd like to do a search, you're going to need a way to sort the results. Sorting by the number of times a keyword appears in a block of text is one way, and it's called search relevence. Here is a PHP functions for performing a MySQL database search and ording the results by relevence:
-
function relevance_search($keyword_raw, $page, $perpage)
-
{
-
$return = NULL;
-
$offset = ' OFFSET '.(($page-1)*$perpage)-1;
-
if ($page == 1) {
-
$offset = '';
-
}
-
$i = 0;
-
foreach($keywords as $value) {
-
-
if ($i > 0) {
-
$plus = ' + ';
-
$or = ' OR ';
-
}
-
$keyword_string = $keyword_string.$plus."(CASE WHEN body LIKE '%$chunk%' THEN 1 ELSE 0 END) + (CASE WHEN title LIKE '%$chunk%' THEN 1 ELSE 0 END)";
-
$where_string = $where_string.$or."body LIKE '%$chunk%' OR title LIKE '%$chunk%'";
-
$i++;
-
}
-
$sql = "SELECT *, (".$keyword_string.") AS relevance FROM table_name WHERE (".$where_string.") ORDER BY relevance DESC LIMIT ".$perpage.$offset;
-
$i = 0;
-
$return[$i] = $row;
-
$i++;
-
}
-
}
-
}
-
return $return;
-
}
This function returns all the data matching to inputted keywords, and return an array of results sorted beginning with most relevent (the highest count of keyword matches).
Advertisment
Comments
2 Responses to “Perform a MySQL search by relevance in PHP”
Leave a Reply
Here’s how I did a weighted results:
SELECT *,
IF(`name` LIKE “searchterm%”, 20, IF(`name` LIKE “%searchterm%”, 10, 0)) +
IF(`description` LIKE “%searchterm%”, 5, 0) +
IF(`url` LIKE “%searchterm%”, 1, 0) AS `weight`
FROM `myTable`
WHERE (`name` LIKE “%searchterm%” OR
`description` LIKE “%searchterm%” OR
`url` LIKE “%searchterm%”)
ORDER BY `weight` DESC
LIMIT 20
I actually did more weighting with if the term started with, then it got another value.. stuff like that..