Leading-wildcard search without a sequential scan
ILIKE '%term%' cannot use a B-tree. How trigram indexes and a semijoin rewrite took grid search on a shared Postgres from tens of seconds to well under a second.
In the first post we flattened pagination on a grid of properties in a multi-tenant payments service. Search was the other half of that grid’s problem. On the largest tenant, a search for a short term took 35 to 50 seconds, and three of them at once each still took about 44, because they queued on the same CPU. This post is about why, and what we changed.
Why a “contains” search is expensive
Grid search was a plain contains match, implemented as ILIKE '%term%'. Users search property name, company name, lease code and similar fields, and they expect to type a fragment from the middle of a word and see results.
A B-tree index is ordered by the start of the value. That makes it excellent for LIKE 'term%' and useless for LIKE '%term%', because the database has no starting point. Every search was a sequential scan of every candidate row, with a string comparison on each. On a small tenant you never notice. On the large one it was tens of seconds, and because the scan burns CPU on a database shared with other services, the cost spread beyond the person who searched.
The no-match case was the worst. A search that finds nothing has to read everything to prove it.
Trigram indexes
Postgres has an extension for exactly this, pg_trgm. It splits strings into overlapping three-character fragments and indexes those, so a GIN or GiST index can answer “which rows contain this substring” without reading the table.
Two details about our environment mattered:
- Each tenant is its own schema, and migrations run with
search_pathpointed at that schema. We enabled the extension once per database, in thepublicschema, and referenced the operator class schema-qualified in each tenant’s index definition. Without that, an index migration that works in one schema fails in the next. - We put trigram indexes only on the columns people actually search. They are large and they slow writes, so “index every string column” is the wrong generalisation.
CREATE EXTENSION IF NOT EXISTS pg_trgm SCHEMA public;
CREATE INDEX properties_name_trgm
ON properties USING gin (name public.gin_trgm_ops);
The index only helps if the plan can use it
Adding the index was the easy part. The worst filter in the grid was a correlated EXISTS that looped over every managed property and asked, for each one, whether any lease matched the search term. The planner cannot turn that into an index lookup on the lease table, so the trigram index sat unused.
We rewrote it as a semijoin: find the matching leases first, using the index, then match the properties to them by id.
-- before: per-property correlated lookup
EXISTS (
SELECT 1 FROM leases l
WHERE l.property_id = property.id
AND l.external_code ILIKE :term
)
-- after: set-based, the trigram index can drive it
property.id IN (
SELECT lease.property_id
FROM leases AS lease
WHERE lease.property_id IS NOT NULL
AND lease.external_code ILIKE :term
)
Name columns that already sit on the outer row stay as a direct ILIKE, which the trigram index can match without any join. Lease and company text is searched in the inner query and joined back by id. The pattern is the same each time: find the small set of matching ids with an index, then bring the rows in.
Not every search term is the same kind of term
A grid search box gets used for names, codes and email addresses without the user saying which. The obvious implementation is one OR across every table that could hold a match. That drags contact rows into a plan that has nothing to do with them.
We split the lookup by shape instead. A term that looks like an email address takes a different path from free text, so a short string does not make the planner consider every contact row. This is a small amount of application logic that removes a large amount of database work.
Numbers
On a development database at production-like scale, one search path went from 1382ms to 210ms after the indexes, about 6.6 times faster. A later semijoin pass took a common-term search from about 79ms to about 43ms once the indexes were warm.
The no-match case from the first post is the same family of fix. It went from 4809ms to 148ms in service time, because the planner stops reading the whole table to discover that nothing matched. The 35 to 50 second figure from the start of this post was measured live, end to end, so it is not directly comparable with these service-side timings. Both point the same way.
These are the measurements that matter, because they cover both the common term and the empty result.
How we check a search change before shipping it
The checklist is short, and we run it on a dataset the size of the largest tenant, never on a small one.
- Search for a term that matches a lot of rows, one that matches a few, and one that matches nothing. Their plans are often different.
- Read the
EXPLAINoutput for an index scan on the trigram index, not just the elapsed time. A query can be fast by accident on a warm cache and slow on the next cold one. - Run the same search a few times at once, because the original problem was concurrent searches queuing on one CPU.
- Check the count query as well as the page query. They are separate statements and they can have separate plans.
Pitfalls
Trigram indexes cost something. They are large relative to B-trees and they make writes slower. Put them on the searched text columns, not on every string in the schema, and check the table’s write rate first.
The index does nothing if the predicate does not match the operator class. Wrapping the column in a function the index was not built on, or comparing against an expression the operator class does not cover, turns the plan back into a sequential scan. The same happens if the query joins so widely that the planner never considers the index at all. Always check the plan with EXPLAIN, not just the timing.
COUNT(DISTINCT id) brings the sequential work back. If a search joins three tables to produce its page, a distinct count over that same join reintroduces the cost you just removed. When the joins are not multiplying rows, COUNT(*) is the honest aggregate. We covered the same trap in the pagination post, and it comes back here because search is where the joins are widest.
Small tenants will not use your new index. At a few thousand rows a sequential scan can be a handful of milliseconds, and the planner will correctly ignore the index. That is fine. The index earns its place at larger sizes, so test on data that looks like your biggest customer, not your average one.
The habit
For any search box, ask what a leading wildcard does to the plan before shipping it. If the answer is a sequential scan, pick the columns, add a trigram index, and rewrite the correlated filters as semijoins so the index can drive them. Then time the search that matches nothing, because that is the one that reads everything.
The next post is about the second grid in this product, the collections queue, and why we stopped computing its numbers inside the request.
Previous: Why page 40 took fourteen seconds. Next: A summary table for an operational grid.