Postgres Full Text Search: Ranking, Typo Matching and When Elasticsearch Wins
Saket Bhatnagar, Founder, SevyDevy, Last updated , 18 min read
Summary
- Postgres full text search lets the database you already run find rows by meaning-bearing words, not raw letters. It turns text into a sorted list of word roots and matches queries against it.
- A tsvector is that stored list of word roots (lexemes) with their positions. A tsquery is the search, such as wireless AND earphones. The @@ operator checks if one matches the other.
- A GIN index (a word-to-rows lookup, like the index at the back of a book) keeps searches fast. ts_rank scores each match so the best rows come first.
- Full text search does not forgive typos. The pg_trgm extension compares three-letter chunks of words, so earfones can still find earphones.
- Beginners can stop after the section on typos. Engineers get the measured limits after that: ranking with no word rarity, product codes that split, 16,383-position caps, and the honest line where Elasticsearch wins.
What goes wrong when you search with LIKE in Postgres?
LIKE matches letters, not words, so it misses what people mean and slows down as the table grows. Postgres full text search fixes the meaning problem, and an index fixes the speed problem.
Picture a common setup. An online store keeps 2 lakh (200,000) products in Postgres, and the search box runs name ILIKE with the user's words wrapped in percent signs. The store is made up, but every result below came from real queries.
A shopper types earphone. The product called Wireless Earphones shows up, because the letters earphone sit inside earphones. Another shopper types earphones, plural, and a product named Wireless Earphone, singular, vanishes. Plain LIKE is also case-sensitive, so lower-case earphone misses Earphones unless you switch to ILIKE.
Then come the harder asks. The shopper wants the best match first, wants to exclude wired models, and types earfones with an f. LIKE has no ranking, no exclusion syntax and no idea that two spellings are close.
How does Postgres full text search work?
Postgres full text search turns each document into a list of normalised words, turns the search into the same form, and checks for a match. A document is just the text you search, such as a product name plus its description.
The work happens in three steps. A parser cuts text into tokens, which are raw pieces like words, numbers and hyphenated words. Dictionaries then turn tokens into lexemes, which are normalised word roots. Finally the lexemes and their positions are stored as a tsvector.
SELECT to_tsvector('english',
'Wireless Earphones with a charging case, great for running');
-- 'case':6 'charg':5 'earphon':2 'great':7 'run':9 'wireless':1Look at what changed. Everything is lower case. Earphones became earphon, charging became charg and running became run, because the English stemmer cuts words to a shared root. The words with, a and for vanished, because they are stop words: words so common they help no search.
The numbers are positions. Running was the ninth word, so it keeps position 9 even though stop words were dropped. Positions let Postgres check phrases and reward words that sit close together.
From product text to a ranked result
Drag to exploreNotice that the document and the query pass through the same English rules. That is why earphones in a query finds earphone in a product.
Diagram connections:
- Product name and text to Parser makes tokens (raw text)
- Parser makes tokens to Dictionaries (tokens)
- Dictionaries to tsvector column (lexemes)
- tsvector column to GIN index (indexed)
- Shopper's search text to websearch_to_tsquery (same English rules)
- websearch_to_tsquery to GIN index (look up lexemes)
- GIN index to Match and rank (candidate rows)
- Product name and text: Wireless Earphones with a charging case
- Parser makes tokens: Splits words, numbers, hyphenated words
- Dictionaries: Drop stop words, stem: earphones to earphon
- tsvector column: Stored lexemes with positions and weights
- GIN index: Lexeme to list of matching rows
- Shopper's search text: wireless earphones -wired
- websearch_to_tsquery: Builds wireless AND earphon AND NOT wire
- Match and rank: @@ finds rows, ts_rank orders them
What are tsvector and tsquery in Postgres?
A tsvector is the searchable form of a document, and a tsquery is the searchable form of a question. You match them with the @@ operator, which returns true or false.
You rarely write a tsquery by hand. Postgres gives you functions that build one from text, and the choice matters because user input is messy.
| Function | Input tried | Result | Use it for |
|---|---|---|---|
| to_tsquery | wireless earphones | Error: syntax error in tsquery | Queries your code writes, with explicit AND and OR symbols |
| plainto_tsquery | wireless earphones | 'wireless' AND 'earphon' | Plain words where every word must match |
| phraseto_tsquery | noise cancelling | 'nois' FOLLOWED BY 'cancel' | Exact phrases, words next to each other |
| websearch_to_tsquery | wireless earphones -wired | 'wireless' AND 'earphon' AND NOT 'wire' | Raw text from a search box |
For a search box, use websearch_to_tsquery. It reads quotes as a phrase, the word or as OR, and a leading dash as NOT. The manual says it never raises syntax errors, and stray brackets in our test were simply dropped.
The table shows the ASCII words AND, OR, NOT and FOLLOWED BY in place of the real symbols. Postgres prints them as an ampersand, a vertical bar, an exclamation mark and a short arrow.
How do you set up full text search on a Postgres table?
Store the tsvector in a generated column and put a GIN index on it. A generated column is one that Postgres computes from other columns and keeps current on every insert and update.
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
description text,
search tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(name, '')), 'A') ||
setweight(to_tsvector('english', coalesce(description, '')), 'B')
) STORED
);
CREATE INDEX products_search_idx ON products USING GIN (search);Three details carry weight here. The coalesce call swaps a missing description for empty text; without it, the whole vector became NULL in our test. The setweight call labels name words A and description words B, so ranking can favour the name. The double bar joins the two vectors into one.
We tested that the column keeps up. Renaming a product to Wireless Earbuds Pro made the search earbuds find it immediately, with no trigger and no extra code.
Why you must name the language
Always pass the configuration name, such as english, as the first argument. Without it, to_tsvector uses the server's default_text_search_config setting, and that can change.
We tried both forms. Creating an index on to_tsvector of name alone failed with the error functions in index expression must be marked IMMUTABLE. With an index on the two-argument form, a query using the one-argument form ignored it and scanned the whole table.
How to check the index is used
Put EXPLAIN ANALYZE in front of your search query; it runs the query and prints the plan Postgres chose. You want a line saying Bitmap Index Scan on products_search_idx. On our 2 lakh rows, the query for wireless earphones touched one table page.
EXPLAIN ANALYZE
SELECT id FROM products
WHERE search @@ websearch_to_tsquery('english', 'wireless earphones');
-- Bitmap Heap Scan on products
-- Bitmap Index Scan on products_search_idxA Seq Scan line means Postgres read every row. On a two-row test table we got exactly that, even with the index, because reading one page beats opening an index. Load realistic data before you judge the plan.
What is a GIN index and why does search need one?
A GIN index (Generalised Inverted Index) maps each lexeme to the list of rows that contain it. To answer wireless AND earphon, Postgres fetches two short row lists and keeps the rows on both.
Think of the index at the back of a textbook. You look up a word and get page numbers, then turn only to those pages. The lexeme is the word, the row IDs are the page numbers, and the final check is turning to the page.
Where the picture breaks: a book index lists only the words an editor chose, but GIN lists every lexeme. It also says nothing about which page is best, so ranking is separate work.
The manual calls GIN the preferred text search index. The other choice, GiST (Generalised Search Tree), is lossy: it can return false matches that Postgres must recheck against the table. GIN updates are slow for a different reason: one product row adds an entry for every lexeme it holds.
How does ranking work in Postgres full text search?
ts_rank gives each matching row a score from how often the query words appear and which weight label they carry. You sort by that score. ts_rank_cd also rewards query words that sit close together.
SELECT id, name, ts_rank(search, query) AS rank
FROM products,
websearch_to_tsquery('english', 'wireless earphones') AS query
WHERE search @@ query
ORDER BY rank DESC
LIMIT 20;On our sample data, Wireless Earphones Pro scored 0.9964. A charging case whose description mentions wireless earphones scored 0.3964, tied with a pair of running shoes whose description says the same. The A weight on the name did that work.
The default weights are 1.0 for A, 0.4 for B, 0.2 for C and 0.1 for D. You can pass your own as an array, in the order D, C, B, A.
How do you handle typos in Postgres search?
Add the pg_trgm extension and compare words by trigrams, which are three-character chunks. Full text search alone returned nothing for earfones, because no stemmer turns earfones into earphon.
pg_trgm lowercases each word, pads it with two spaces in front and one behind, and cuts it into three-letter pieces. The word cat becomes four trigrams: space space c, space ca, cat and at space. Two words are similar when they share many trigrams.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
SELECT similarity('earfones', 'earphones');
-- 0.46153846 (1.0 means identical, 0 means nothing shared)
CREATE INDEX products_name_trgm_idx
ON products USING GIN (name gin_trgm_ops);
SELECT id, name FROM products WHERE name ILIKE '%arphon%';That trigram index does a second job. It lets ILIKE with a leading percent sign use an index, which a B-tree, the default index type, cannot do. Our ILIKE query for arphon used it and read one table page. A pattern under three letters, such as ar, gives the index no trigram to narrow on. Our run fetched every row from the index and rechecked each one.
A did-you-mean list that the index can serve
Comparing a short typo against a long product name scores low. Earfones against Wireless Earphones Pro scored only 0.23, below the 0.3 default threshold of the percent operator, so it matched nothing.
The pg_trgm manual suggests a better pattern. Build a table of every distinct word in your products, index it with trigrams, and suggest the closest word. Then run the normal full text search with that word.
CREATE TABLE search_words AS
SELECT word
FROM ts_stat('SELECT to_tsvector(''simple'', name) FROM products');
CREATE INDEX search_words_trgm_idx
ON search_words USING GIN (word gin_trgm_ops);
SELECT word, similarity(word, 'earfones') AS sim
FROM search_words
WHERE word % 'earfones'
ORDER BY sim DESC
LIMIT 3;
-- earphones | 0.46153846The simple configuration lowercases words without stemming them, so the list holds real words a shopper would recognise. The percent operator keeps pairs above pg_trgm.similarity_threshold, which defaults to 0.3. The word table goes stale, so rebuild it on a schedule.
For engineers
Beginners can stop here. You now know the full working setup: a generated tsvector column, a GIN index, websearch_to_tsquery, ts_rank and a trigram did-you-mean. The rest is for engineers who will run this in production.
Where does Postgres full text search fall short?
It falls short on relevance, on text that is not ordinary prose, and on very large or very busy search workloads. Each limit below was run on PostgreSQL 16.15 or quoted from the manual.
Ranking does not know which words are rare
The manual says the ranking functions do not use any global information. In our table, steel appeared in 33,334 rows and bluetooth in one. A row matching steel and a row matching bluetooth scored exactly the same, 0.0608.
BM25 is a ranking formula that also counts how rare each word is across all documents. Under it, the rare word bluetooth would count for more than steel. Elasticsearch uses BM25 by default, as of 31 October 2026.
Ranking reads every match before the limit
A query for steel matched 33,334 rows. Postgres had to fetch and score all of them, then keep the top 10. That took about 35 to 40 ms on our two-core test machine, against 0.05 ms for bluetooth. Your numbers will differ; the point is that scoring work grows with the number of matches.
The manual warns that ranking needs the tsvector of each matching document and can be I/O bound, meaning limited by disk reads. Watch for broad, common-word queries, not just for the size of the table.
Product codes and hyphens split in surprising ways
The default parser splits USB-C into usb-c, usb and c. It reads WX-1000 as the word wx followed by the negative number minus 1000. Searching WX-1000 still found the right row, but a search for 1000 alone did not.
Keep exact identifiers like SKUs (stock-keeping unit codes) in their own column with a normal index, or search them with pg_trgm. Run ts_debug, which lists each token and its type, on your real codes.
The stemmer merges words you may want apart
The English stemmer turned universe, university and universal into the same lexeme, univers. Ran stayed ran while running became run, because stemmers cut endings and do not know grammar.
Hard caps on long documents
Positions stop at 16,383. A word placed after 20,000 others was still found, but its position was stored as 16,383. Our run kept 255 positions for a word repeated 1,000 times, and the manual caps a tsvector at under 1 MB.
Indian languages and mixed text
PostgreSQL 16.15 ships hindi and tamil configurations alongside english. The hindi stemmer reduced three forms of the word for boy to one root. It kept the Hindi word for and, so no Hindi stop words were removed in our run.
Hinglish, Hindi written in Latin letters, gets English rules. The English stemmer turned chappals into chappal, which helps, but kapde into kapd, which still misses kapda. Trigram similarity between kapda and kapde was 0.5, so pg_trgm catches such spelling variants.
Index upkeep under heavy writes
GIN uses a pending list to speed up writes. New entries wait in an unsorted list until vacuum (Postgres's clean-up process), autoanalyze or a size limit merges them. The default limit is 4 MB. The manual warns that a large pending list slows searches significantly.
When should you use Elasticsearch instead of Postgres search in 2026?
Move to a dedicated search engine when relevance, scale or search features become the product, not a side feature. Stay in Postgres while search is one feature among many and your data fits one database.
| Need | LIKE or ILIKE | Postgres FTS | pg_trgm | Elasticsearch |
|---|---|---|---|---|
| Match word forms like earphone and earphones | No | Yes, through stemming | Partly, by spelling closeness | Yes, through analysers |
| Survive typos | No | No | Yes | Yes, fuzzy queries by edit distance (one-letter changes) |
| Rank by relevance | No | Yes, without word rarity | By similarity score only | Yes, BM25 by default |
| Hindi text | Letters only | Hindi stemmer, no stop words in our run | Yes, by spelling closeness | Hindi analyser with stemming and stop words |
| Stay in the same transaction as your data | Yes | Yes | Yes | No, it is a separate system to sync |
The last row is the big one. Inside Postgres, a product is searchable the moment its insert commits, with no sync job. With a separate engine you run a pipeline to copy every change and handle the lag and failures.
Signals that you have outgrown Postgres search are concrete. Relevance complaints that need word rarity or tuned scoring. Common-word queries that match tens of thousands of rows on every keystroke. Faceted counts, the numbers beside filters like brand and price band, across many filters at once. Search traffic that slows down checkout queries on the same database.
Choosing a search approach
Drag to exploreNotice that most stores reach a good answer without a second system. A separate engine enters only after the ranking or load questions say yes.
Diagram connections:
- New search feature to Exact codes only?
- Exact codes only? to Plain B-tree index (Yes)
- Exact codes only? to Postgres FTS plus GIN (No, words)
- Postgres FTS plus GIN to Typos common?
- Typos common? to Add pg_trgm (Yes)
- Add pg_trgm to Rarity or load limits?
- Typos common? to Rarity or load limits? (No)
- Rarity or load limits? to Dedicated search engine (Yes, measured)
- New search feature: Product names and descriptions
- Exact codes only?: SKUs, order IDs, phone numbers
- Plain B-tree index: Equality or prefix lookups
- Postgres FTS plus GIN: Stemming, ranking, phrases
- Typos common?: Mobile users, brand names
- Add pg_trgm: Did-you-mean and middle-of-word match
- Rarity or load limits?: Broad matches, facets, heavy traffic
- Dedicated search engine: BM25, fuzzy queries, own cluster
Read the related guides on how a distributed inverted index splits across machines, and on how hybrid search combines BM25 with vectors. Both pick up where this guide stops.
In the interview
How do you explain Postgres full text search in a system design interview?
Start from the requirement, show the simple setup inside the existing database, and name the point where you would add a separate engine. Interviewers want the trade-off, not a tool name.
Clarify the search
Ask what is searched, how many rows, how fresh results must be, and whether typos and ranking matter. Product names for 2 lakh items is a small corpus.
Store a tsvector
Add a generated tsvector column with name weighted A and description weighted B, using an explicit language configuration.
Index and query
Put a GIN index on it, build queries with websearch_to_tsquery, and order by ts_rank with a LIMIT.
Handle typos
Add pg_trgm with a word table for did-you-mean suggestions, and a trigram index for middle-of-word matches.
Name the limits
Say that ranking ignores word rarity, that broad queries score every match, and that writes add GIN upkeep.
Give the exit plan
Move to a dedicated engine when those limits show up in metrics, and sync it from a change stream, a feed of every committed change.
Questions people ask
Is Postgres full text search good enough for production?
Yes, for many apps where search is one feature over a modest amount of text. It gives stemming, phrases, ranking and index-backed speed inside the database you already run. Measure common-word queries and relevance complaints, because those show its limits first.
What is the difference between tsvector and tsquery?
A tsvector is a processed document: normalised word roots with their positions. A tsquery is a processed search: word roots joined by AND, OR, NOT or FOLLOWED BY. The @@ operator checks whether a tsvector matches a tsquery and returns true or false.
Should I use GIN or GiST for full text search?
Use GIN in most cases. The PostgreSQL manual calls GIN the preferred text search index. GiST is lossy, so Postgres must recheck candidate rows against the table. GIN updates can be slow, because every lexeme in a row needs an index entry.
Why does my full text search not find words with typos?
Because full text search matches normalised words exactly, and no stemmer fixes spelling. The typo earfones never becomes earphon. Add the pg_trgm extension, build a table of known words, and suggest the closest word by trigram similarity before searching again.
Which search function should I use for user input?
Use websearch_to_tsquery for anything typed into a search box. It understands quotes, the word or and a leading dash, and the manual says it never raises syntax errors. to_tsquery raised a syntax error on plain words like wireless earphones in our test.
Can Postgres full text search handle Hindi?
Partly. PostgreSQL 16.15 ships a hindi configuration with a stemmer, and it merged three forms of the word for boy in our test. It did not remove common words like and. For Hinglish written in Latin letters, add pg_trgm to catch spelling variants such as kapda and kapde.
When should I move search to Elasticsearch?
Move when measured problems appear: relevance that needs word rarity, common-word queries matching tens of thousands of rows, heavy faceted filtering, or search load hurting other queries. Until then, keeping search in Postgres avoids a sync pipeline and stale results.
Keep learning
Practise it with Lala
A question on this guide, hints and a review.
Read next
Sources (13)
- PostgreSQL 18 manual: 12.1 Introduction to text search
- PostgreSQL 18 manual: 12.2 Tables and indexes (generated column, two-argument to_tsvector)
- PostgreSQL 18 manual: 12.3 Controlling text search (query functions, ranking, headlines)
- PostgreSQL 18 manual: 12.6 Dictionaries (stop words, simple, Snowball)
- PostgreSQL 18 manual: 12.9 Preferred index types for text search
- PostgreSQL 18 manual: 12.11 Limitations
- PostgreSQL 18 manual: GIN indexes and the fast update pending list
- PostgreSQL 18 manual: pg_trgm module
- PostgreSQL versioning policy and supported releases
- Elasticsearch reference: similarity settings (BM25 default)
- PostgreSQL 18 manual: 11.2 Index types (B-tree and anchored LIKE patterns)
- Elasticsearch reference: language analysers
- Elasticsearch reference: fuzzy query