Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Build fast text search directly in PostgreSQL without external search engines. Master to_tsvector, to_tsquery, relevance ranking with ts_rank, and GIN indexes.
Quick answer
PostgreSQL Full-Text Search converts text into tokenized, normalized tsvector documents and searches them using boolean tsquery expressions. Accelerated by GIN indexes, it supports language stemming, stopword elimination, prefix matching, and relevance ranking with ts_rank() directly inside the database.
FAQs
What is the difference between to_tsquery and plainto_tsquery?
to_tsquery expects boolean syntax (&, |, !), while plainto_tsquery converts raw user input into an unpunctuated AND-query automatically.
Can I search for prefixes in PostgreSQL full-text search?
Yes. In tsquery, appending :* to a term matches prefixes, such as to_tsquery('english', 'postgre:*').
How fast is PostgreSQL full-text search compared to Elasticsearch?
For datasets under 50 million rows, PostgreSQL full-text search with a GIN index executes queries in 2 to 10 milliseconds, matching dedicated search engines while keeping data unified in one ACID database.
Does PostgreSQL full-text search support multiple languages?
Yes. PostgreSQL includes stemming dictionaries and stopword lists for dozens of languages, including English, French, German, Spanish, and Russian.
Learn how to cache complex analytical queries with PostgreSQL materialized views. Master REFRESH MATERIALIZED VIEW CONCURRENTLY, indexing, and scheduling.
When application users need to search through articles, products, or support tickets, developers often assume they must deploy external search infrastructure like Elasticsearch or Meilisearch. Managing external search clusters introduces synchronization delays, operational overhead, and distributed consistency challenges.
PostgreSQL includes an enterprise-grade full-text search engine built directly into the database. It handles linguistic stemming, stopword removal, phrase searches, relevance scoring, and index acceleration using Generalized Inverted Indexes (GIN) with zero external infrastructure.
Why LIKE wildcards fail for text search
Searching text using LIKE '%keyword%' or ILIKE '%keyword%' forces PostgreSQL to perform a sequential table scan, inspecting every character of every row. Read our guide on PostgreSQL ILIKE and case-insensitive searches to understand table scan costs.
Beyond performance, LIKE has zero linguistic awareness: searching for "running" will not match "runs" or "ran", and searching for "postgres" will not match "postgresql". Full-text search solves both issues through normalization and inverted indexing.
The core types: tsvector and tsquery
PostgreSQL implements full-text search using two dedicated data types:
tsvector: A sorted list of distinct normalized lexemes (word stems) along with their positional pointers within the document.
tsquery: A search query containing lexemes combined using boolean operators: & (AND), | (OR), ! (NOT), and <-> (phrase distance).
Converting text into tsvector and matching with @@
-- Convert natural language to tsvector:-- 'The quick brown foxes are running fast'-- Normalizes to stems: 'brown':3 'fast':6 'fox':4 'quick':2 'run':5SELECT to_tsvector('english', 'The quick brown foxes are running fast');-- Match document against query using @@ match operator:SELECT to_tsvector('english', 'PostgreSQL provides full-text search') @@ to_tsquery('english', 'postgres & search');-- Returns TRUE!
As detailed in the PostgreSQL text search documentation, to_tsvector() automatically strips common stopwords ("the", "are", "in") and applies language-specific stemming rules.
Building a searchable table with a GIN index
To build high-performance search across millions of documents, store the tsvector in a dedicated generated column and attach a GIN index.
Creating a full-text search table with GIN index
CREATE TABLE support_articles ( article_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, title VARCHAR(200) NOT NULL, body TEXT NOT NULL, category VARCHAR(50) NOT NULL, -- Generated tsvector column combining title and body with weights -- 'A' weight gives title matches higher relevance than body matches ('B') search_vector TSVECTOR GENERATED ALWAYS AS ( setweight(to_tsvector('english', title), 'A') || setweight(to_tsvector('english', body), 'B') ) STORED);-- Build GIN index for sub-millisecond keyword lookupCREATE INDEX idx_articles_search_ginON support_articles USING gin (search_vector);
Ranking results by relevance with ts_rank()
A search feature is ineffective if relevant results are buried at the bottom. PostgreSQL provides ts_rank() and ts_rank_cd() (cover density) to score documents based on how frequently and closely query terms appear.
Searching and ranking by relevance
-- User searches for: "database performance"SELECT article_id, title, ts_rank(search_vector, query) AS rank_scoreFROM support_articles, plainto_tsquery('english', 'database performance') AS queryWHERE search_vector @@ queryORDER BY rank_score DESCLIMIT 10;
Actionable checklist for PostgreSQL full-text search
Use STORED generated columns: store computed tsvector documents to avoid recalculating stems during queries.
Assign weights with setweight(): assign weight A to titles and weight B to body text for accurate relevance scoring.
Create GIN indexes: always build a GIN index on the tsvector column to enable instant inverted index lookups.
Use plainto_tsquery for raw input: use plainto_tsquery() or websearch_to_tsquery() to parse raw user search strings safely.
Add headline snippets: use ts_headline() to display highlighted search snippets in search result pages.
Configure correct dictionaries: specify the correct language dictionary ('english', 'simple') matching your content.
Wrapping up
PostgreSQL native full-text search provides a dependable, zero-infrastructure solution for searching unstructured text with stemming, boolean filters, and relevance ranking. Storing precomputed tsvector columns with GIN indexes satisfies search requirements for most production applications. Keep your complex full-text SQL queries cleanly structured with sqlfmt or review our pricing tiers.