PostgreSQL Enterprise (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
Full-Text Search in PostgreSQL: `tsvector`, `tsquery`, and GIN Indexes.
senior LevelMost AskedCode ExampleDatabases & SQLPostgreSQL
In Simple Words: PostgreSQL includes native search engine capabilities:
to_tsvector('english', text): Normalizes text into a sorted list of unique stemmed lexemes (e.g. "running", "runs" both reduce to "run").to_tsquery('english', 'search & query'): Represents search query terms with boolean operators (&,|,!).ts_rank: Ranks matching rows by keyword density and proximity.
sql
-- Generated tsvector column with GIN index
ALTER TABLE articles ADD COLUMN search_vector tsvector
GENERATED ALWAYS AS (to_tsvector('english', title || ' ' || body)) STORED;
CREATE INDEX idx_articles_search ON articles USING GIN (search_vector);
SELECT title, ts_rank(search_vector, query) AS rank
FROM articles, to_tsquery('english', 'database & performance') query
WHERE search_vector @@ query
ORDER BY rank DESC;