TL;DR: For many applications, PostgreSQL's built-in full-text search plus the
pg_trgmextension is enough to replace a separate Elasticsearch cluster.to_tsvectorgives you stemmed, ranked matches, and trigram word similarity with a GIN index catches typos such as "iphne" for "iPhone". Search stays transactionally consistent with your data, and you avoid running a sync pipeline. This guide shows tested SQL and a Node.js endpoint, plus the cases where a dedicated search engine is still the better tool.
Key Takeaways
- Replace
ILIKE '%query%'sequential scans with PostgreSQL'sto_tsvectorandwebsearch_to_tsqueryfunctions for stemmed word matching using the@@operator. - Pre-compute and store search vectors in a
GENERATED ALWAYScolumn indexed with GIN to drastically reduce query latency. - Apply
setweight()(e.g., 'A' for titles, 'B' for descriptions) to your vectors to rank and prioritize specific fields in search results. - Enable the
pg_trgmextension and use the word similarity operator<%for typo tolerance. Plain%compares the whole string, so a short query rarely reaches the 0.3 threshold against a multi-word title. - Change trigram thresholds with
SET LOCALinside a transaction so the setting never leaks to other requests through the connection pool. - GIN indexes with
gin_trgm_opsare the usual choice for trigram search. GiST (gist_trgm_ops) is an alternative that also supports distance-ordered (<->) queries; benchmark both on your data and write rate.
You launched your Node.js application backed by PostgreSQL. Everything was fast. Then, your users asked for a search bar, and you started with the classic, naive SQL approach: SELECT * FROM products WHERE name ILIKE '%query%';.
A leading-wildcard ILIKE cannot use a regular B-tree index, so every search scans the table. As the table grows, search latency and database CPU grow with it.
To fix it, you reached for the industry-standard sledgehammer: Elasticsearch.
Suddenly, your architecture went from a simple Node.js and PostgreSQL stack to a distributed system. You had to run an Elasticsearch cluster and build a sync path, often Change Data Capture (CDC) with Debezium and Kafka, to keep your Postgres source of truth and your search index in step. Now there are two copies of the data that can disagree, another stateful system to upgrade, monitor and size, and another bill.
You are now managing a distributed data synchronization pipeline just so a user can type "johhn" and find "John".
For many applications, especially those searching product names, titles and short descriptions, this is more machinery than the problem needs. PostgreSQL ships with Full-Text Search (FTS), and the pg_trgm contrib extension adds trigram matching, which together cover stemming, ranking and typo tolerance.
Let's build typo-tolerant search entirely inside PostgreSQL and Node.js. Every SQL statement below was run against PostgreSQL 18.
The Foundation: Lexemes and PostgreSQL Full-Text Search
Standard B-tree indexing relies on exact or prefix matches. Full-Text Search (FTS) instead works on lexemes: normalized words with stop words removed and suffixes stripped by a language-specific stemmer (for example, "foxes" becomes "fox" and "jumping" becomes "jump"). This is linguistic normalization, not semantic understanding: synonyms do not match unless you configure a thesaurus dictionary.
To see this in action, we use the to_tsvector and to_tsquery functions.
-- Convert a string into a searchable vector of lexemes
SELECT to_tsvector('english', 'The quick brown foxes are jumping over the lazy dogs');
/*
Output:
'brown':3 'dog':10 'fox':4 'jump':6 'lazi':9 'quick':2
*/
-- Query the vector using tsquery
SELECT to_tsvector('english', 'The quick brown foxes') @@ to_tsquery('english', 'fox & quick');
-- Output: true
Tip: The
@@operator is the core of Postgres FTS. It checks if atsquerymatches atsvector. Notice how "foxes" was stemmed to "fox", allowing a query for "fox" to match successfully.
Computing vectors on the fly for every row in every query is wasteful. Instead, we compute, store, and index them. A GIN (Generalized Inverted Index) maps lexemes to the rows that contain them, drastically speeding up lookups.
-- Add a generated column to store the vector
ALTER TABLE products
ADD COLUMN search_vector tsvector
GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(description, '')), 'B')
) STORED;
-- Create the GIN index for rapid retrieval
CREATE INDEX idx_products_search_vector ON products USING GIN (search_vector);
By assigning weights ('A' for title, 'B' for description), we can later rank results so that a match in the title appears higher than a match in the description. Adding a stored generated column rewrites the table, so on a large production table run it in a maintenance window or add a regular column, backfill it in batches and keep it updated with a trigger.
Beating Typos with pg_trgm (Trigram Indexing)
Postgres FTS handles word variants well, but it does not tolerate typos. If a user searches for "focks" instead of "fox", to_tsquery will return no results.
This is where pg_trgm helps. A trigram is a group of three consecutive characters extracted from a string. By comparing the overlapping trigrams between two strings, Postgres can determine their similarity.
First, enable the extension:
-- pg_trgm is a trusted extension (PostgreSQL 13+): a user with CREATE
-- privilege on the database can install it without superuser rights
CREATE EXTENSION IF NOT EXISTS pg_trgm;
-- See how trigrams are generated (lowercased, padded, sorted)
SELECT show_trgm('PostgreSQL');
/*
Output:
{" p"," po",esq,gre,ost,pos,"ql ",res,sql,stg,tgr}
*/
To use trigrams for indexed fuzzy matching, we create a GIN index with the gin_trgm_ops operator class.
-- Create a trigram index on the title column
CREATE INDEX idx_products_title_trgm ON products USING GIN (title gin_trgm_ops);
-- Whole-string similarity vs. word similarity for a typo
SELECT title,
similarity(title, 'iphne') AS sim, -- whole title vs. query
word_similarity('iphne', title) AS word_sim -- best-matching part of the title
FROM products;
/*
title | sim | word_sim
---------------+------------+----------
iPhone 15 Pro | 0.25 | 0.5
Iphone case | 0.2857143 | 0.5
Android phone | 0.05263158 | 0.16666667
*/
This output shows the trap most tutorials fall into. The % operator compares the query with the whole title and only matches at similarity >= 0.3, so title % 'iphne' returns nothing here. For searching a short query inside longer text, use word similarity and its operator <%, which compares the query with the best-matching run of words in the title. Its default threshold (pg_trgm.word_similarity_threshold) is 0.6, which is strict for typos, so we lower it per transaction in the next section. The same GIN index serves both operators.
Production Note: GIN trigram indexes add write overhead on
INSERTandUPDATE; GIN'sfastupdatepending list softens this at the cost of occasional cleanup work. GiST (gist_trgm_ops) is the other option and additionally supports ordering by distance with<->. The PostgreSQL documentation does not declare a universal winner, so benchmark both with your data and write rate.
Constructing the Hybrid Search Architecture in SQL
Elasticsearch gives you analyzed full-text matching and fuzzy matching out of the box. To get both in Postgres, we combine the tsvector index (stemmed word matches) with the trigram index (typo tolerance) and calculate a combined score.
BEGIN;
-- Applies to this transaction only, so it cannot leak through a connection pool
SET LOCAL pg_trgm.word_similarity_threshold = 0.4;
WITH search_query AS (
SELECT 'iphne' AS user_input, -- The user's typo
websearch_to_tsquery('english', 'iphne') AS tsq
)
SELECT
p.id,
p.title,
ts_rank(p.search_vector, sq.tsq) AS fts_rank,
word_similarity(sq.user_input, p.title) AS trgm_sim,
-- Combined score: weight FTS matches above trigram matches
ts_rank(p.search_vector, sq.tsq) * 2.0 + word_similarity(sq.user_input, p.title) AS final_score
FROM products p
CROSS JOIN search_query sq
WHERE p.search_vector @@ sq.tsq -- stemmed full-text match
OR sq.user_input <% p.title -- typo-tolerant word match (uses the trigram index)
ORDER BY final_score DESC
LIMIT 20;
COMMIT;
/*
id | title | fts_rank | trgm_sim | final_score
----+---------------+----------+----------+-------------
1 | iPhone 15 Pro | 0 | 0.5 | 0.5
2 | Iphone case | 0 | 0.5 | 0.5
*/
The 2.0 weight and the 0.4 threshold are starting points, not tuned values. Collect real queries and adjust them against results your users actually click.
Notice the use of websearch_to_tsquery. Unlike to_tsquery, which raises a syntax error on malformed operator input, websearch_to_tsquery never raises a syntax error for raw user input. It supports a syntax similar to web search engines: quoted phrases, or, and - for exclusion. For example, "quick fox" -dog or cat becomes 'quick' <-> 'fox' & !'dog' | 'cat'.
Implementing the Search API in Node.js
Writing the SQL is only half the battle. To expose this to your frontend, we need to wire it up in Node.js.
Raw parameterized queries through node-postgres (pg) are a good fit for search: ranking expressions, operators like <% and SET LOCAL are awkward or impossible to express through most ORM query builders. If you want help designing the search API and schema together, our backend API development services cover that work.
Here is an Express route implementing the hybrid search with parameterized queries and validated paging:
const { Pool } = require('pg');
const express = require('express');
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 20, // Connection pool size
});
const app = express();
app.get('/api/search', async (req, res) => {
const { q } = req.query;
if (typeof q !== 'string' || q.trim().length === 0 || q.length > 200) {
return res.status(400).json({ error: 'q must be a non-empty string up to 200 characters' });
}
// Clamp paging values so bad input cannot request huge result sets
const limit = Math.min(Math.max(Number.parseInt(req.query.limit, 10) || 20, 1), 50);
const offset = Math.min(Math.max(Number.parseInt(req.query.offset, 10) || 0, 0), 1000);
// Define our SQL query with parameterized inputs to prevent SQL Injection
const searchQuery = `
SELECT
id,
title,
description,
price,
ts_rank(search_vector, websearch_to_tsquery('english', $1)) AS fts_rank,
word_similarity($1, title) AS trgm_sim
FROM products
WHERE
search_vector @@ websearch_to_tsquery('english', $1)
OR $1 <% title
ORDER BY (
ts_rank(search_vector, websearch_to_tsquery('english', $1)) * 2.0 +
word_similarity($1, title)
) DESC, id
LIMIT $2 OFFSET $3;
`;
const client = await pool.connect();
try {
// SET LOCAL only lasts until COMMIT, so pooled connections stay clean
await client.query('BEGIN');
await client.query('SET LOCAL pg_trgm.word_similarity_threshold = 0.4');
const { rows } = await client.query(searchQuery, [q, limit, offset]);
await client.query('COMMIT');
res.json({
data: rows,
meta: {
count: rows.length,
query: q,
},
});
} catch (error) {
await client.query('ROLLBACK').catch(() => {});
console.error('Search failure:', error);
res.status(500).json({ error: 'Internal Server Error' });
} finally {
client.release();
}
});
Security & Performance Note: Never run a plain
SET pg_trgm.word_similarity_threshold = ...on a pooled connection. A session-levelSETstays on that connection after it returns to the pool and silently changes results for later requests.SET LOCALinside a transaction, as above, is scoped to that transaction. Alternatively, set the value for a dedicated database role withALTER ROLE ... SET.Warning: Be careful with
OFFSETpagination on large datasets. If users frequently click to page 500 of your search results, the database still has to compute and sort all previous records. For large datasets, implement Keyset Pagination (cursor-based pagination) using thefinal_scoreandidas cursors.
Benchmarking, Cost Savings, and Infrastructure Strategy
Why go through the effort of consolidating this into PostgreSQL? It comes down to two factors: System Reliability and Infrastructure Cost.
If you rely on Elasticsearch, you are paying for and operating a separate cluster, whether self-managed, Amazon OpenSearch Service or Elastic Cloud. A highly available setup needs several nodes across availability zones, and its cost depends heavily on data size, replicas and instance types, so price it with your provider's calculator rather than a rule of thumb.
Syncing data between Postgres and Elasticsearch, whether through CDC (Kafka and Debezium) or dual writes, adds moving parts and a consistency gap. When the sync lags, a user updates their product in your app, searches for it immediately, and sees the old version. With Postgres, search is transactionally consistent: once the COMMIT returns, queries see the new row through the index.
Before you compare third-party search tools like Algolia or Elastic, check that your Postgres query actually uses its indexes with EXPLAIN ANALYZE, on production-sized data:
EXPLAIN ANALYZE
SELECT title
FROM products
WHERE 'iphne' <% title;
/* Plan shape to look for (timings depend on your data and hardware):
Bitmap Heap Scan on products
Filter: ('iphne'::text <% title)
-> Bitmap Index Scan on idx_products_title_trgm
Index Cond: (title %> 'iphne'::text)
*/
A Bitmap Index Scan on the trigram index means the query is not scanning the whole table. If you see Seq Scan on a large table instead, check the operator (<% and % are indexable, the similarity() function in a WHERE clause is not) and that the extension's operator class matches the index.
A dedicated search engine starts to earn its operational cost when:
- Search load or index size is large enough that it competes with your transactional workload on the primary database (read replicas can delay this point).
- You need faceted navigation and aggregations across many fields with low latency.
- You need language analyzers, synonyms, per-field fuzziness, or learning-to-rank relevance tuning beyond what
ts_rankand trigrams offer.
Until then, combining tsvector, pg_trgm, and a small Node.js API gives you typo tolerance, stemming, and transactional consistency with one less system to run.
Sources
- PostgreSQL documentation: pg_trgm (similarity vs. word similarity, thresholds, GIN and GiST operator classes, trusted extension)
- PostgreSQL documentation: Controlling Text Search (
websearch_to_tsquery,ts_rank,setweight) - PostgreSQL documentation: Generated Columns
- PostgreSQL documentation: SET (
SET LOCALscope) - node-postgres: Transactions
Need help building this in production?
SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.
Get a Free ConsultationFrequently Asked Questions
Can PostgreSQL full-text search replace Elasticsearch?
For many product search needs, yes: tsvector handles stemming and ranking, and pg_trgm adds typo tolerance. Elasticsearch still wins for very large corpora, complex relevance tuning, faceted analytics, and multi-language analysers at scale.
How does pg_trgm make search typo-tolerant?
It splits text into three-character sequences and measures how many two strings share, so "postgers" still matches "postgres". For short queries against longer text, use word similarity (<%) rather than whole-string similarity (%). A GIN or GiST trigram index keeps these searches fast.
Should I combine full-text search and trigram matching?
Yes. Full-text search gives good ranking for correctly spelled words, and trigram similarity catches misspellings and partial matches. Run both and merge the results with a weighted score.
How much can dropping Elasticsearch save?
You remove a separate cluster and the pipeline that keeps it in sync with your database. The hosting saving depends on cluster size, and the operational saving of one less stateful system to upgrade, monitor and back up can matter as much as the bill. Check first that the extra search load fits on your PostgreSQL instance.
