Mar 18, 2014, by admin
Normally, most of us use “SELECT * FROM table WHERE field1 LIKE ‘%$keyword%’” OR field2 LIKE ‘%$keyword%‘ ..etc” to search our table and get results. This is slow and inefficient approach, as it does return all (too many) rows in which it does find a match for “keyword” without caring for “relevancy” and time.
What is alternate to make your searches lot more fast and ensure correctness of results? Exactly! The full-text search thing!
What is Full-text search?
According to the MySQL manual, Full-text is a “natural language search”; it indexes words that appear to represent the row, using the columns you specified. As an example, if all your rows contain “MySQL” then “MySQL” won’t match much. It’s not terribly unique, and it would return too many results. However, if “MySQL” were present in only 5% of the rows, it would return those rows because it doesn’t appear too often to be known as a keyword that’s very common. (If you have “MySQL” in none of your rows, it’ll return nothing!)
What do i need to apply Full-text Search?
MySQL version 3.23.23 or better.
PHP and MYSQL knowledge (Just kidding!)
Full-text index. For example: use “ALTER TABLE table_name ADD FULLTEXT(field1, field2);” to add field1 and field2 to full-text index.
How do i write search query?
SELECT *,
MATCH(field1, field2) AGAINST (‘$keyword’) AS score
FROM table_name
WHERE MATCH(field1, field2) AGAINST(‘$keyword’)
ORDER BY score DESC
In the above query score represents the relevancy score which may come like 1.2311552443038, 1.2210267538154, 0.74408202544174, …etc, enough to sort your records off!