Nov 23, 20265 min read

Fuzzy Search and Autocomplete in Postgres with pg_trgm

How trigram similarity finds "keybaord" when the product is called "Keyboard", which index to create, how similarity thresholds work, and a TypeScript search endpoint on Encore.

Illustration for Fuzzy Search and Autocomplete in Postgres with pg_trgm

A search box backed by ILIKE '%term%' works until users typo or type longer phrases: "keybaord", "headfones", "iphone 15 pro max". Exact substring matching misses all of those and scans the whole table on every keystroke.

The pg_trgm extension compares strings by three-character sequences, tolerates typos and adds an index that also speeds up plain ILIKE. This guide covers both and builds a search endpoint in TypeScript.

How does trigram matching work?

pg_trgm splits a string into trigrams, groups of three consecutive characters after lowercasing and padding words with spaces. "cat" becomes " c", " ca", "cat" and "at ". Two strings that share many trigrams are similar, and a typo only breaks the few trigrams around it, so "keybaord" still shares most of its trigrams with "keyboard".

The extension gives you two scores. similarity(a, b) compares the whole strings, which works for matching names of similar length. word_similarity(query, value) compares the query with the best matching stretch of the value, which is what search boxes need: "headfones" scored 0.5 against "Wireless Headphones" with word_similarity but only 0.30 with similarity on local Postgres 17.

Which index should you create?

A GIN index with the gin_trgm_ops operator class:

CREATE EXTENSION IF NOT EXISTS pg_trgm; CREATE INDEX products_name_trgm ON products USING gin (name gin_trgm_ops);

This one index serves LIKE and ILIKE with wildcards on both sides, regular expression matches and the trigram operators % (similarity) and <% (word similarity). A GiST index with gist_trgm_ops also supports ordering by distance (ORDER BY name <-> 'query') directly from the index, at the cost of slower lookups and larger size, so GIN is the usual default for search boxes. On a local Postgres 17 table of 350,000 product names, a query combining a prefix ILIKE and a <% typo match ran in about 3 ms through a BitmapOr over this GIN index.

How do similarity thresholds work?

The % and <% operators return true when the score is above a threshold: pg_trgm.similarity_threshold (default 0.3) and pg_trgm.word_similarity_threshold (default 0.6). The default for word similarity is strict enough that "headfones" does not match "Wireless Headphones". Lower it to around 0.3 to 0.4 for search boxes, and set it with SET LOCAL inside a transaction so the setting stays with that query and does not leak to other requests sharing the connection pool.

How do you build autocomplete on top?

Combine a prefix match with the fuzzy match and rank prefix hits first, since a user who has typed "keyb" expects "Keyboard" items at the top. Escape % and _ in user input before building the ILIKE pattern, cap the result count, and only query once the input has two or three characters. Below that, trigram scores carry little signal and nearly every row matches.

For long text such as articles or support tickets, use Postgres full-text search instead, since it understands words, stemming and ranking. Trigrams are for short fields: names, titles, SKUs, cities and email addresses.

Fuzzy search with Encore

Encore

Encore is a backend framework with built-in infrastructure, so the search table, the extension and the endpoint that queries them are all in one TypeScript service. The Postgres database enables pg_trgm in a migration, and the extension is part of the Encore Postgres image that encore run starts locally, so local search behaves like production on RDS or Cloud SQL in your own cloud account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- catalog/migrations/1_create_products.up.sql CREATE EXTENSION IF NOT EXISTS pg_trgm; CREATE TABLE products ( id BIGSERIAL PRIMARY KEY, name TEXT NOT NULL ); CREATE INDEX products_name_trgm ON products USING gin (name gin_trgm_ops);
// catalog/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("catalog");
// catalog/search.ts import { api, APIError, Query } from "encore.dev/api"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { MinLen, MaxLen } from "encore.dev/validate"; const db = new SQLDatabase("catalog", { migrations: "./migrations" }); interface SearchParams { q: Query<string & MinLen<2> & MaxLen<100>>; } interface Hit { id: number; name: string; score: number; } const escapeLike = (s: string) => s.replace(/[\\%_]/g, (c) => "\\" + c); export const search = api( { expose: true, method: "GET", path: "/catalog/search" }, async ({ q }: SearchParams): Promise<{ hits: Hit[] }> => { const term = q.trim(); // Check the trimmed term, so a query of spaces cannot become a match-all pattern. if (term.length < 2) throw APIError.invalidArgument("query must be at least 2 characters"); const prefix = escapeLike(term) + "%"; await using tx = await db.begin(); await tx.exec`SET LOCAL pg_trgm.word_similarity_threshold = 0.35`; const hits = await tx.queryAll<Hit>` SELECT id, name, word_similarity(${term}, name)::float8 AS score FROM products WHERE name ILIKE ${prefix} OR ${term} <% name ORDER BY (name ILIKE ${prefix}) DESC, score DESC, name LIMIT 10`; await tx.commit(); return { hits }; }, );

encore run starts Postgres locally and applies the migration, so you can seed a few thousand rows and try typos against the endpoint right away, and the query plan and timing for each search show up in the local trace. The validation types reject one-character queries before they reach the database, which keeps autocomplete from scanning the index for nearly every row.

When an agent tunes the threshold or adds a second searchable column, the migration and the query change in the same diff, and it can check the new ranking against seeded data locally rather than guessing from the SQL.

Best fit: Apps that need typo-tolerant search over names and titles and want it running in their own Postgres database before considering a separate search service.

Frequently asked questions

How do you do fuzzy search in Postgres?

Enable the pg_trgm extension, create a GIN index on the column with gin_trgm_ops, and filter with the % or <% operators, ordering by similarity or word_similarity. The index makes both the typo-tolerant match and ILIKE '%term%' searches fast.

What is the difference between similarity and word_similarity?

similarity compares the whole search string with the whole column value, so short queries against long names score low. word_similarity compares the search string with the best matching part of the value, which suits autocomplete and searches for one word inside a longer title.

Is pg_trgm better than full-text search?

No, they solve different problems. Full-text search understands words, stemming and ranking across long documents, while pg_trgm matches character sequences and tolerates typos in short fields such as names, titles and SKUs. Many apps use full-text search for content and trigrams for names.

How do I add fuzzy search with Encore?

Enable pg_trgm and create the GIN index in a migration for an Encore Postgres database, then query it from an endpoint that sets pg_trgm.word_similarity_threshold with SET LOCAL inside a transaction. encore run starts Postgres locally with the extension available.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders