
153 views
MySQL Query Expansion Fulltext Search
The MySQL can perform full-text searches using the MATCH ... AGAINST
clause in combination with the BOOLEAN MODE
. Full-text search allows you to search for words and phrases in text columns efficiently. Here’s how you can use it:
Assuming you have a table named articles
with a text column content
, and you want to search for articles containing specific words or phrases:
- Create a Full-Text Index: Before you can perform full-text searches, you need to create a full-text index on the column you want to search. You can do this when creating the table or alter an existing table.
CREATE TABLE articles ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255), content TEXT, FULLTEXT(content) );
- Perform a Full-Text Search:
- To perform a full-text search, you use the
MATCH ... AGAINST
clause in your SQL query. - You can use the
+
and-
operators to include or exclude specific words. - You can use double quotes
"
to search for an exact phrase.
SELECT * FROM articles WHERE MATCH(content) AGAINST('+database +query -NoSQL' IN BOOLEAN MODE);
- To perform a full-text search, you use the
- Sorting by Relevance: You can also sort the results by relevance using the
MATCH ... AGAINST
clause in theORDER BY
clause:SELECT *, MATCH(content) AGAINST('+database +query -NoSQL' IN BOOLEAN MODE) AS relevance FROM articles WHERE MATCH(content) AGAINST('+database +query -NoSQL' IN BOOLEAN MODE) ORDER BY relevance DESC;
- Word Length Limit: By default, MySQL’s full-text search ignores words that are too short (less than 4 characters) and words that are very common (stopwords). You can adjust these settings in the MySQL configuration.
- Boolean Mode: The
IN BOOLEAN MODE
option allows you to use operators like+
,-
,*
, etc., for more complex queries. In non-boolean mode, you can simply useMATCH ... AGAINST('your_query')
. - Thesaurus Support: You can also use a thesaurus file to extend the search capabilities. For example, you can specify synonyms for specific words.
Keep in mind that full-text search in MySQL may not be as feature-rich as specialized search engines like Elasticsearch, so consider your requirements and scale when implementing full-text search in your applications.