Skip to main content

Databases · Intermediate · 22 min

Add full-text search to a PostgreSQL database

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · PostgreSQL 18.7

You will make 20,000 product descriptions searchable in PostgreSQL 18 with a weighted tsvector column, a GIN index, ranked and highlighted results, accent-insensitive matching and typo suggestions, all behind one SQL function your app can call.

On this page

A search box on a shop, a help centre or an internal tool usually starts life as WHERE description ILIKE '%' || :term || '%'. That works until the table grows, someone searches for "phones" and misses every row that says "phone", or a customer types "cafe" and the catalogue says "café". PostgreSQL has a full search engine built in that handles all of this, and for many apps it is enough for years.

In this tutorial you build search for a shop catalogue of 20,000 products. You start with the two core functions, to_tsvector and to_tsquery, then accept free-form input from a search box, store a weighted search column, index it and measure the difference. After that you rank and highlight results, make accents irrelevant, suggest corrections for typos, and wrap the whole thing in one function. The last step says when you would move to a dedicated search engine.

You need PostgreSQL 18 on Ubuntu 26.04, installed as in /tutorials/install-postgresql-18-on-ubuntu-26-04. PostgreSQL 19.0 was released on 19 November 2026; everything here works the same on it. Timings in this tutorial depend on your hardware, so compare your own before and after numbers rather than matching the ones described.

Step 1 · Create a catalogue of 20,000 products

Create a database called shop and a products table with a name and a description. The rows are generated with generate_series from fixed lists of words, so everyone gets the same catalogue: ten materials, eleven kinds of product, nine colours, and descriptions built from two sentences each. About one description in seven mentions "café-style coffee", which you will need later.

Bash
sudo -u postgres createdb shop
sudo -u postgres psql -d shop -v ON_ERROR_STOP=1 <<'SQL'
CREATE TABLE products (
  id          integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name        text NOT NULL,
  description text NOT NULL
);

INSERT INTO products (name, description)
SELECT
  (ARRAY['Solar', 'Clay', 'Bamboo', 'Steel', 'Cotton',
         'Leather', 'Copper', 'Cedar', 'Woven', 'Enamel'])[1 + g % 10]
    || ' ' ||
  (ARRAY['lantern', 'kettle', 'basket', 'backpack', 'mug', 'sandals',
         'charger', 'blanket', 'stool', 'radio', 'grinder'])[1 + g % 11]
    || ', ' ||
  (ARRAY['black', 'sand', 'indigo', 'red', 'green',
         'white', 'grey', 'ochre', 'teal'])[1 + g % 9],
  (ARRAY['Charges two phones a day from sunlight.',
         'Makes strong café-style coffee in four minutes.',
         'Keeps drinks hot for six hours.',
         'Hand woven by a cooperative of twelve weavers.',
         'Survives drops, dust and heavy rain.',
         'Folds flat for travel and storage.',
         'Runs for a week on one charge.'])[1 + g % 7]
    || ' ' ||
  (ARRAY['Pairs well with our clay kettle.',
         'Easy to clean with warm water.',
         'Made from recycled materials.',
         'Comes with a two-year guarantee.',
         'Light enough to carry all day.',
         'Sold in packs of two.',
         'Suits small kitchens and shared flats.',
         'Popular with market traders.',
         'Repairs are free for the first year.',
         'Designed for unreliable power.',
         'Gift wrapped on request.',
         'Ships within two working days.',
         'Each piece is slightly different.'])[1 + g % 13]
FROM generate_series(1, 20000) AS g;

ANALYZE products;
SQL

The commands in this tutorial use sudo -u postgres psql with either -c for one statement or a heredoc for several. -v ON_ERROR_STOP=1 makes psql stop at the first error rather than carry on. If you prefer an interactive session, open one with sudo -u postgres psql -d shop and paste the SQL at the shop=# prompt.

Check it worked

Bash
sudo -u postgres psql -d shop -c "SELECT id, name, description FROM products ORDER BY id LIMIT 3;"

You see three rows. The first is Clay kettle, sand, with a description that starts "Makes strong café-style coffee". If createdb says the database already exists, you ran this step before; drop it with sudo -u postgres dropdb shop and run the step again.

Step 2 · Match words with to_tsvector and to_tsquery

Full-text search compares two things. A tsvector is a document reduced to its lexemes: words lower-cased, stemmed to a root form, with common words such as "a" and "from" removed, and each kept with its position. A tsquery is a search reduced the same way, joined with operators. The @@ operator asks whether a document matches a query.

See what PostgreSQL makes of one description:

Bash
sudo -u postgres psql -d shop -c "SELECT to_tsvector('english', 'Charges two phones a day from sunlight.');"

You get something like 'charg':1 'day':5 'phone':3 'sunlight':7 'two':2. "Charges" became charg and "phones" became phone. "a" and "from" are gone, but they still use up positions 4 and 6, which matters for phrase searches.

The first argument, 'english', is the text search configuration. It decides the stemmer and the list of stop words. Always name it: without it PostgreSQL uses the server's default_text_search_config setting, which can differ between servers, and a search column built with one configuration will not reliably match queries built with another.

Now search the whole table. In to_tsquery, & means AND, | means OR, ! means NOT and <-> means "followed by":

Bash
sudo -u postgres psql -d shop -c "SELECT count(*) FROM products WHERE to_tsvector('english', description) @@ to_tsquery('english', 'charge & phone');"

The query word "charge" stems to charg too, so it matches "Charges two phones". A plain ILIKE '%charge%phone%' would have missed every row that said "phones charged".

Run the same search under EXPLAIN ANALYZE and note the Execution Time. You will compare it with the indexed version later.

Bash
sudo -u postgres psql -d shop -c "EXPLAIN (ANALYZE, COSTS OFF) SELECT id FROM products WHERE to_tsvector('english', description) @@ to_tsquery('english', 'charge & phone');"

The plan is a Seq Scan on products. PostgreSQL reads every row and runs to_tsvector on every description, for every search. That parsing is the slow part.

Check it worked

The count is 2857: every product whose description starts "Charges two phones". Write down the Execution Time from the plan.

Step 3 · Accept what people type with websearch_to_tsquery

to_tsquery expects its own syntax. Give it two words separated by a space, which is what every person types into a search box, and it fails:

Bash
sudo -u postgres psql -d shop -c "SELECT to_tsquery('english', 'solar charger');"

PostgreSQL answers ERROR: syntax error in tsquery. Never pass raw user input to to_tsquery. Use websearch_to_tsquery instead. It never raises a syntax error and understands the conventions people already know from web search engines: words are ANDed, "quoted words" must appear as a phrase, or between words means either, and a leading - excludes a word.

Bash
sudo -u postgres psql -d shop -c "SELECT websearch_to_tsquery('english', 'solar charger -leather \"two phones\"');"

The result is something like 'solar' & 'charger' & !'leather' & 'two' <-> 'phone'. Try it against the table, this time searching the name and the description together:

Bash
sudo -u postgres psql -d shop -c "SELECT id, name FROM products WHERE to_tsvector('english', name || ' ' || description) @@ websearch_to_tsquery('english', 'solar charger \"two phones\"') ORDER BY id LIMIT 5;"

Two other query functions exist. plainto_tsquery ANDs every word and ignores punctuation, and phraseto_tsquery treats the whole input as one phrase. websearch_to_tsquery is the best default for a search box.

Check it worked

Every row returned is a Solar charger whose description starts "Charges two phones". If you see syntax error in tsquery, check that you called websearch_to_tsquery, not to_tsquery.

Step 4 · Store a weighted search column

Computing to_tsvector on every search is wasted work: the descriptions rarely change. Store the result in a generated column instead, and PostgreSQL keeps it up to date on every INSERT and UPDATE.

A match in a product's name should count for more than a match in its description. setweight labels lexemes with a weight from A (highest) to D (lowest), and || joins two tsvectors into one. Adding a stored column rewrites the table and holds an exclusive lock while it does, so reads and writes to it wait. That takes a moment here and much longer on a big table, so on a busy production table plan it for a quiet time. Add the column:

Bash
sudo -u postgres psql -d shop -v ON_ERROR_STOP=1 <<'SQL'
ALTER TABLE products
  ADD COLUMN search tsvector
  GENERATED ALWAYS AS (
    setweight(to_tsvector('english', name), 'A') ||
    setweight(to_tsvector('english', description), 'B')
  ) STORED;

ANALYZE products;
SQL

The word STORED matters. In PostgreSQL 18, a generated column without it is virtual: computed each time it is read, which is the slow path you are trying to leave, and not something you can index for search. If either column could be NULL, wrap it in coalesce(name, ''), because a NULL joined with || makes the whole vector NULL.

Look at one row's search column:

Bash
sudo -u postgres psql -d shop -c "SELECT name, search FROM products WHERE id = 1;"

The name's lexemes carry an A (for example 'kettl':2A) and the description's carry a B.

Queries now use the column directly:

Bash
sudo -u postgres psql -d shop -c "EXPLAIN (ANALYZE, COSTS OFF) SELECT id FROM products WHERE search @@ websearch_to_tsquery('english', 'solar charger');"

Check it worked

The plan is still a Seq Scan, but its Execution Time is lower than the one you wrote down, because there is no parsing left to do. PostgreSQL still reads all 20,000 rows to find fewer than two hundred. Write this time down too.

Step 5 · Index the column with GIN and measure

A GIN (generalised inverted) index stores, for each lexeme, the list of rows that contain it, which is how a book's index works. It is the index type PostgreSQL recommends for text search. On a table with live traffic, write CREATE INDEX CONCURRENTLY instead, so the build does not block writes; here the table is yours alone, so the plain form is fine. Create it:

Bash
sudo -u postgres psql -d shop -c "CREATE INDEX products_search_idx ON products USING gin (search);"

Run the same query again:

Bash
sudo -u postgres psql -d shop -c "EXPLAIN (ANALYZE, COSTS OFF) SELECT id FROM products WHERE search @@ websearch_to_tsquery('english', 'solar charger');"

The plan now has a Bitmap Index Scan on products_search_idx feeding a Bitmap Heap Scan. The index finds the rows that contain both solar and charger, and PostgreSQL only visits those. Compare the three Execution Time figures: parsing on the fly, stored column with a full scan, and stored column with the index. The last is typically a fraction of a millisecond, and the gap widens as the table grows.

A GIN index costs something on writes, because every new or changed row updates one index entry per distinct lexeme. Check its size:

Bash
sudo -u postgres psql -d shop -c "SELECT pg_size_pretty(pg_relation_size('products_search_idx')) AS index_size, pg_size_pretty(pg_relation_size('products')) AS table_size;"

Check it worked

The plan names products_search_idx. A search for a very common word, such as water, may still use a Seq Scan: when a large share of the table matches, reading it all is cheaper, and the planner is right to choose that.

Step 6 · Rank results and highlight the matching words

A match is a yes or no. To put the best results first, rank them. ts_rank_cd scores a row by how often and how close together the query's words appear, and it multiplies each match by its weight: by default A counts 1.0, B 0.4, C 0.2 and D 0.1. ts_headline returns a piece of the original text with the matching words marked.

Search for "kettle", which appears in some names and in the description sentence "Pairs well with our clay kettle":

Bash
sudo -u postgres psql -d shop -v ON_ERROR_STOP=1 <<'SQL'
SELECT id, name,
       round(rank::numeric, 2) AS rank,
       ts_headline('english', description, query, 'StartSel=[, StopSel=]') AS snippet
FROM (
  SELECT p.id, p.name, p.description, query, ts_rank_cd(p.search, query) AS rank
  FROM products AS p, websearch_to_tsquery('english', 'kettle') AS query
  WHERE p.search @@ query
  ORDER BY rank DESC, p.id
  LIMIT 5
) AS top
ORDER BY rank DESC, id;
SQL

The five rows all have "kettle" in both the name and the description, so they share the top score: 1.0 for the name match plus 0.4 for the description match. About 140 products are in that group, so a top five cannot show anything below it. The snippet shows the description with [kettle] marked.

To see the whole ranking, count the matches at each score:

Bash
sudo -u postgres psql -d shop -c "SELECT round(ts_rank_cd(search, query)::numeric, 2) AS rank, count(*) FROM products, websearch_to_tsquery('english', 'kettle') AS query WHERE search @@ query GROUP BY 1 ORDER BY 1 DESC;"

There are three tiers: 1.40 for "kettle" in both fields, 1.00 for the name only, and 0.40 for the description only.

Two details in that query are deliberate:

  • The inner query ranks and limits first, and the outer one calls ts_headline on the five rows left. ts_headline works on the original text, not the tsvector, so it is slow. Run it on the page of results you show, never on every match.
  • StartSel and StopSel set the markers. On a web page you might use <mark> and </mark>, but ts_headline does not escape the rest of the text, so any HTML in a description would reach the browser as HTML. Escape the snippet in your app, then swap your own markers for tags.

Check it worked

The first query shows five kettles that all share the top rank of 1.40; that is expected, not a fault. The tiers query shows three distinct scores, 1.40, 1.00 and 0.40. If it shows only one score, check that the search column was built with setweight.

Step 7 · Make "cafe" find "café" with unaccent

Search for "cafe", the way most people type it on a phone keyboard:

Bash
sudo -u postgres psql -d shop -c "SELECT count(*) FROM products WHERE search @@ websearch_to_tsquery('english', 'cafe');"

The count is 0, although thousands of descriptions say "café". To the English stemmer they are different words. The unaccent extension removes accents, and the clean way to use it is inside your own text search configuration, so it applies to documents and queries alike. Create the extension and a configuration called shop_english that copies english and runs words through unaccent before stemming:

Bash
sudo -u postgres psql -d shop -v ON_ERROR_STOP=1 <<'SQL'
CREATE EXTENSION IF NOT EXISTS unaccent;

CREATE TEXT SEARCH CONFIGURATION shop_english (COPY = english);
ALTER TEXT SEARCH CONFIGURATION shop_english
  ALTER MAPPING FOR hword, hword_part, word
  WITH unaccent, english_stem;
SQL

word, hword and hword_part are the parser's token types for words that contain non-ASCII letters, including hyphenated ones like "café-style". Plain ASCII words do not need the extra step. Check the new configuration:

Bash
sudo -u postgres psql -d shop -c "SELECT to_tsvector('shop_english', 'Makes strong café-style coffee');"

The lexemes now include 'cafe'. Point the search column at the new configuration. SET EXPRESSION rewrites every row and rebuilds the index, so on a large table run it at a quiet time:

Bash
sudo -u postgres psql -d shop -v ON_ERROR_STOP=1 <<'SQL'
ALTER TABLE products
  ALTER COLUMN search SET EXPRESSION AS (
    setweight(to_tsvector('shop_english', name), 'A') ||
    setweight(to_tsvector('shop_english', description), 'B')
  );

ANALYZE products;
SQL

From now on, every query must use shop_english as well. A query built with english against a column built with shop_english runs without error and quietly misses rows.

Bash
sudo -u postgres psql -d shop -c "SELECT count(*) FROM products WHERE search @@ websearch_to_tsquery('shop_english', 'cafe');"

If your catalogue holds names in Yoruba, Hausa, Swahili or other languages, two notes. unaccent strips many accents and tone marks, but test it on samples of your own text with SELECT unaccent('...'); before relying on it. And PostgreSQL ships stemmers for a fixed list of languages (see them with \dF in psql); for a language that is not on it, build that column with the simple configuration, which lower-cases words without stemming them.

Check it worked

The count for "cafe" now equals the number of descriptions that contain "café", and a search for "café" with the accent returns the same rows.

Step 8 · Suggest corrections for typos with pg_trgm

Full-text search matches whole lexemes, so "backpak" finds nothing. The pg_trgm extension measures how alike two strings are by the three-letter sequences (trigrams) they share. Rather than running fuzzy matching over every description, build a list of the distinct words in the catalogue and offer the closest one as "Did you mean ...?".

Bash
sudo -u postgres psql -d shop -v ON_ERROR_STOP=1 <<'SQL'
CREATE EXTENSION IF NOT EXISTS pg_trgm;

CREATE MATERIALIZED VIEW search_words AS
  SELECT word, ndoc
  FROM ts_stat($$SELECT to_tsvector('simple', public.unaccent(name || ' ' || description)) FROM public.products$$);

CREATE INDEX search_words_trgm_idx ON search_words USING gin (word gin_trgm_ops);
SQL

ts_stat lists every lexeme in a set of tsvectors with the number of rows it appears in (ndoc). The simple configuration keeps whole words rather than stems, so a suggestion is a real word, and unaccent keeps the list in line with the search column. The names inside the query are written as public.products and public.unaccent because PostgreSQL builds and refreshes a materialized view with a locked-down search_path that leaves out the public schema, so short names fail with relation "products" does not exist. Now ask for the closest words to a typo:

Bash
sudo -u postgres psql -d shop -c "SELECT word, round(similarity(word, 'backpak')::numeric, 2) AS score FROM search_words WHERE word % 'backpak' ORDER BY score DESC, ndoc DESC LIMIT 3;"

% keeps words whose similarity is above pg_trgm.similarity_threshold, 0.3 by default, and the trigram index makes that filter fast on a large word list. Raise the threshold (SET pg_trgm.similarity_threshold = 0.4;) if suggestions are too loose. A materialized view does not update itself: run REFRESH MATERIALIZED VIEW search_words; after a bulk import or on a nightly schedule.

Check it worked

The first suggestion is backpack, with a score around 0.6. Searching for the suggested word with websearch_to_tsquery('shop_english', 'backpack') returns rows again.

Step 9 · Wrap search in one function your app can call

Your application should not repeat this SQL in several places. Put the search query in a function, so every caller gets the same configuration, ranking and snippet rules:

Bash
sudo -u postgres psql -d shop -v ON_ERROR_STOP=1 <<'SQL'
CREATE OR REPLACE FUNCTION search_products(search_text text, max_rows integer DEFAULT 10)
RETURNS TABLE (product_id integer, product_name text, snippet text, score real)
LANGUAGE sql STABLE
AS $fn$
  SELECT top.id, top.name,
         ts_headline('shop_english', top.description, top.tsq, 'StartSel=[, StopSel=]'),
         top.r
  FROM (
    SELECT p.id, p.name, p.description, tsq, ts_rank_cd(p.search, tsq) AS r
    FROM products AS p, websearch_to_tsquery('shop_english', search_text) AS tsq
    WHERE p.search @@ tsq
    ORDER BY r DESC, p.id
    LIMIT least(max_rows, 50)
  ) AS top
  ORDER BY top.r DESC, top.id;
$fn$;
SQL

Call it with what a person typed:

Bash
sudo -u postgres psql -d shop -c "SELECT * FROM search_products('cafe kettle', 5);"

From your app, pass the search text as a query parameter (SELECT * FROM search_products($1, $2)), never by pasting it into the SQL string. When the function returns no rows, query search_words as in the previous step and offer the suggestion. The least(max_rows, 50) cap keeps a caller from asking for thousands of rows at once. Small pages of short snippets also keep each response light for people on prepaid mobile data or low-end Android phones.

When you would outgrow this

PostgreSQL search like this serves catalogues and document sets into the millions of rows. These are the signs it is time to look at a dedicated engine such as OpenSearch, Meilisearch or Typesense:

  • Common words get slow. Ranking has to score every matching row before it can sort, so a query that matches hundreds of thousands of rows does that work on every search, and the index does not help.
  • You need typo tolerance inside every query, faceted counts, synonyms or search-as-you-type on each keystroke, and the SQL to fake them is growing.
  • Search traffic starts to compete with the writes your app depends on, and you would rather scale it separately.

Before switching, measure: put the slow searches under EXPLAIN (ANALYZE, BUFFERS) as in /tutorials/speed-up-slow-postgres-queries-with-explain.

Check it worked

You see up to five rows. Each is a product whose name or description mentions a kettle and whose description mentions café-style coffee, with the matching words marked in square brackets in the snippet. A search for a word that is not in the catalogue returns no rows rather than an error.

Next steps

  • Search fields inside JSON documents as well as plain text: /tutorials/store-and-query-json-in-postgresql-with-jsonb.
  • Add meaning-based matching alongside keyword search: /tutorials/combine-keyword-and-vector-search-in-postgresql.
  • Find out which searches are slow in production with pg_stat_statements: /tutorials/speed-up-slow-postgres-queries-with-explain.

When you are finished, remove the practice database with sudo -u postgres dropdb shop.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.