Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

A product search in a Spring Boot app uses a JPA query with LIKE '%term%' and is slow on 5 million rows. Why, and what are the options?

A pattern with a leading wildcard such as '%phone%' cannot use a normal B-tree index, because the index is sorted by the start of the value, so the database scans all 5 million rows. In PostgreSQL, a trigram index from pg_trgm or full-text search with a tsvector column and a GIN index handles many cases quickly. A search engine such as Elasticsearch or OpenSearch adds relevance ranking, facets and typo tolerance, but it is a second data store that must be kept in sync, so we start with database features when the requirements are simple.

Why this question is asked

Almost every application gets a search box sooner or later, and the first implementation is nearly always a LIKE query. It works in development with a thousand rows and becomes a problem in production with millions. Interviewers ask this question because the answer requires knowing how indexes actually work, and because the options range from a one-line index to a whole new system. In this answer, we will reproduce the slow query, see why the index cannot help, fix it with trigram indexes and full-text search in PostgreSQL, look at what a search engine adds and costs, and decide when each makes sense.

1Reproducing the Slow Query

Here is the typical repository method. JPQL's LIKE with a parameter wrapped in percent signs finds products whose name contains the term anywhere.

Java
@Query("select p from Product p where lower(p.name) like lower(concat('%', :term, '%'))")
List<Product> search(@Param("term") String term);
-- what PostgreSQL does with it
EXPLAIN ANALYZE SELECT * FROM product WHERE lower(name) LIKE '%phone%';
-- Seq Scan on product (rows=5000000) Filter: lower(name) ~~ '%phone%'
-- Execution Time: 1850 ms

The plan says Seq Scan: PostgreSQL reads every one of the 5 million rows and tests each name. Even if there is an index on name, it is not used. With 50 searches per second, that is the database's whole capacity spent on one feature.

2Why a Leading Wildcard Cannot Use a B-tree Index

A normal index in PostgreSQL is a B-tree, a sorted structure that lets the database jump to a value instead of scanning. Think of a phone book sorted by surname. Finding everyone whose surname starts with Smi is easy: jump to Smi and read forward. That is why LIKE 'phone%' can use a suitable index, as long as the index supports pattern matching, for example one created with text_pattern_ops when the database collation is not C.

But finding everyone whose surname contains mit somewhere is impossible with a sorted list: Smith, Mitchell and Kemit are in completely different places. A pattern starting with % has no fixed prefix, so the sort order gives no starting point, and the database must look at every row. Wrapping the column in lower() makes it worse, because a plain index on name does not even cover lower(name).

3Option 1: Trigram Indexes With pg_trgm

The pg_trgm extension breaks text into trigrams, every group of three consecutive characters. The word phone gives trigrams such as pho, hon and one, plus a few with padding at the start and end. A GIN index, an inverted index that maps each trigram to the rows containing it, can then answer contains queries by finding rows that have all the trigrams of the search term, and checking only those.

SQL
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX product_name_trgm ON product USING gin (name gin_trgm_ops);
EXPLAIN ANALYZE SELECT * FROM product WHERE name ILIKE '%phone%';
-- Bitmap Index Scan on product_name_trgm
-- Execution Time: 12 ms
SELECT name FROM product WHERE name % 'iphome' ORDER BY similarity(name, 'iphome') DESC LIMIT 5;
-- finds 'iPhone 16' despite the typo: similarity 0.31, above the default threshold of 0.3

Notice that ILIKE, case-insensitive LIKE, can use the trigram index directly, so we no longer need lower(). Trigram indexes keep the exact contains behaviour users expect and add simple typo tolerance through similarity. Terms shorter than three characters cannot be helped much, and the index is larger than a B-tree, but for product names it is often all we need.

4Option 2: PostgreSQL Full-Text Search

Full-text search works with words rather than characters. PostgreSQL turns text into a tsvector, a sorted list of normalised words called lexemes, where running and runs both become run thanks to stemming, and common words such as the are dropped. A query is turned into a tsquery the same way, and a GIN index on the tsvector makes matching fast. It also supports ranking, so better matches come first.

SQL
ALTER TABLE product ADD COLUMN search tsvector
GENERATED ALWAYS AS (to_tsvector('english', coalesce(name, '') || ' ' || coalesce(description, ''))) STORED;
CREATE INDEX product_search_gin ON product USING gin (search);
SELECT id, name, ts_rank(search, q) AS rank
FROM product, websearch_to_tsquery('english', 'wireless headphones') q
WHERE search @@ q
ORDER BY rank DESC LIMIT 20; -- matches 'Wireless Headphone' and 'headphones, wireless'

From Spring we call this with a native query. Full-text search is better than trigrams when users type several words, search descriptions as well as names, or need ranking; trigrams are better for partial words and codes like SKU fragments. Many applications use both.

5Option 3: A Search Engine

When search becomes a core feature, a dedicated engine such as Elasticsearch or OpenSearch adds things the database does poorly: relevance ranking that can be tuned with business signals, facets such as counts by brand and price range computed with each query, typo tolerance through fuzzy matching, synonyms, autocomplete, and scaling search separately from the transactional database.

But there is a real cost. A search engine is a second data store. Every product change must be sent to it, usually through an outbox or change data capture into an indexer, and for a short time the two disagree. We now operate a cluster, plan reindexing when mappings change, and handle the case where the index is behind or down. None of that is needed for a simple name search.

6Choosing Between Them

The sensible path is to start with what the database offers and move when requirements demand it. For a search box over names and SKUs, a trigram index is often enough. When users need multi-word queries and ranking, full-text search in PostgreSQL covers it. When the business wants facets, synonyms, tuned relevance or high search traffic, a search engine earns its operational cost.

Options for slow LIKE search
OptionGood atCost
Trigram GIN indexcontains matching, short typosone index, larger than B-tree
Full-text tsvector + GINwords, stemming, rankinggenerated column, language config
Elasticsearch or OpenSearchrelevance, facets, typos, scalesecond store, sync, cluster ops

7Follow-up questions

Can a B-tree index help a LIKE query at all?

Yes, when the pattern has a fixed prefix, such as LIKE 'phone%', and the index supports pattern matching, which in PostgreSQL means the C collation or an index built with text_pattern_ops or varchar_pattern_ops. It never helps a pattern that starts with a wildcard.

Why is a GIN index slower to update?

Each row produces many index entries, one per trigram or lexeme, so inserts and updates do more work. GIN uses a pending list to batch updates, controlled by the fastupdate option, which keeps writes fast at the cost of slightly slower searches until the list is merged.

How do you keep a search engine in sync with the database?

Publish changes reliably, with a transactional outbox or change data capture such as Debezium, into an indexer that writes to the engine with versions, and periodically reconcile counts to catch anything missed.

8Conclusion

In this answer, we saw that LIKE '%term%' forces a full table scan because a B-tree index is sorted by the start of the value and a leading wildcard gives it nowhere to start. We fixed it in PostgreSQL with a trigram GIN index for contains matching and simple typos, and with a tsvector column and GIN index for word-based, ranked search, then looked at what Elasticsearch or OpenSearch adds and the cost of keeping a second store in sync, and chose to start with the database.

What to say in the interviewAbout 80 seconds aloud

Open with

The problem is the leading wildcard. A normal B-tree index is sorted by the beginning of the value, like a phone book sorted by surname, so it can find names starting with phone, but it has no way to find names that contain phone in the middle.

Then, if they want more

With a percent sign at the start, PostgreSQL falls back to a sequential scan and tests all 5 million rows, and wrapping the column in lower makes even a prefix index unusable. My first option is the pg_trgm extension with a GIN trigram index on the name.

It indexes every three-character sequence, so ILIKE with wildcards on both sides becomes an index scan, and it also gives similarity search for small typos. My second option is full-text search: a generated tsvector column over name and description with a GIN index, queried with websearch_to_tsquery and ranked with ts_rank, which handles multiple words and stemming.

If the business needs facets, synonyms, tuned relevance and typo tolerance at scale, I would bring in Elasticsearch or OpenSearch, but that is a second data store we must keep in sync with an outbox or CDC and operate. So I would start with the database features and move only when requirements demand it.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A product search in a Spring Boot app uses a JPA query with LIKE '%term%' and is slow on...": https://scrivio-interview-library.netlify.app/architecture/backend-system-design/751963f265/