Video in progress

When is `LIKE '%...%'` not enough for searching products by name, and you need a search system like Elasticsearch?

LIKE '%word%' can't use a plain B-tree index and does a full scan on a large table; there's also no morphology, no typo tolerance and no sorting by relevance. If you need those, you use a full-text search system.

📖 Answer

With 50 thousand products, LIKE works fine — measure it, it's probably 20 ms. The problems usually show up later:

  • at 10 million rows every search takes seconds;
  • if the user types "phones", "phone" isn't found;
  • it doesn't correct the typo "iphnoe";
  • results come in arbitrary order, not by relevance;
  • filters (price, brand, category) and counting their totals (facets) are heavy.

Elasticsearch or OpenSearch builds an inverted index, splits text into words and normalizes them, scores with BM25, and makes fuzzy search and aggregations fast.

But there's an in-between step. In PostgreSQL itself:

  • pg_trgm + a GIN index — speeds up ILIKE '%...%' and similarity search;
  • tsvector / tsquery — plain full-text search.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX idx_products_name_trgm ON products USING gin (name gin_trgm_ops);

The cost of a separate search system: one more cluster, syncing with the DB (through CDC or events), and search results lagging the DB by a few seconds. So the DB always remains the source of truth, and ES is just a copy for search.