Skip to content

Full-text search in PostgreSQL with tsvector and tsquery

Build a production full-text search in PostgreSQL — generated tsvector columns, GIN indexes, ranking, multilingual dictionaries, and operational care.

PostgreSQL’s full-text search is good enough that a lot of applications skip a separate search service entirely. The pieces are tsvector (a normalised, ranked vector of lexemes), tsquery (a parsed query expression), the @@ operator that matches them, GIN as the index, and configurable language dictionaries that handle stemming and stop-words. This article covers the build that holds in production — generated columns, ranking, multilingual content, and what to watch when the table grows.

How to verify

Confirm dictionaries are available and the column is indexed:

psql -d app -c "SELECT * FROM pg_ts_config;"
psql -d app -c "\d documents"
psql -d app -c "SELECT to_tsvector('english', 'PostgreSQL is a database');"
psql -d app -c "EXPLAIN (ANALYZE, BUFFERS)
                SELECT id FROM documents
                WHERE search_vector @@ to_tsquery('english','postgres & database')
                ORDER BY ts_rank(search_vector, to_tsquery('english','postgres & database')) DESC
                LIMIT 10;"

The EXPLAIN should show Bitmap Index Scan using ... gin. If it shows a sequential scan, the index isn’t being used.

What’s happening

to_tsvector('english', 'PostgreSQL is a database') produces something like 'databas':4 'postgresql':1. The english configuration applies the English stemmer (Snowball), removes stop-words (“is”, “a”), and lowercases. Each lexeme gets a position used for phrase queries and proximity ranking. to_tsquery('english', 'postgres & database') parses the query the same way: stem, strip stops, build a boolean expression with &, |, !, and <-> (proximity).

The @@ operator returns true if every required lexeme in the query appears in the vector. GIN indexes the vector — one posting list per lexeme, lookup is O(lexemes-in-query). ts_rank and ts_rank_cd score how well a vector matches; the cover-density variant gives more weight to clusters of matching terms.

The choice of configuration is the most consequential decision. english doesn’t handle French; french doesn’t handle quoted technical terms. For mixed content, you either pick a “simple” configuration (no stemming, exact match only) or maintain multiple vectors.

The procedure

  1. Add a generated tsvector column on PG 12+:

    ALTER TABLE documents ADD COLUMN search_vector tsvector
      GENERATED ALWAYS AS (
        setweight(to_tsvector('english', coalesce(title, '')),       'A') ||
        setweight(to_tsvector('english', coalesce(subtitle, '')),    'B') ||
        setweight(to_tsvector('english', coalesce(body, '')),        'C')
      ) STORED;
    
    CREATE INDEX documents_search_gin
      ON documents USING GIN (search_vector);

    setweight assigns A/B/C/D so ts_rank_cd can weight title matches above body matches. The column is STORED — it occupies disk but is computed automatically on INSERT and UPDATE.

  2. Query with ranking:

    SELECT id, title,
           ts_rank_cd(search_vector, query) AS rank,
           ts_headline('english', body, query) AS snippet
    FROM documents,
         to_tsquery('english', 'postgres <-> tuning | performance') query
    WHERE search_vector @@ query
    ORDER BY rank DESC
    LIMIT 20;

    ts_headline returns the body with <b> tags around matched terms — useful for the search-results snippet.

  3. Use websearch_to_tsquery for user input:

    SELECT id FROM documents
    WHERE search_vector @@ websearch_to_tsquery('english', $1);

    This parses Google-style input ("exact phrase" -excluded OR another) without throwing syntax errors on user queries — to_tsquery is unforgiving.

  4. For multilingual content, store the language with the row:

    ALTER TABLE documents ADD COLUMN content_lang regconfig NOT NULL DEFAULT 'simple';
    
    ALTER TABLE documents ADD COLUMN search_vector tsvector
      GENERATED ALWAYS AS (
        setweight(to_tsvector(content_lang, coalesce(title, '')), 'A') ||
        setweight(to_tsvector(content_lang, coalesce(body, '')),  'C')
      ) STORED;

    Each row’s vector is built with the right dictionary. Query-side, derive content_lang from the search context or use multiple queries.

  5. Tune GIN for high write rate:

    ALTER TABLE documents SET (gin_pending_list_limit = '16MB');

    See GIN tuning notes.

  6. Maintain. Schedule REINDEX INDEX CONCURRENTLY documents_search_gin quarterly on busy tables — GIN bloats steadily. Pair with autovacuum and VACUUM ANALYZE to keep stats fresh.

Common pitfalls

  • A misconfigured dictionary (using english on French content) silently returns wrong results — the query parses without error but matches nothing. Verify with SELECT to_tsvector(config, sample_text) for known content.
  • Stop-words (“the”, “is”) are dropped — searching for “to be or not to be” returns empty in english config. Use the simple config for verbatim search.
  • ts_rank is slow on result sets larger than a few thousand rows because it ranks every match. Add a LIMIT and an ORDER BY with a tie-breaker.
  • Generated columns can’t reference other tables — denormalise the searchable fields onto the row or maintain via a trigger.
  • tsvector is limited to ~1 MB per value; very long documents (entire books) need chunking.

In the engagements we run, Postgres full-text search is the answer for application-level search up to a few tens of millions of documents and a few dozen QPS. We push to a dedicated search service (Meilisearch, OpenSearch) only when we need faceting, typo-tolerance, or scale beyond what GIN can serve. The generated-column + GIN + ranking pattern is our default starting point. For the operating model behind a Postgres-led app stack, see managed operations.