Sub topic 18
Limitations and when to reach for an external engine
This chapter assumes you have followed the earlier chapters: you can build a tsvector column, query it with @@, rank with ts_rank, and read an EXPLAIN plan. Built-in full-text search covers a lot of ground. This chapter lists where it stops and gives criteria for adding pg_trgm or a dedicated search engine.
What built-in search does well
Full-text search in PostgreSQL runs inside your database. That gives you several things an external engine has to work to match:
- Transactions: a committed row is searchable immediately, and a rolled-back row never appears.
- No second copy of the data to keep in sync.
- SQL joins and filters in the same query as the text match.
- One system to back up, secure, and monitor.
For catalogs, documentation sites, help centers, and internal tools with up to a few million documents, this is often enough. The limitations below decide whether yours is such a case.
Limitations of the built-in feature
No typo tolerance
A tsquery matches lexemes exactly after stemming. A search for postgress produces the lexeme postgress, which does not match postgr. Stemming handles word forms such as jumped and jumping. It does not handle misspellings. The usual in-database remedy is pg_trgm, covered below.
Simple relevance model
ts_rank and ts_rank_cd score a document from term frequency, positions, and weights. They use no corpus-wide statistics, so a rare term counts the same as a common one. There is no BM25-style inverse document frequency. You cannot tune field boosts, decay by date, or add click signals except by writing your own SQL expression around the rank.
Ranking is also expensive at scale. To rank, PostgreSQL must read the tsvector of every matching row, and that read can be I/O bound. The GIN index finds the matches. It does not give you the top 10 by rank. A query matching 500,000 rows ranks all 500,000 before LIMIT applies.
Hard size limits
A tsvector must be smaller than 1 MB, including positions. A lexeme can be at most 2046 bytes. Positions are recorded only up to 16383, and later occurrences share that value. Very long documents such as whole books need to be split into chunks, one row per chunk.
Write cost
A GIN index is slow to update, because one document touches an index entry for each of its lexemes. PostgreSQL softens this with a pending list (fastupdate), which batches insertions. Heavy ingest can still slow down, and searches must also scan the pending list until it is flushed.
Missing search-engine features
These have no built-in equivalent:
- Facet counts, such as "42 results in category Books".
- "Did you mean" suggestions.
- Autocomplete tuned for prefix and popularity.
to_tsquery('english', 'postg:*')gives prefix matching, but nothing more. - Per-field analyzers, with different tokenizing for different columns inside one index.
- Good tokenizing for languages without spaces, such as Chinese or Japanese. The default parser does not segment these. Extensions exist, but you have to install and maintain them.
- Vector or hybrid semantic search combined with keyword scoring. The
pgvectorextension adds vectors, but combining the two scores is your job. - Horizontal scaling of the search workload. A single primary has to do the work, and you can only offload reads to replicas.
Typo tolerance with pg_trgm
The pg_trgm extension breaks strings into three-character sequences and measures how many they share. It is the standard way to add fuzzy matching without leaving PostgreSQL.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX articles_title_trgm_idx
ON articles USING gin (title gin_trgm_ops);
SELECT id,
title,
similarity(title, 'postgress full txt') AS sim
FROM articles
WHERE title % 'postgress full txt'
ORDER BY sim DESC
LIMIT 10;The % operator is true when the similarity is above pg_trgm.similarity_threshold, which defaults to 0.3. The GIN trigram index serves that operator. Trigram matching works best on short strings such as titles, names, and tags. On long bodies it is slow, and the scores are less meaningful. A common pattern runs full-text search first and falls back to trigram search when the first query returns few or no rows.
Checking whether you are hitting a limit
Measure before you decide. These two queries show document size and the cost of ranking a large match set.
SELECT max(pg_column_size(search)) AS largest_tsvector_bytes,
avg(pg_column_size(search))::int AS average_bytes
FROM articles;
EXPLAIN (ANALYZE, BUFFERS)
SELECT a.id, ts_rank(a.search, q.query) AS rank
FROM articles AS a,
websearch_to_tsquery('english', 'database') AS q(query)
WHERE a.search @@ q.query
ORDER BY rank DESC
LIMIT 10;In the plan, look at the number of rows the bitmap heap scan returns, and at the sort node above it. If a common word matches a large share of the table and the sort takes most of the time, ranking is your bottleneck. The Buffers: shared read counts show whether it is reading from disk.
Mitigations that stay inside PostgreSQL:
- Add filters that shrink the match set, such as a date range, tenant, or category.
- Cap the work: rank only the first N matches in a subquery, accepting that this is no longer an exact top 10.
- Add a stop-word list or a minimum query length, so users cannot search for very common words alone.
- Use a read replica for search traffic.
Deciding where to search
The table maps common needs to a choice.
| Need | Built-in FTS | + pg_trgm | External engine |
|---|---|---|---|
| Stemmed keyword and phrase search | Yes | Not needed | Yes |
| Transactional consistency with the table | Yes | Yes | No, it lags behind |
| Typos in short fields | No | Yes | Yes |
| Facets and aggregations | No | No | Yes |
| BM25-style tuned relevance | No | No | Yes |
| CJK and other unsegmented languages | Weak | Weak | Yes |
| Search load independent of the database | No | No | Yes |
The cost of an external engine
Moving to Elasticsearch, OpenSearch, Solr, Meilisearch, or Typesense is not free. You take on:
- A sync pipeline, using change data capture, an outbox table, or periodic reindexing. It will sometimes fail, and you need a way to rebuild the index.
- Eventual consistency. A user can save a record and not find it for a second or more.
- Another system to run, upgrade, secure, and monitor.
- Duplicated permission logic, since the engine must filter results by what the user may see.
Choose one when a concrete requirement from the list above cannot be met in PostgreSQL, not because search "feels like" a separate concern. A sound sequence is to start with built-in search, add pg_trgm for typos, measure, and move to an engine only when the numbers or the feature list force it.
Exercise
Your articles table has 8 million rows. A search for the common word "database" is slow even though the GIN index is used. EXPLAIN ANALYZE shows 2 million rows returned by the bitmap scan and a large sort on ts_rank. Name the cause and two ways to reduce it without leaving PostgreSQL.
Show answer
The GIN index finds matching rows quickly, but ts_rank must read the tsvector of every one of the 2 million matches and sort them before LIMIT applies. To reduce the work, narrow the match set with additional filters such as a date range or category, or reject or deprioritize very common words with a stop-word list or minimum query specificity. Rank only a capped subset of matches, or send search traffic to a read replica. If none of these is acceptable and relevance tuning is also needed, consider an external engine.