PostgreSQL full-text search

Build search on PostgreSQL's built-in full-text search with tsvector, tsquery, dictionaries and GIN indexes, and know when an external engine such as OpenSearch is worth running.

On this page

When PostgreSQL full-text search is enough for your application

PostgreSQL full-text search identifies the documents that match a query and sorts them by relevance, and for many application search needs it removes the need to run a second system. If your team already operates PostgreSQL and needs search over support tickets, internal documents, product catalogs or contract records, the built-in feature is the first option to test. Its dictionaries normalize tokens into lexemes, so a query for "running" can match text that contains "run". The PostgreSQL documentation describes standard dictionaries that ship with the server and custom dictionaries you can create for your own vocabulary, such as product codes, internal project names or domain terms that stemming would otherwise mangle.

The feature fits best when the searchable corpus lives in tables you already maintain, when search results must respect the same transactions, joins and row-level permissions as the rest of the application, and when query volume is moderate for your hardware. Searches can combine full-text conditions with ordinary SQL filters on status, owner, date or tenant, which is often the deciding advantage. Confirm the size of your corpus, the growth rate, and peak concurrent search load with a test on production-like data before you decide, because these figures, not the feature list, determine whether the database host has headroom.

Plan the test around your hardest queries, not your easiest ones. Include misspellings you expect users to type, phrase queries, multilingual content if you have it, and the highest-volume filters combined with search terms. Record the results, the ranking users expect and the latency you need. If those tests pass, the remaining work is schema and index design, which the following sections cover. If prefix matching, typo tolerance, faceted navigation or search across many separate systems is central to the product, the team should expect to evaluate a dedicated search engine instead.

How tsvector, tsquery and GIN indexes fit together

The request starts with raw text and a chosen language configuration, which a dictionary turns into lexemes and stores as a tsvector in a column or expression. A GIN index over that vector answers matches for a tsquery, and ranking then orders the matched rows before the application receives them. Everything up to the ranked result stays inside the PostgreSQL server. The dashed path to an external engine is optional and only exists when you choose to run one, so check which side of the boundary each sync job and each stored copy of your data falls on.

Query path inside PostgreSQL, with an optional external sync path shown dashed.

Configuration options and when each one fits

This table compares the main design choices for PostgreSQL full-text search: configuration, where the tsvector lives, index type and ranking function. Read each row for when the option fits, what it costs to change later, and what to confirm against the PostgreSQL version you run. The main takeaway is that the configuration name and the stored vector are the choices hardest to reverse once data and indexes exist.

DecisionWhen it fitsCost to change laterConfirm before deciding
Built-in language configuration (for example, a standard English configuration)Content is in one language and the standard stemming and stop word behavior is acceptable for users.Low to moderate. Changing the configuration means recomputing every stored vector and rebuilding dependent indexes.Which standard configurations and dictionaries ship with your PostgreSQL version and language packs.
Custom text search configuration with a tailored dictionary setDomain terms, product codes, synonyms or mixed-language content return poor matches under standard dictionaries.Moderate. Custom dictionaries and configurations must be maintained, backed up and deployed with the schema.How dictionary files are installed on your servers or managed services, and how they migrate across major upgrades.
Stored tsvector in a generated columnSearch is frequently queried and you want the vector kept current automatically by the database on every write.Moderate. Changing the expression or configuration rewrites the table and the column's index.Whether your PostgreSQL version supports the generated column form you plan to use and its restrictions on functions.
Stored tsvector maintained by a triggerYou need logic that a generated column cannot express, such as combining fields with conditional weights from other tables.Moderate to high. Trigger logic lives outside the table definition and must be tested after each change.Trigger behavior during bulk loads and restores, and how it interacts with your replication setup.
Expression GIN index computed at query timeThe table is small, writes are light, or you are prototyping and do not want a stored column yet.Low. The index expression is replaced, but every query must repeat the same expression to use the index.That query text matches the index expression exactly, since the planner depends on the match.
GIN index on the tsvectorMost search workloads with many lookups and fewer writes; the standard choice for full-text search.Low to moderate. Rebuilding is possible online, but large tables take time and extra disk space during the build.Index build and maintenance settings on your version, and monitoring of index size as the table grows.
GiST index on the tsvectorWrite-heavy tables where index update cost matters more than lookup speed, or when you need its specific features.Moderate. Switching between GIN and GiST requires building a new index and retesting query plans.Current guidance on GIN versus GiST trade-offs in the PostgreSQL documentation for your version.
ts_rank for rankingRanking by how often query terms appear, with a simple, predictable order that is easy to explain to users.Low. Switching the ranking function changes result order only, not stored data.Behavior of weight arrays and normalization options on your version, tested on representative queries.
ts_rank_cd for rankingRanking should reward matches that appear close together, such as phrase-like queries over long documents.Low. Like ts_rank, it changes only the ordering logic in queries and can be swapped after testing.Results on your own sample of queries, since the better ordering depends on the content and users.

Designing the search document and language configuration

The first design decision is what goes into the searchable document, because PostgreSQL only searches what you place in a tsvector. Decide which columns contribute, typically a title, a summary and a body, and build the vector with to_tsvector or a stored generated column. Use setweight to label each source with a weight such as A for titles and D for low-value fields, so that ts_rank can rank a title match above a match buried in a long body. Keep the weighting rules in one function or view so that the indexing code and the query code cannot drift apart. Multilingual content needs a decision too: either store a regconfig value per row, which lets each document use its own dictionary, or fix the language per table or column when the content is known in advance. Confirm with your content owners how mixed-language rows, such as a German product description with English part names, will be classified.

The text search configuration determines how words are normalized. Each configuration chains parsers and dictionaries, so the stemmer decides that "installing" and "install" match, and the stop word list decides which common words are dropped before indexing. Review the stop word list for your domain, since a word that is noise in general prose may be meaningful in a legal, medical or engineering corpus. Product names, model numbers, internal project code names and acronyms are often mangled by a stemmer or dropped entirely. For these, create a custom dictionary, for example a synonym or thesaurus dictionary, and add it to a copy of the configuration. Test every change with a representative set of real queries from your users (illustrative: a search for a product code should return the product page) and record the expected results so that future changes can be checked against them.

Treat the configuration as a schema decision. Once the tsvector column and its GIN index hold data, changing the configuration, the weights or the dictionaries means recomputing every stored vector and rebuilding the index, which can take a long time on large tables and needs a plan for write load during the rebuild. Changing the dictionary or the language after launch also changes which queries match, so users may notice results shifting. Write the configuration name, the weighting scheme and the dictionary files into version control next to the migration that creates the column, and ask your team to confirm who approves a change. Where the answer is uncertain, a short pilot on a copy of production data will show the effect before the decision is locked in.

Setting up full-text search with a GIN index

This sequence takes a PostgreSQL database from an unindexed text column to a tested search path, with a GIN index, a documented text search configuration and ranked results. Each step ends with a check that the database and the application behave as expected before the feature is released.

  1. Confirm the PostgreSQL version and available features

    Confirm the PostgreSQL major version in each environment, from development through production, and check that the built-in text search configurations and dictionaries you plan to use are present. Your DBA or platform team does this with a query against the server, and the check is a short written record of the version, the installed extensions and the text search configurations available. Confirm the version is on a supported release line under the PostgreSQL versioning policy before you design around it, because a search design should not depend on a version that is about to leave support. If a dictionary you need is missing, ask the vendor or package maintainer before you build around it.

  2. Create the text search configuration

    Choose a language configuration for the content, such as a built-in language configuration for the main language of your documents, and create a custom configuration only when the standard one does not fit. Clone the base configuration, then attach dictionaries for stop words, stemming and any synonyms your domain needs. Record the configuration name, because every expression index and query must reference the same one. The output is a named configuration that can be inspected in the database, with its token mapping listed in the same place where you keep the schema migrations.

  3. Add the tsvector column or expression

    Decide whether to store a precomputed tsvector column, which a trigger or generated column keeps current, or to compute the tsvector in an expression index. A stored column makes the search expression simple to reuse and makes weighting explicit, for example giving titles a higher weight than body text. An expression index avoids extra storage but ties every query to the exact expression. Your application team and DBA should make this choice together in a migration file. The check is a schema review that shows which columns feed the vector and which weight each receives.

  4. Build the GIN index

    Create a GIN index on the tsvector column or expression, using the same text search configuration named in the earlier step. Build it in a maintenance window or with a concurrent build option if your environment allows it, and confirm disk headroom for the index on the target storage before starting. The index is what lets the database find matching documents without scanning every row. The check is that the index exists in the catalog with the expected definition and that its build completed without errors in the server log.

  5. Backfill existing rows

    Populate the tsvector column for rows that existed before the change, in batches so that locks and write load stay manageable. Run the backfill against a copy of production first to measure how long it takes on your data volume, then schedule the production run. Confirm that new inserts and updates keep the column current, either through the trigger or generated definition from the previous steps. The check is a query that counts rows with a null or stale vector and returns zero, plus a sample of recently changed rows that show the expected lexemes.

  6. Review stop-word and stemming output on real content

    Run the configured parser on a sample of real documents from your own content, not only on demonstration text, and inspect the lexemes it produces. Look for stop words that carry meaning in your domain, stemming that merges terms that should stay separate, and product names or identifiers that are split or dropped. Adjust the dictionaries or add synonyms in the configuration, then rerun the check. This review is where most relevance problems are found, and it should involve someone who knows the content. The output is a reviewed list of tokens that was signed off, with any exceptions recorded for the search team.

  7. Wire the application query and ranking

    Connect the application to the search using websearch_to_tsquery for user-typed input, because it accepts quoted phrases and the minus operator without raising syntax errors, or plainto_tsquery when you want every term to be required with simple handling. Pass the same configuration name, and rank results with ts_rank or ts_rank_cd using the weights you set earlier. Limit the returned rows and escape or parameterize the input so that user text is never concatenated into SQL. The check is an automated test set of known queries with expected documents, which must return the right rows in the right order before release.

  8. Verify index use with EXPLAIN and known queries

    Run EXPLAIN or EXPLAIN ANALYZE on the production-shaped queries and confirm the plan uses the GIN index through a bitmap index scan rather than a sequential scan on the table. Then run a fixed set of known queries, each with documents you know should match or not match, and compare the returned rows with the expected list. Repeat this after large data loads and after any configuration change, because the planner may choose differently as table statistics change. The output is a saved test report with the plans, the queries and the expected rows, kept with the release record.

Access control and data exposure in search results

Full-text search copies document text into indexes, ranks it, returns snippets and logs queries, so a permission mistake can leak content through several paths at once. The cards below cover the places where restricted text can reach a user, a log or a backup, and the control and test that closes each one.

Rows returned outside the user's rights

A search query matches any row whose tsvector matches, so a WHERE clause that forgets the tenant or owner filter returns other people's documents. Enable row-level security on the searched table with ENABLE and FORCE ROW LEVEL SECURITY, and keep the application role from owning the table or holding BYPASSRLS. Before go-live, run the same search as users in different tenants and confirm that no matching row from another tenant appears, including for terms that only exist in the other tenant's documents.

Full-text search docs

Ranking and snippets exposing restricted text

Functions such as ts_headline and ts_rank read the full document text, so a snippet can show a sentence from a field the user cannot open. Build the search view or function so that it selects only columns the caller may see, and avoid returning restricted fields in the same result set. Test by searching for a word that appears only in a restricted field and checking that neither the hit count, the rank nor the highlighted snippet reveals it.

Indexes and backups holding copies of content

A GIN index stores the lexemes extracted from every indexed document, so it is a second copy of sensitive text outside the table's row policies. Backups, replicas and dumps carry the index as well. Ask who can read the database files and backup sets, encrypt backups at rest, and confirm that a restore is tested under the same access rules as production. Deleted or reclassified documents also remain in the index until vacuum runs, so confirm removal timing against your retention commitments.

Query logs storing search terms

When statement logging is on, PostgreSQL writes the query text, and the search term is often the most sensitive part: a name, diagnosis or case number typed into a search box. Review log_statement and log_min_duration_statement, decide which roles' statements are logged, and restrict who can read the log files. Mask or hash parameters where your logging pipeline supports it, and test by running a search with a known term and checking exactly what appears in the log and in any log shipper.

Excessive grants to the search account

Applications often run search as a single role with broad SELECT rights across schemas. Grant that role only the tables and columns the search needs, and keep it out of the table owner role. Revoke CREATE on the public schema where it is not needed, and review any SECURITY DEFINER function that runs search on behalf of users. Test by connecting as the search role and attempting to read a restricted column or table, which should fail.

Authentication for the database connection

A search service that connects with a shared password exposes every row its role can read to anyone who obtains that password. Use SCRAM password authentication rather than MD5, which PostgreSQL 18 deprecates, and restrict the connection in pg_hba.conf to the application hosts. Where the platform supports it, pass the end user's identity into the session so that row-level policies can read it. Test that a connection from an unlisted host is rejected and that the session identity matches the user who ran the search.

Deprecates MD5
PG 18
Authentication methods

What ranking gives you and what it does not

PostgreSQL ranks matches using the text itself: how often query terms appear in a document, how the lexemes are weighted through the labels assigned to parts of a tsvector, and how the ranking functions combine those signals. It does not know that a recent document matters more, that a particular user prefers certain content, or that a manager's team documents should float upward. Personalization, typo tolerance, faceted navigation and fine-grained relevance tuning are not built into the database, so each one is either application work (extra filters, boosts stored as columns, a second query for facet counts) or a reason to choose another engine. Write those requirements down before the build starts, because they decide the design more than the choice of ranking function does.

Measure result quality with a fixed set of queries and expected results before you tune anything. Choose a set of real or representative searches, list the documents that should appear at the top for each one, and record the position each query currently returns. Rerun that set after every change to dictionaries, weights, ts_rank or ts_rank_cd calls, or indexed text, and treat any drop in the expected positions as a regression. Keep the set under version control next to the schema, so reviewers can see what the search is supposed to return.

Confirm the behavior of each language configuration separately. Check stemming, stop word removal and synonym handling against the exact queries your users type, including names, product codes, acronyms and misspellings, because a configuration that works for English prose can drop or merge terms in other content. Test mixed-language documents and confirm which configuration is applied at index time and at query time. Confirm the dictionaries and their versions on the server you will run, since custom dictionaries are your responsibility to maintain and document.

When running OpenSearch is worth the extra system

Keeping search in PostgreSQL is usually the right starting point for application search at moderate scale, where the searched data already lives in PostgreSQL, queries are mostly keyword lookups over a few text columns, and the team wants results filtered by the same access rules as the rest of the application. The search index is a GIN index on a tsvector column, so there is no second system to secure, back up or upgrade, and writes commit in the same transaction as the data they describe.

  • Data locality: Search results are always consistent with the rows they point to, because there is no indexing delay.
  • Operational footprint: Backups, restores and access control follow the database you already run.
  • Security model: Row-level access applied in PostgreSQL covers search results without a second authorization layer.
  • Staff time: Your database team already knows the tooling, so no new cluster skill set is needed.
  • Limits to watch: Ranking options and language tuning are narrower than a dedicated engine, and index size and query latency grow with the corpus.

Before committing, confirm with a representative dataset and query mix that latency and relevance meet your requirements, since the built-in tools have limits that only testing will reveal.

Limits to confirm in your environment

PostgreSQL full-text search works well inside the database, but its behavior depends on the build, the dictionaries installed, the write load and the topology you run. The cards below list the items to check in your own environment rather than assume from documentation alone.

Languages and dictionaries in your build

Confirm which text search configurations and dictionaries your PostgreSQL build provides for each language your users search in. Standard dictionaries ship with PostgreSQL, but stemming quality varies by language, and custom dictionaries are a separate piece of work. Run sample queries from real content through each configuration and review the lexemes produced, including names, product codes and mixed-language text.

Text search docs

Index size and rebuild time

Measure the GIN index size and the time to build it on a copy of your largest table before you commit to a design. Index size depends on how much text you index, how many distinct lexemes it produces and whether you index one column or a combined expression. Rebuild time matters for dictionary changes and reindexing windows, so time the rebuild at production volume.

Write load and GIN maintenance

Test how inserts and updates to indexed text affect throughput and latency under your peak write rate. GIN indexes are often slower to update than to query, so bursts of writes can build up index maintenance work. Confirm the effect of your chosen settings with a load test that mirrors your real write pattern, and watch vacuum activity during the run.

Query syntax and operator coverage

Check that the query parser in your design supports the operators your users expect, such as phrase search, prefix matching, boolean combinations and negation. Plain text queries, websearch-style input and the raw tsquery syntax behave differently, and user input must be converted safely before it reaches the database. Test a list of real queries from your support logs against each parser and record the results.

Dictionaries in managed or packaged PostgreSQL

If you run PostgreSQL through a managed service, a Linux package or a container image, confirm that the needed text search dictionaries and configurations are present and enabled. Packaged builds may omit language dictionaries, and some managed offerings limit which extensions and dictionary files you can add. Ask the provider or check the installed package list before you design around a specific language.

Behavior across replicas and failover

Confirm how search queries behave on hot standby servers, since read-only replicas can serve search traffic but cannot write new index entries. Check replication lag, which determines how quickly newly inserted documents appear in search results on a replica. After a failover, verify that the promoted server has the same configurations, dictionaries and index state, and that the application reconnects cleanly.

High availability docs

Questions buyers ask before building PostgreSQL search

What drives the cost and effort of a PostgreSQL full-text search build?

The main drivers are data volume and how much text each row contributes, the number of languages and dictionaries involved, how much ranking control the product needs, how access rules must filter results, and how much testing is required to show relevance is acceptable. Volume affects index build time and storage. Each additional language adds configuration, stemming and stop-word decisions, and test cases. Access rules add work when a search must respect row-level security or document permissions, since the query path and the indexed columns both change. Testing usually takes the largest share of effort when the team has no sample queries to start from. Ask any partner to break a quote into these components so you can see which items your data would increase.

What recurs after a PostgreSQL search goes live?

Recurring work falls into four areas. GIN indexes need monitoring for size, bloat and update cost as content changes, and vacuum settings may need adjustment for write-heavy tables. Dictionaries and synonym lists change as the business adds product names, abbreviations and new terms, and each change needs a re-test. Relevance needs periodic review using real user queries, especially queries that return no results. PostgreSQL upgrades also recur, because text search configurations can behave differently across major versions, so the upgrade plan should include search regression tests. Confirm with your team who owns each of these tasks after handover.

How long does a full-text search implementation take, and what sets that duration?

Duration depends on scope rather than on the database itself. The largest factors are the number of content sources to index, how many languages must be supported, whether ranking needs custom weights or business rules, how complex the access model is, and how many rounds of relevance review stakeholders need. Data quality matters too: messy source text, inconsistent categories or missing metadata often extend discovery. Integration with the application's query layer and the staging environment also affect the schedule. Ask for a timeline that lists these items separately and states which decisions must be made before build work starts.

What does the client team need to provide for a search build?

The work needs a small set of named people and artifacts. Content owners should confirm which fields are searchable, which are confidential and how often content changes. Product or support staff should supply a list of real sample queries, including misspellings, abbreviations and queries that failed in the past, since these drive dictionary and ranking decisions. Engineers need a representative test dataset that matches production shape and volume, with any sensitive values masked. A staging environment with the same PostgreSQL major version and extensions as production is needed to measure index size and query latency before release.

Can an internal team build PostgreSQL full-text search without outside help?

A team with solid PostgreSQL experience can build a basic search on its own, because the core features are documented and included with the server. The harder parts are ranking design, multi-language configuration, permission-aware queries and a test suite that catches relevance regressions. Teams that have not run GIN indexes or dictionaries before usually spend time learning these during the build. Consider an internal build if the search covers one language, modest data and simple access rules, and someone can own it after launch. Consider outside help if the search must meet tight dates, serve several languages, or respect complex access rules, or if the internal team lacks capacity to maintain it.

When should we ask for a fixed-scope quote for search work?

Ask for a fixed-scope quote once you can describe the searchable sources, languages, ranking requirements, access rules, the test approach and the staging environment. At that point the scope can be written down with clear deliverables and acceptance criteria. DeployOpen agrees scope, deliverables and timelines in writing before work starts, and provides a quote based on that written scope. If the requirements are still open, a short discovery phase with sample queries and a data review usually gives the information needed to scope the build. Keep ongoing relevance review and upgrade support as a separate line item so you can see what recurs.

When is an external search engine worth running instead of PostgreSQL search?

Move to an external engine when search becomes a core product feature with needs PostgreSQL does not meet well, such as very large corpora, heavy faceting across many fields, advanced typo tolerance or analytics on search behavior. OpenSearch is open source under the Apache License, Version 2.0, and documents installation options including Docker, Helm and the OpenSearch Kubernetes Operator. Running a second system adds synchronization, security review, backups and upgrades. Confirm the choice against your own query patterns, data volume and team capacity before committing, and check the access controls and audit logging your compliance team requires.

How DeployOpen scopes and delivers PostgreSQL search

DeployOpen plans, builds, tests and documents full-text search on your own PostgreSQL servers, in infrastructure you control. Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts, and ongoing support is available as a retainer.

How we scope

  • Inventory the searchable tables, languages, document sizes and query patterns that the written scope must cover.
  • Agree which dictionaries, language configurations and ranking rules are in scope before any indexes are created.
  • Record the decision point for an external search engine, with the criteria that would trigger it, in the written scope.

How we build

  • Design the tsvector columns or expression indexes, and build GIN indexes sized against your actual write volume.
  • Create custom dictionaries and stop-word lists where standard configurations do not match your domain vocabulary.
  • Tune ranking and query parsing against a representative set of real user searches agreed with your team.

How we hand over

  • Deliver a test suite of expected query results that your team can rerun after schema or configuration changes.
  • Document the search configuration, index maintenance steps, and how to add a language or dictionary later.
  • Walk your engineers through the runbook for reindexing, vacuum behavior on search tables and performance checks.

How we support

  • Review search performance and index health on a schedule set in the retainer, if you choose one.
  • Plan PostgreSQL minor and major upgrades with checks that search results and index behavior still match.
  • Re-evaluate the external search engine decision when search volume, relevance needs or features change.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.