Log inSign up

Search, encrypt and measure distance inside PostgreSQL

Add a generated tsvector column, index it with GIN and query it with websearch_to_tsquery to get ranked full-text search without a separate search server. For sensitive fields, enable pgcrypto and store values with pgp_sym_encrypt, keeping the key outside the database. For "near me" queries, the earthdistance extension or a short haversine formula returns distances in metres or kilometres.

Topic: Databases · Tested on: Ubuntu 24.04 and 22.04, Debian 12 and 13, Rocky Linux 9, AlmaLinux 9 · Updated 2026-12-03

What should be ready before you begin?

A running PostgreSQL 13 or newer server and a database you own are enough; all three features ship in core or in the contrib modules. Install the server with the PostgreSQL guide. On Rocky and Alma with PGDG packages, add contrib with sudo dnf install -y postgresql18-contrib (use your version number).

psql -h 127.0.0.1 -U deploy appdb
SELECT name, default_version FROM pg_available_extensions
WHERE name IN ('pgcrypto', 'cube', 'earthdistance', 'pg_trgm', 'unaccent');

If those rows appear, every example below will work. Create extensions as the database owner; they apply to that database only, so repeat the step in each database that needs them.

How does PostgreSQL full-text search work?

Text is turned into a tsvector (normalised word stems with positions) and the search into a tsquery; the @@ operator tests whether they match. Language configurations handle stemming, so a search for "running" also finds "runs".

SELECT to_tsvector('english', 'The servers were running smoothly');
-- 'run':4 'server':2 'smooth':5
SELECT to_tsvector('english', 'Servers running') @@ to_tsquery('english', 'server & run');
SELECT websearch_to_tsquery('english', '"daily backup" -windows or restic');

websearch_to_tsquery understands the syntax people type in search boxes: quotes for phrases, a minus sign to exclude, and or. It never raises a syntax error on odd input, which makes it the safe choice for user queries. List the available languages with \dF.

How do you add an indexed search column?

Store the vector in a generated column so it always matches the text, give the title a higher weight than the body, and index it with GIN.

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

INSERT INTO articles (title, body) VALUES
  ('Backups with restic', 'Schedule encrypted backups to remote storage every night.'),
  ('Firewall basics', 'Allow SSH first, then deny everything else by default.');

Then rank and highlight the results:

SELECT id, title,
       ts_rank(search, q) AS rank,
       ts_headline('english', body, q, 'MaxWords=20, MinWords=8') AS snippet
FROM articles, websearch_to_tsquery('english', 'encrypted backup') AS q
WHERE search @@ q
ORDER BY rank DESC
LIMIT 20;

Confirm the index is used with EXPLAIN ANALYZE; you should see a Bitmap Index Scan on articles_search_gin once the table holds more than a handful of rows.

How do you handle typos and accents?

Combine full-text search with the pg_trgm extension for fuzzy matches and unaccent to ignore diacritics.

CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX articles_title_trgm ON articles USING gin (title gin_trgm_ops);
SELECT title, similarity(title, 'firwall basic') AS score
FROM articles WHERE title % 'firwall basic' ORDER BY score DESC;

CREATE EXTENSION IF NOT EXISTS unaccent;
SELECT unaccent('Café résumé');

Trigram indexes also speed up LIKE '%term%' and ILIKE, which ordinary B-tree indexes cannot help with. A common pattern runs the full-text query first and falls back to trigram similarity when it returns nothing. Because unaccent is not marked immutable, wrap it in your own immutable SQL function before using it inside a generated column or index expression.

How do you encrypt a column with pgcrypto?

Enable pgcrypto, store the value as bytea encrypted with pgp_sym_encrypt, and decrypt with pgp_sym_decrypt using a key your application supplies at query time.

CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE customers_secure (
  id        bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email     text NOT NULL,
  tax_id    bytea
);
INSERT INTO customers_secure (email, tax_id)
VALUES ('ana@example.net', pgp_sym_encrypt('PT123456789', :'enc_key', 'cipher-algo=aes256'));

SELECT email, pgp_sym_decrypt(tax_id, :'enc_key') AS tax_id FROM customers_secure;

In psql, set the key for the session with \set enc_key 'long-random-key-from-your-secret-store'; in an application, pass it as a bound parameter. Never store the key in a table in the same database, or the encryption protects nothing against a stolen dump.

Remember that the key travels with each statement, so it can show up in server logs if you log slow or all statements. Keep log_statement at none or ddl on databases that use this pattern, and restrict who can read pg_stat_statements. Disk-level protection for the whole server is a different topic; pgcrypto protects selected fields even in dumps and backups.

How should you store passwords in PostgreSQL?

Hash them, never encrypt them: use crypt() with a bcrypt salt so each hash is salted and slow to brute-force.

CREATE TABLE app_users (
  login text PRIMARY KEY,
  pw    text NOT NULL
);
INSERT INTO app_users VALUES ('deploy', crypt('correct horse battery', gen_salt('bf', 12)));

SELECT login FROM app_users
WHERE login = 'deploy' AND pw = crypt('correct horse battery', pw);

The work factor 12 is a reasonable 2026 default; raise it as hardware gets faster. Many frameworks hash in application code instead, which is equally sound, so pick one place and stay consistent. For random tokens, encode(gen_random_bytes(32), 'hex') gives 64 hex characters of strong randomness.

How do you find places within a distance?

For quick radius searches on latitude and longitude, enable cube and earthdistance, index ll_to_earth() with GiST, and filter with earth_box before computing the exact distance.

CREATE EXTENSION IF NOT EXISTS cube;
CREATE EXTENSION IF NOT EXISTS earthdistance;
CREATE TABLE sites (
  name text,
  lat  double precision,
  lon  double precision
);
INSERT INTO sites VALUES ('Lisbon', 38.7223, -9.1393), ('Madrid', 40.4168, -3.7038), ('Porto', 41.1579, -8.6291);
CREATE INDEX sites_earth ON sites USING gist (ll_to_earth(lat, lon));

SELECT name, round((earth_distance(ll_to_earth(38.7223, -9.1393), ll_to_earth(lat, lon)) / 1000)::numeric, 1) AS km
FROM sites
WHERE earth_box(ll_to_earth(38.7223, -9.1393), 400000) @> ll_to_earth(lat, lon)
ORDER BY km;

Distances come back in metres on a spherical earth, which is accurate to within a fraction of a percent for most uses.

Without any extension, the haversine formula in plain SQL works for small tables:

SELECT name, round((2 * 6371 * asin(sqrt(
  power(sin(radians(lat - 38.7223) / 2), 2) +
  cos(radians(38.7223)) * cos(radians(lat)) * power(sin(radians(lon + 9.1393) / 2), 2)
)))::numeric, 1) AS km
FROM sites ORDER BY km;

For polygons, routes or precise geodesic maths, move to PostGIS.

When is a separate search server worth it?

Stay inside PostgreSQL while one database holds the content and you need ranked keyword search, filters and highlighting; move to a dedicated engine when you need faceting across millions of documents, many languages per field or relevance tuning beyond weights.

Built-in search keeps data in one place, follows transactions automatically and adds no extra service to patch. A search server such as Apache Solr or Elasticsearch brings faceting, synonyms and analysers, at the cost of more memory and a sync job between the database and the index. Measure real queries with EXPLAIN ANALYZE before deciding, and track slow ones with PgHero.

Plans that fit this guide

Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.

All prices
PlanFits becauseSizeMonthlyOrder from
A2-4search index kept in memory2 vCPU, 4 GB RAM, 100 GB NVMe$14.40/mo$43.20 for 3 months
A4-8large article or product catalogues4 vCPU, 8 GB RAM, 180 GB NVMe$28.80/mo$86.40 for 3 months

Questions about PostgreSQL full-text search and encryption

Is to_tsvector stemming available for other languages?

Yes. PostgreSQL ships configurations for around 30 languages, including german, french, spanish and russian. Run \dF in psql to list them, and use the simple configuration for codes and names that should not be stemmed.

Why is my full-text query not using the index?

The query must use the same expression as the index. With a generated column, filter on that column with @@. On tiny tables the planner may prefer a sequential scan, which is normal.

Does pgcrypto encrypt data on disk?

Only the columns you encrypt with its functions. Other columns, indexes and the rest of the database stay readable to anyone with file access, so treat it as field-level protection.

Where should I keep the encryption key?

Outside the database: an environment variable or secret file readable only by the app user, loaded at start-up. See environment variables.

Is earthdistance accurate enough for delivery zones?

For radius filters and sorting by distance, yes. It assumes a perfect sphere, so for legal boundaries, polygons or exact routes use PostGIS geography types.