# Postgres full-text search in practice: tsvector, GIN, websearch_to_tsquery, and the queries that silently return nothing

A hands-on guide to PostgreSQL full-text search: a stored tsvector column with weights, a GIN index, websearch_to_tsquery for raw user input, ts_rank and ts_headline. Covers the five mistakes that make search return zero rows or skip the index, with timings on 200,000 documents: about 900 ms for ILIKE, 14 seconds for to_tsvector at query time, and 2 ms with a GIN index. Every query tested on Postgres 17.11.

**Most apps need a search box long before they need a search cluster. Postgres has had full-text search built in for years: it splits text into words, reduces them to stems, drops stop words, ranks the matches and highlights them, and a GIN index keeps it fast. It is also easy to get subtly wrong. A query that works in `psql` returns nothing in production because the two sides used different language configurations; a search for "postgres" misses every row that says "PostgreSQL"; an index you created is never used because the query spells the expression differently. This post builds a working search on one table, in about 20 lines of SQL you can paste, then goes through five easy mistakes that make it return nothing or skip the index, and ends with timings on 200,000 documents: about 900 ms for `ILIKE`, 14 seconds for computing `to_tsvector` at query time, and 2 ms with a stored column and a GIN index. Every query and output here was replayed on PostgreSQL 17.11, the major version Relyt One runs.**

## The short version

- **Store**: A `tsvector` column `GENERATED ALWAYS AS (...) STORED`. Computing `to_tsvector` per query is what makes search slow.
- **Configure**: Always pass the configuration: `to_tsvector('english', ...)`. The one-argument form depends on a server setting and cannot be indexed.
- **Index**: `CREATE INDEX ... USING gin (search)`. GIN is the preferred index type for text search.
- **Parse input**: `websearch_to_tsquery('english', $1)`. It never raises a syntax error, and understands quotes, `or` and `-`.
- **Rank**: `ORDER BY ts_rank(search, q) DESC LIMIT n`. Weights let title matches beat body matches.
- **Snippets**: `ts_headline` on the rows you return. It re-parses the original text, so it is slow per row.
- **Typos**: `pg_trgm` for "did you mean". Full-text search matches whole lexemes, not similar spellings.

## How it works in one picture

Full-text search does not compare strings. Both the document and the query are turned into **lexemes**: normalized word stems, with stop words like "with" and "the" removed. A document matches when its lexemes satisfy the query, using the `@@` operator.

![The document "Connection pooling with PgBouncer" becomes 'connect' 'pgbouncer' 'pool' through to_tsvector('english', …); the search box text "connection pooling" becomes 'connect' & 'pool' through websearch_to_tsquery('english', …); the @@ operator matches them; a GIN index maps each lexeme to the rows that contain it.](/blog/assets/16591c2ad2207d8f.svg)

You can see the normalization directly:

```sql
SELECT to_tsvector('english', 'The quick brown foxes jumped over the lazy dogs');
--  'brown':3 'dog':9 'fox':4 'jump':5 'lazi':8 'quick':2

SELECT to_tsvector('simple', 'The quick brown foxes jumped over the lazy dogs');
--  'brown':3 'dogs':9 'foxes':4 'jumped':5 'lazy':8 'over':6 'quick':2 'the':1,7
```

The `english` configuration stems ("foxes" becomes `fox`, "jumped" becomes `jump`) and drops stop words. The `simple` configuration only lowercases. The numbers are word positions, which phrase search and some ranking functions use.

This is also why full-text search is not a faster `ILIKE`. `ILIKE '%cat%'` matches "Concatenate"; a full-text search for `cat` does not, because "concatenate" is a different word:

```sql
SELECT 'Concatenate two arrays' ILIKE '%cat%' AS ilike_hit,
       to_tsvector('english', 'Concatenate two arrays') @@ to_tsquery('english', 'cat') AS fts_hit;
--  ilike_hit | fts_hit
--  t         | f
```

## A working search in about 20 lines

Here is the whole setup. The `search` column is computed by Postgres on every insert and update, so application code never has to remember it:

```sql
CREATE TABLE articles (
  id     bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  title  text NOT NULL,
  body   text,
  search tsvector GENERATED ALWAYS AS (
    setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
    setweight(to_tsvector('english', coalesce(body,  '')), 'B')
  ) STORED
);
CREATE INDEX articles_search_idx ON articles USING gin (search);
```

Three details carry most of the weight:

- **`setweight`** labels title lexemes `A` and body lexemes `B`, so ranking can prefer title matches.
- **`coalesce`** matters because `body` can be `NULL`, and `to_tsvector(NULL)` is `NULL`. Concatenating `NULL` onto the title vector makes the whole column `NULL`, and the row can never be found, not even by its title.
- **`'english'`** is written out. More on that below.

We loaded eight short articles, one-paragraph summaries of posts on this blog, one of them with no body. A search reads like this:

```sql
SELECT id, title, round(ts_rank(search, q)::numeric, 4) AS rank
FROM articles, websearch_to_tsquery('english', 'connection pooling') AS q
WHERE search @@ q
ORDER BY rank DESC, id;
```

```text
 id |               title               |  rank
----+-----------------------------------+--------
  1 | Connection pooling with PgBouncer | 0.9973
  5 | Job queues with SKIP LOCKED       | 0.3964
```

Article 1 has both words in its title; article 5 only mentions "No connection pooling tricks needed" in its body. Both match because `&` does not care about order or distance, and the title weight puts article 1 on top.

### Parse user input with websearch_to_tsquery

Postgres has four functions that build a `tsquery`. For a search box, use `websearch_to_tsquery`. The older `to_tsquery` expects query syntax and fails on ordinary input:

```sql
SELECT to_tsquery('english', 'why is postgres slow');
-- ERROR:  syntax error in tsquery: "why is postgres slow"

SELECT websearch_to_tsquery('english', 'why is postgres slow');
--  'postgr' & 'slow'
```

The documentation says `websearch_to_tsquery` "will never raise syntax errors, which makes it possible to use raw user-supplied input for search". It also understands the syntax people already type into search engines:

```sql
SELECT websearch_to_tsquery('english', '"connection pooling" -pgbouncer or index');
--  'connect' <-> 'pool' & !'pgbouncer' | 'index'
```

Quotes become a phrase (`<->` means "followed by"), `-` excludes a word, and `or` is an OR. The phrase `"connection pooling"` matches both of our articles, while `"pooling connection"` matches neither, because order matters inside quotes.

### Show snippets with ts_headline

```sql
SELECT id, ts_headline('english', body, q, 'MaxFragments=1, MaxWords=12, MinWords=5') AS snippet
FROM articles, websearch_to_tsquery('english', 'connection pooling') AS q
WHERE search @@ q
ORDER BY ts_rank(search, q) DESC, id;
```

```text
 id |                                         snippet
----+-----------------------------------------------------------------------------------------
  1 | Transaction <b>pooling</b> lets thousands of clients share a few server <b>connections</b>. Session
  5 | process the same job. No <b>connection</b> <b>pooling</b> tricks needed
```

`ts_headline` returns HTML-like markup around matches, and the rest of the snippet is your raw document text: the documentation warns its output "is not guaranteed to be safe for direct inclusion in web pages". If you render it as HTML, either HTML-escape the document before passing it to `ts_headline`, or set `StartSel` and `StopSel` to markers that cannot occur in your text, escape the whole snippet, and then replace the markers with tags.

## Five ways search silently returns nothing (or ignores your index)

### 1. The two sides use different configurations

A document indexed with `english` and a query parsed with `simple` disagree about what a word is:

```sql
SELECT to_tsvector('english', 'running migrations') @@ to_tsquery('simple', 'running') AS mixed,
       to_tsvector('english', 'running migrations') @@ to_tsquery('english', 'running') AS both_english;
--  mixed | both_english
--  f     | t
```

The `english` side stored `run`; the `simple` side asks for `running`. No error, just no rows. This happens most often through the one-argument forms, `to_tsvector(text)` and `to_tsquery(text)`, which use the `default_text_search_config` setting. Its value is chosen when the cluster is initialized and can differ between your laptop, CI and production, or be changed per session. Our test container reports `pg_catalog.english`; yours might not. Write the configuration name everywhere and the question goes away.

### 2. The index uses a different expression from the query

The one-argument form also cannot be indexed at all:

```sql
CREATE INDEX ON articles USING gin (to_tsvector(body));
-- ERROR:  functions in index expression must be marked IMMUTABLE
```

And when you index an expression instead of a stored column, the query must repeat that exact expression. The PostgreSQL documentation puts it plainly: only a query that uses the two-argument `to_tsvector` "with the same configuration name will use that index". On our 200,000-document table with a GIN index on the stored column, a query that spelled the vector as `to_tsvector('english', title || ' ' || body)` took **13 to 14 seconds** with a sequential scan. The same search against the column took **2 ms**. A stored generated column removes this whole class of mistake: there is only one way to write `search @@ q`.

### 3. A NULL column wipes out the whole vector

Shown above, but it deserves its own entry because it fails silently and only for some rows:

```sql
SELECT to_tsvector('english', 'Draft without a body') || to_tsvector('english', NULL::text);
--  (null)
```

Wrap every nullable column in `coalesce(col, '')` inside the generated expression.

### 4. Partial words and different word forms do not match

Lexemes match whole. A user typing `connec` gets nothing; add `:*` to ask for a prefix match:

```sql
SELECT count(*) FROM articles WHERE search @@ to_tsquery('english', 'connec');    -- 0
SELECT count(*) FROM articles WHERE search @@ to_tsquery('english', 'connec:*');  -- 2
```

Stemming has its own surprise. The `english` stemmer turns "Postgres" into `postgr` but leaves "PostgreSQL" as `postgresql`, so a search for `postgres` does not find an article titled "Upgrading PostgreSQL". A prefix query finds both:

```sql
INSERT INTO articles (title, body) VALUES
  ('Upgrading PostgreSQL', 'Major version upgrades with pg_upgrade or logical replication.');

SELECT title FROM articles WHERE search @@ websearch_to_tsquery('english', 'postgres');
--  Why Postgres is not using your index

SELECT title FROM articles WHERE search @@ to_tsquery('english', 'postgres:*');
--  Why Postgres is not using your index
--  Upgrading PostgreSQL
```

`websearch_to_tsquery` has no prefix syntax. For search-as-you-type, build the prefix query yourself from the last word the user typed, and quote it so characters like `&`, `|`, `!` and `'` cannot break the syntax: `to_tsquery('english', quote_literal($1) || ':*')`. Two inputs still need handling in your code: skip the prefix query when the word is empty (`'':*` is a syntax error), and strip backslashes first (`quote_literal` turns them into an `E'...'` string that `to_tsquery` reads as an extra word). The opposite problem also exists: stemming can merge words you consider different. "universe", "university" and "universal" all become `univers`.

### 5. A query made only of stop words matches nothing

```sql
SELECT count(*) FROM articles WHERE search @@ websearch_to_tsquery('english', 'the who');
-- NOTICE:  text-search query contains only stop words or doesn't contain lexemes, ignored
--  count
--  0
```

"The Who" is a band; to the `english` configuration it is two stop words, so the query is empty and matches no rows. If your users search for names like this, fall back to another strategy (an `ILIKE` on the title, or a `simple`-configuration column) when the parsed query is empty. You can test for that with `numnode(q) = 0`.

## How fast is it? 200,000 documents, measured

We generated 200,000 documents in a fresh `postgres:17.11-alpine` container: a 6-word title and an 80-word body each, drawn from about 1,660 distinct words taken from Postgres's own catalog comments (mostly English, plus language and country names and some Postgres jargon) with a skewed distribution so that some words are very common and most are rare. The table, including the stored `tsvector` column, is 391 MB. Parallel query was turned off so the numbers reflect a single core. We ran the whole benchmark twice, each time in a fresh container, three runs per query, and report the median and range of those six runs. The machine is an Apple M1 Pro laptop with 5 CPUs and 12 GB given to Docker, on default Postgres settings, so read the numbers as relative, not as what your server will do.

If you want to reproduce it, this is the generator:

```sql
-- about 1,660 distinct words from Postgres's own catalog comments
CREATE TABLE vocab AS
SELECT row_number() OVER (ORDER BY w) AS n, w
FROM (SELECT DISTINCT lower(w) AS w
      FROM pg_description, regexp_split_to_table(description, '[^A-Za-z]+') AS w
      WHERE length(w) >= 3) s;

SELECT setseed(0.42);
CREATE TABLE docs (
  id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  title text NOT NULL,
  body  text NOT NULL
);
-- random()^3 skews the choice: a few words are very common, most are rare
INSERT INTO docs (title, body)
SELECT
  (SELECT string_agg(x.w, ' ') FROM (SELECT v.a[1 + floor(v.c * random()^3)::int] AS w
                                     FROM generate_series(1, 6 + 0 * g)) x),
  (SELECT string_agg(x.w, ' ') FROM (SELECT v.a[1 + floor(v.c * random()^3)::int] AS w
                                     FROM generate_series(1, 80 + 0 * g)) x)
FROM generate_series(1, 200000) g,
     (SELECT array_agg(w ORDER BY n) AS a, count(*) AS c FROM vocab) v;

ALTER TABLE docs ADD COLUMN search tsvector GENERATED ALWAYS AS (
  setweight(to_tsvector('english', title), 'A') ||
  setweight(to_tsvector('english', body),  'B')
) STORED;
VACUUM ANALYZE docs;
SET max_parallel_workers_per_gather = 0;
```

The test search is a single word, `zulu`, that appears in 3,452 documents (about 1.7%). `ILIKE` only looked at the body, where it found 3,191 rows; the full-text queries search title and body.

| Approach                    | Median (ms) | Range (ms)      |
| --------------------------- | ----------- | --------------- |
| ILIKE on the body           | 898         | 865 – 992       |
| to_tsvector in the query    | 13,755      | 13,443 – 14,246 |
| Stored column, no index     | 53          | 50 – 93         |
| Stored column + GIN         | 1.8         | 1.6 – 2.7       |
| Two words (77 matches), GIN | 0.29        | 0.26 – 0.42     |

Three things stand out. Computing `to_tsvector` at query time is by far the slowest option, more than ten times slower than `ILIKE`, because it parses and stems 200,000 documents on every search. Storing the vector alone makes a sequential scan fast enough for small tables. The GIN index brings a selective search down to about 2 ms, because the lookup grows with the number of matching rows rather than the size of the table (the next section shows what happens with a very common word). Building it took about 3 seconds (2.7 and 3.0 s in the two runs) and it is 44 MB, about 11% of the table.

The stored column has a cost too: Postgres computes it on every insert and every update of the row. Adding it to the 200,000 existing rows took about 17 seconds, and `ALTER TABLE ... ADD COLUMN` holds an `ACCESS EXCLUSIVE` lock while it runs, blocking reads and writes on the table. On a large production table, plan for that the way you would plan any [migration that takes a heavy lock](/blog/postgres-migration-locks).

### Ranking cost grows with the number of matches

An index finds matching rows; it does not rank them. `ORDER BY ts_rank(...) LIMIT 10` has to compute the rank for every match and keep the top ten:

| Top 10 for | Matches | Median (ms) | Range (ms) |
| ---------- | ------- | ----------- | ---------- |
| zulu       | 3,452   | 3.2         | 2.5 – 16.1 |
| access     | 108,222 | 79          | 78 – 86    |

For `access`, which appears in more than half of the documents, the planner skipped the index entirely: reading the whole table is cheaper than visiting more than half of it through the index. That is the right choice, and around 80 ms is still acceptable, but it shows where Postgres full-text search runs out of room: very common terms on very large tables, ranked across every match. Tighter queries (two words instead of one) and filters that narrow the candidates first (tenant, date range, category) are the usual fix.

### ts_headline: costly per row, but only if you let it run on every row

The documentation warns that `ts_headline` "uses the original document, not a tsvector summary, so it can be slow and should be used with care". We measured it three ways for `zulu`:

| Query shape                       | Rows highlighted | Median (ms) | Range (ms) |
| --------------------------------- | ---------------- | ----------- | ---------- |
| In the select list, with LIMIT 10 | 10               | 3.7         | 3.1 – 4.8  |
| Top 10 picked in a subquery first | 10               | 3.3         | 3.1 – 3.5  |
| Every match, no LIMIT             | 3,452            | 201         | 200 – 202  |

The old advice is to wrap the ranked query in a subquery and call `ts_headline` outside it. On modern Postgres the planner does this for you: since 9.6 it can "postpone evaluation of SELECT output expressions until after an ORDER BY sort", so with a `LIMIT` the headline ran only 10 times either way. The cost shows up when nothing limits it: about 58 µs per document here, 200 ms for all 3,452 matches (one run each in the two containers). So paginate, and do not compute snippets for rows you will not show.

## When Postgres full-text search is not enough

It is a good default, and for many apps it is all you need. Reach for something else when:

- **You need typo tolerance.** Full-text search has no fuzzy matching: `pgbouncr` finds nothing. The `pg_trgm` extension can find similar words, for example to build a "did you mean" from the indexed vocabulary (`ts_stat` lists it), and in our test it suggested `pgbouncer` for `pgbouncr` with a similarity of 0.58.
- **You need relevance tuning at scale.** `ts_rank` knows term frequency and weights; it does not use corpus statistics like BM25, and the ranking functions read every match as shown above.
- **Your documents are very large.** A single `tsvector` must be smaller than 1 MB, positions stop at 16,383, and each lexeme keeps at most 256 positions.
- **You need semantic search.** Lexemes match words, not meaning. That is what vector search is for, and combining the two is a topic for another post.

If you do outgrow it, it is usually after search has proven its value, and you will know exactly which queries need more.

## Try it on a branch

Everything in this post is plain PostgreSQL 17: no extension is needed except `pg_trgm` for the typo example, and Relyt One provides that one. The part that is risky on a real database is not the queries but the migration: adding a stored column and building an index on a large, busy table. On Relyt One you can do that rehearsal on a branch first. A branch starts from the parent's data with copy-on-write storage and runs on its own compute, so you can measure how long the `ALTER TABLE` and `CREATE INDEX` take on your real data, try a different configuration or weights, compare the search results, and throw the branch away.

[Start for free](/auth/signin?ref=blog-postgres-full-text-search)
