Medium postgresql sql

How do you make a contains search like LIKE '%boot%' fast, and when do you use full-text search instead?

The 30 second answer

A B-tree can't help a pattern that starts with a wildcard. The pg_trgm extension breaks text into three-character pieces and its GIN or GiST index supports LIKE, ILIKE and regex anywhere in the string, plus similarity for typos. Full-text search with a tsvector and a GIN index matches words after stemming and can rank, which suits natural-language search. For real product search with ranking and facets, that's Elasticsearch's job.

Could you say this in an interview?

From the basics. LIKE 'boot%' can use a B-tree because all values starting with "boot" sit next to each other in sorted order. LIKE '%boot%' can be anywhere in the string, so sorted order is useless and PostgreSQL scans every row.

Option one: trigrams. pg_trgm splits text into three-character sequences ("boot" gives " b", " bo", "boo", "oot", "ot "). The docs: GIN and GiST trigram indexes "support trigram-based index searches for LIKE, ILIKE, ~, ~* and = queries", and "the search string need not be left-anchored". A pattern with no extractable trigrams, such as one or two letters, "will degenerate to a full-index scan".

CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX products_name_trgm ON products USING gin (name gin_trgm_ops);

SELECT id, name FROM products WHERE name ILIKE '%boot%';
SELECT id, name FROM products WHERE name % 'snekers' ORDER BY similarity(name, 'snekers') DESC LIMIT 10;

Option two: full-text search. A tsvector stores normalized words (lexemes), so "boots" and "boot" match. A GIN index makes @@ queries fast, and ts_rank can order results.

ALTER TABLE products ADD COLUMN search_tsv tsvector
  GENERATED ALWAYS AS (to_tsvector('english', coalesce(name, '') || ' ' || coalesce(description, ''))) STORED;
CREATE INDEX products_search_tsv ON products USING gin (search_tsv);

SELECT id, name FROM products
WHERE search_tsv @@ websearch_to_tsquery('english', 'leather boots')
ORDER BY ts_rank(search_tsv, websearch_to_tsquery('english', 'leather boots')) DESC LIMIT 20;

How to choose.

NeedPick
Substring of codes, emails, SKUs, admin searchpg_trgm
Typos on short stringspg_trgm similarity
Words, stemming, simple ranking in one languageFull-text search
Multi-language analysis, synonyms, facets, learning to rank at scaleA search engine such as Elasticsearch

Trade-offs.

  • GIN indexes are larger and slower to update than B-trees. The docs discuss GIN versus GiST performance for text search.
  • Full-text search is language-specific: the english configuration stems English words only.
  • Moving search into PostgreSQL avoids a second system and its sync pipeline, but ranking, analysis and scale are where a search engine earns its place.

Alternate interview scenarios

"Customer service searches orders by part of an email address and it times out."

Add a trigram GIN index on email and require at least three characters in the UI.

"Why not just use PostgreSQL full-text search instead of Elasticsearch for the shop?"

It can be enough for a small catalog in one language. For many languages, synonyms per market, facets over tens of millions of items and learned ranking, a dedicated engine scales and tunes better, at the cost of running and syncing it.

Sources (3)
  1. PostgreSQL docs: pg_trgmpostgresql.org
  2. PostgreSQL docs: Preferred index types for text searchpostgresql.org
  3. PostgreSQL docs: Controlling text search (ranking, websearch_to_tsquery)postgresql.org