What is PostgreSQL full text search
· Category: SQL & Databases
Short answer
PostgreSQL full-text search converts documents into tsvector structures and queries into tsquery structures, enabling fast linguistic searches with relevance ranking.
Steps
- Create a tsvector column:
ALTER TABLE articles ADD COLUMN tsv TSVECTOR; - Populate it:
UPDATE articles SET tsv = to_tsvector('english', title || ' ' || content); - Search:
SELECT * FROM articles WHERE tsv @@ to_tsquery('english', 'database & optimization'); - Create a GIN index:
CREATE INDEX idx_fts ON articles USING GIN (tsv); - Rank results:
SELECT ts_rank(tsv, query) FROM articles, to_tsquery('database') query;
Tips
- Use triggers to keep
tsvectorcolumns synchronized with source text. - Customize text search configurations for different languages and stopword lists.
Common issues
- Full-text search is language-dependent; choosing the wrong dictionary misses relevant stems.
- Large documents may need chunking or separate highlighting strategies.r