Saturday, May 24, 2008

A few notes on full-text searching in MySQL

Firstly we'll create a table to experiment with.

CREATE TABLE books(title VARCHAR(50), author VARCHAR(50), FULLTEXT(title, author));
INSERT INTO books (title,author) VALUES("Elementary Mechanics","Bob Smith");
INSERT INTO books (title,author) VALUES("Popular Science","Reg Hammer");
INSERT INTO books (title,author) VALUES("Beginner's Guide to Mechanics","R. G. Wesley");
INSERT INTO books (title,author) VALUES("Advanced Statistical Mechanics","O. R. Ange");


Our table therefore contains the following:
+--------------------------------+--------------+
| title | author |
+--------------------------------+--------------+
| Elementary Mechanics | Bob Smith |
| Popular Science | Reg Hammer |
| Beginner's Guide to Mechanics | R. G. Wesley |
| Advanced Statistical Mechanics | O. R. Ange |
+--------------------------------+--------------+
Suppose we want to find all books with the word "mechanics" in the title. This can be done easily using:

SELECT * FROM books WHERE MATCH(title,author) AGAINST ('mechanics' IN BOOLEAN MODE);


This gives:
+--------------------------------+--------------+
| title | author |
+--------------------------------+--------------+
| Elementary Mechanics | Bob Smith |
| Beginner's Guide to Mechanics | R. G. Wesley |
| Advanced Statistical Mechanics | O. R. Ange |
+--------------------------------+--------------+
If we want to find all books containing the word "mechanics" in the title but not the word "elementary":

SELECT * FROM books WHERE MATCH(title,author) AGAINST ('mechanics -elementary' IN BOOLEAN MODE);

This gives:
+--------------------------------+--------------+
| title | author |
+--------------------------------+--------------+
| Beginner's Guide to Mechanics | R. G. Wesley |
| Advanced Statistical Mechanics | O. R. Ange |
+--------------------------------+--------------+

No comments: