Full-text search in Postgres before reaching for Elasticsearch
I loaded my own blog posts into Postgres 18 and built search on them with tsvector, a GIN index, ranking, highlighted snippets and pg_trgm for typos, then called it from Go. Plus the numbers that tell you when it's time for a real search engine.
Sooner or later every app gets a search box. The first version is always WHERE title ILIKE '%' || $1 || '%', and it's fine until somebody searches for "ghost backups" and my post about backing up a Ghost blog doesn't show up, because those two words are never next to each other in the title. Or the table gets big and every search is a full scan. The usual next step people suggest is Elasticsearch. That's a whole cluster to run for a search box.
In this blog we will look at what Postgres can do on its own first: tsvector, a GIN index, ranking, highlighted snippets, and pg_trgm for typos. Then a small Go function that uses it, and when I'd actually move to a search engine. Level is intermediate, you should know basic SQL and have read something like Postgres index design. I used Postgres 18.7 in the postgres:18 Docker image, Go 1.27.3 and pgx v5.13.0.
Some real text to search
Searching made-up lorem ipsum doesn't teach you much, ranking only gets interesting with real writing. So I loaded the Tech posts from this blog: 28 published posts, title and Markdown body, code blocks stripped. A small Python script turned the folders into one INSERT with dollar quoting, so quotes and apostrophes in the posts didn't need any escaping.
docker run -d --name fts-pg -e POSTGRES_PASSWORD=secret postgres:18
docker exec -it fts-pg psql -U postgres
tsvector and tsquery
Full-text search works on two types. A tsvector is a document turned into a sorted list of normalised words (lexemes) with their positions. A tsquery is the search, also normalised.
SELECT to_tsvector('english', 'Nightly backups were running on the servers');
'backup':2 'night':1 'run':4 'server':7
"backups" became backup, "running" became run, and "were", "on", "the" are gone as stop words. That stemming is why a search for "backup" will find "backups" now. It's also a bit odd sometimes. "Nightly" became night, and later on I noticed "caddy" turns into caddi. It doesn't matter as long as the query goes through the same stemmer, which it does.
For the query side, use websearch_to_tsquery. It accepts what people actually type into a search box: quotes for phrases, or, and a minus to exclude. It never throws a syntax error on odd input, unlike to_tsquery.
SELECT websearch_to_tsquery('english', 'ghost backups -mysql');
SELECT websearch_to_tsquery('english', '"systemd timer" or cron');
'ghost' & 'backup' & !'mysql'
'systemd' <-> 'timer' | 'cron'
The table and the index
I store the tsvector in a generated column so it's always in step with the text, and index it with GIN. Title words get weight A and body words weight B, so a match in the title ranks higher.
My first try was without STORED, since Postgres 18 now has virtual generated columns and makes them the default. That failed in the first run itself.
CREATE TABLE t (title text, search tsvector GENERATED ALWAYS AS (to_tsvector('english', title)));
CREATE INDEX ON t USING gin (search);
ERROR: indexes on virtual generated columns are not supported
So on 18, write STORED. Before 18 the keyword was required anyway, so older examples all have it, but if you trim it on 18 you quietly get a virtual column and the index fails.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
slug text NOT NULL UNIQUE,
title text NOT NULL,
body text NOT NULL,
search tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', title), 'A') ||
setweight(to_tsvector('english', body), 'B')
) STORED
);
CREATE INDEX posts_search_idx ON posts USING gin (search);
The 'english' has to be written in the expression. A generated column needs an immutable expression, and the one-argument to_tsvector(text) depends on the default_text_search_config setting, so Postgres won't accept it.
Searching and ranking
The match operator is @@. ts_rank scores how well a row matches, using the weights.
SELECT slug, ts_rank(search, q) AS rank
FROM posts, websearch_to_tsquery('english', 'backup snapshots') q
WHERE search @@ q
ORDER BY rank DESC
LIMIT 5;
slug | rank
---------------------------------------------------------------------+-------------
daily-ebs-snapshots-with-data-lifecycle-manager-in-terraform | 0.66195
migrating-a-ghost-cli-blog-to-docker-compose-with-caddy-and-mysql-8 | 0.34328216
nightly-mysql-and-content-backups-to-s3-with-a-systemd-timer | 0.34268957
automatic-https-and-www-redirects-for-a-ghost-blog-using-caddy | 0.086922765
importing-hand-built-aws-resources-into-terraform | 4e-16
That's a sensible order only. The snapshots post really is the best answer, and the backups post is right there. The last row made me laugh a bit, a rank of 4e-16 is Postgres saying "technically it matches". You could cut those off with a minimum rank.
ts_rank looks at how often the words appear. ts_rank_cd also looks at how close together they are, and the third argument 32 scales the result into 0 to 1. For "terraform" the top result was the same with both, the import post, but the middle of the list moved around. Try both on your own data and pick by eye. There is no right answer here.
Snippets with ts_headline
Search results need a snippet with the matched words marked.
SELECT slug, ts_headline('english', body, q,
'MaxFragments=1, MaxWords=18, MinWords=8, StartSel=[, StopSel=]') AS snippet
FROM posts, websearch_to_tsquery('english', 'systemd timer') q
WHERE search @@ q
ORDER BY ts_rank(search, q) DESC
LIMIT 2;
backup I set up: a bash script, a [systemd] [timer], and an S3 bucket in Terraform.
Two warnings from doing this. ts_headline works on the raw text, so my snippets had Markdown in them, a ## The bucket heading came along in one. Store a plain text copy of the body if that bothers you. And by default it wraps matches in <b> and </b> but does nothing to the rest of the text. If the body can contain HTML and you put the snippet straight into a page, you have an XSS bug. Escape the snippet first, then add your own highlight markers, or use markers like [ ] as above and swap them after escaping.
ts_headline is also the slow part, it re-parses the whole document. Only call it on the rows you show, which the LIMIT takes care of.
Does the index help
28 rows is nothing, so I copied the posts 360 times to get 10,108 rows, 100 MB of table with a 10 MB GIN index. Then I searched for "supertrend", which is in one post.
EXPLAIN (ANALYZE, COSTS OFF)
SELECT count(*) FROM posts WHERE search @@ websearch_to_tsquery('english', 'supertrend');
I ran it three ways. These are the execution times from my laptop.
GIN index (Bitmap Index Scan on posts_search_idx) 0.379 ms
seq scan over the stored tsvector column 20.895 ms
seq scan calling to_tsvector() on title and body per row 5999.763 ms
Six seconds against a third of a millisecond. The last one is what you get when you skip the stored column and write to_tsvector('english', title || ' ' || body) @@ ... in the query. See, every search re-parses every document. That's the number to remember.
Typos with pg_trgm
Full-text search matches words, not spelling. Searching "terrafrom" finds nothing.
SELECT count(*) FROM posts WHERE search @@ websearch_to_tsquery('english', 'terrafrom');
0
pg_trgm splits text into three-letter pieces (trigrams) and compares how many two strings share. show_trgm('terraform') gives {" t"," te",afo,err,for,orm,raf,"rm ",rra,ter}. The trick I like is to keep a table of every word in the documents and use trigrams on that, as a "did you mean".
CREATE TABLE search_words AS
SELECT word, ndoc FROM ts_stat($$SELECT to_tsvector('simple', title || ' ' || body) FROM posts$$);
CREATE INDEX search_words_trgm_idx ON search_words USING gin (word gin_trgm_ops);
SELECT word, ndoc, round(similarity(word, 'terrafrom')::numeric, 2) AS sim
FROM search_words WHERE word % 'terrafrom'
ORDER BY sim DESC, ndoc DESC LIMIT 3;
The 'simple' config keeps words as written, without stemming, so the suggestion is a real word. On my posts this gave 2,962 words. "terrafrom" came back as terraform with a similarity of 0.43, and "snapshts" as snapshots at 0.58. % uses pg_trgm.similarity_threshold, 0.3 by default.
It's not magic. Now what happens is, for "zerodah" the top answer was zerodha at 0.45, but zero was right behind at 0.44. Short words share a lot of trigrams with everything. Sorting by ndoc as a tie breaker helps, the real word usually appears in more documents.
You can also put a trigram index straight on the title, which handles partial words too. word_similarity and the <% operator compare against the best matching part of the string. Searching "ollma" in titles found nothing at first, the best score was 0.50 and the default pg_trgm.word_similarity_threshold is 0.6. After SET pg_trgm.word_similarity_threshold = 0.4 both Ollama posts showed up. You will tune these numbers for your data, the defaults are a bit strict for typos.
Calling it from Go
The Go side is a normal query. If there are no hits, it fixes each word with the trigram table and tries once more.
const searchSQL = `
SELECT slug, ts_rank(search, q) AS rank,
ts_headline('english', body, q, 'MaxFragments=1, MaxWords=18, MinWords=8') AS snippet
FROM posts, websearch_to_tsquery('english', $1) q
WHERE search @@ q
ORDER BY rank DESC
LIMIT $2`
const suggestSQL = `
SELECT word FROM search_words
WHERE word % $1
ORDER BY similarity(word, $1) DESC, ndoc DESC
LIMIT 1`
// suggest fixes each word of the query on its own, so "terrafrom imprt"
// becomes "terraform import".
func suggest(ctx context.Context, db *pgxpool.Pool, query string) (string, error) {
words := strings.Fields(strings.ToLower(query))
for i, w := range words {
var best string
err := db.QueryRow(ctx, suggestSQL, w).Scan(&best)
if err == nil {
words[i] = best
}
}
return strings.Join(words, " "), nil
}
The search function scans rows into a small struct, and main calls suggest when search returns nothing. The pattern is the same as in Talking to Postgres from Go with pgx and sqlc, so I won't repeat it. I built it for linux, copied the binary into the container and ran it there.
no results for "terrafrom imprt", showing "terraform import"
0.988 importing-hand-built-aws-resources-into-terraform
write <b>imports</b> as code instead of running `<b>terraform</b> <b>import</b>` one resource at a time. I put them
Two typos in, the right post out. Note the <b> tags in the snippet, that's the escaping problem from above.
When to move to a search engine
Postgres search basically took me an evening and has no new moving parts. I'd stay on it while these hold:
- the search runs over one or a few tables, in one language per column
- results in tens of milliseconds are fine
- you don't need facets with counts across millions of rows, synonyms managed by non developers, or "more like this"
- the write load from updating the
tsvectoris small next to everything else
When those break, OpenSearch or Elasticsearch earns its keep. Relevance tuning is much richer there, and fuzzy matching is built in instead of bolted on. But you then have to keep a second copy of the data in sync, which is its own project (the outbox pattern is the way I'd do it). Watch the search queries in pg_stat_statements and let the numbers tell you when.