Advanced Full Text Search
title: Use tsvector for Full-Text Search impact: MEDIUM impactDescription: 100x faster than LIKE, with ranking support tags: full-text-search, tsvector, gin, search
Section titled “title: Use tsvector for Full-Text Search impact: MEDIUM impactDescription: 100x faster than LIKE, with ranking support tags: full-text-search, tsvector, gin, search”Use tsvector for Full-Text Search
Section titled “Use tsvector for Full-Text Search”LIKE with wildcards can’t use indexes. Full-text search with tsvector is orders of magnitude faster.
Incorrect (LIKE pattern matching):
-- Cannot use index, scans all rowsselect * from articles where content like '%postgresql%';
-- Case-insensitive makes it worseselect * from articles where lower(content) like '%postgresql%';Correct (full-text search with tsvector):
-- Add tsvector column and indexalter table articles add column search_vector tsvector generated always as (to_tsvector('english', coalesce(title,'') || ' ' || coalesce(content,''))) stored;
create index articles_search_idx on articles using gin (search_vector);
-- Fast full-text searchselect * from articleswhere search_vector @@ to_tsquery('english', 'postgresql & performance');
-- With rankingselect *, ts_rank(search_vector, query) as rankfrom articles, to_tsquery('english', 'postgresql') querywhere search_vector @@ queryorder by rank desc;Search multiple terms:
-- AND: both terms requiredto_tsquery('postgresql & performance')
-- OR: either termto_tsquery('postgresql | mysql')
-- Prefix matchingto_tsquery('post:*')Reference: Full Text Search