What is a Full-Text Index? A full-text index is a special type of index in SQL databases designed to optimize the performance of text-based searches. Unlike traditional indexes, full-text indexes tokenize text data into searchable terms (words or phrases), enabling powerful and efficient queries.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE EXTENSION IF NOT EXISTS tsvector;
CREATE TABLE articles (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255),
content TEXT,
FULLTEXT (title, content)
);
-- Add a tsvector column
ALTER TABLE articles ADD COLUMN search_vector tsvector;
-- Populate the column with searchable data
UPDATE articles
SET search_vector = to_tsvector('english', title || ' ' || content);
-- Create a GIN index on the search_vector column
CREATE INDEX search_idx ON articles USING GIN(search_vector);
-- Enable the database for full-text indexing
CREATE FULLTEXT CATALOG FullTextCatalog AS DEFAULT;
-- Create a full-text index
CREATE FULLTEXT INDEX ON articles(content)
KEY INDEX PK_articles
WITH STOPLIST = SYSTEM;
VARCHAR
and TEXT
columns.tsvector
column.
CREATE TRIGGER update_search_vector
BEFORE INSERT OR UPDATE ON articles
FOR EACH ROW
EXECUTE FUNCTION tsvector_update_trigger(search_vector, 'pg_catalog.english', title, content);
-- Full-text indexes in SQL Server are automatically updated.
-- However, you can manually repopulate them:
ALTER FULLTEXT INDEX ON articles START FULL POPULATION;
tsvector
column is always in sync.
SELECT * FROM articles
WHERE MATCH(title, content) AGAINST('search term' IN NATURAL LANGUAGE MODE);
SELECT * FROM articles
WHERE search_vector @@ to_tsquery('search & term');
SELECT * FROM articles
WHERE CONTAINS(content, 'search term');
SELECT * FROM articles
WHERE MATCH(content) AGAINST('+SQL -NoSQL' IN BOOLEAN MODE);
SELECT * FROM articles
WHERE to_tsvector('english', content) @@ phraseto_tsquery('search term');
SELECT * FROM articles
WHERE FREETEXT(content, 'search term');
AND
, OR
, and NOT
.VACUUM
and ANALYZE
.OPTIMIZE TABLE
.
VACUUM ANALYZE articles;
ALTER FULLTEXT INDEX ON articles REBUILD;
Configuring full-text indexes in SQL enables databases to efficiently handle text-based queries, offering powerful search capabilities that go beyond traditional methods. With proper setup, indexing, and query optimization, full-text indexes can significantly improve performance and provide meaningful insights. Whether you're building a search engine or enhancing application features, mastering full-text indexes is an essential skill for modern database applications. Happy coding !❤️