Sub topic 1
When Database Queries Are Not Enough
Most applications start with search implemented as a SQL query. For many systems that is the right place to stay. This chapter gives you criteria for deciding when a database query is enough, when the database's built-in full-text feature is enough, and when the requirements justify a dedicated search service.
Prerequisites
This chapter assumes you have:
- Basic relational database and SQL knowledge, including indexes and
EXPLAIN. - Familiarity with REST APIs and service-to-service communication.
- A general understanding of caching and message queues.
- A basic idea of horizontal scaling and replication.
You do not need to know anything about search engines yet. Later chapters cover the internals.
What a database does well
A relational database is built for exact, structured lookups. You ask for rows where a column equals a value, falls in a range, or matches a join condition. A B-tree index answers these questions in logarithmic time, and the result is the same set of rows every time.
Search is a different kind of question. A user types a few words and expects the system to work out what they meant. Three properties separate it from lookups:
- Matching is fuzzy. "running shoe" should match "Shoes for running".
- Results are ranked. There is no single correct set, only a best-first ordering.
- Input is unstructured. The text is free-form and has to be interpreted.
A database can approximate all three, but it was not designed around them.
Where LIKE breaks down
The first attempt at search is usually a LIKE query:
SELECT id, name
FROM products
WHERE name LIKE '%running shoes%'
ORDER BY created_at DESC
LIMIT 10;This works on a small table and fails in predictable ways as the product grows.
- No index help. A leading wildcard (
%running) prevents a B-tree index from narrowing the search. The database scans every row, so cost grows linearly with table size. - No language awareness. The query misses "Shoes for running", "Running shoe" (singular), and "run shoes". It matches only that exact character sequence.
- No relevance. A row either matches or it does not. The query cannot tell a product titled "Running Shoes" from one that mentions shoes once in a long description. You end up sorting by date or price, which is rarely what users want.
- No typo tolerance. "runing shoes" returns nothing.
- Awkward multi-field matching. Searching name, description, and brand means chaining
ORconditions. Weighting a title match above a description match is not possible without extra code.
You can patch some of these in application code. Each patch is a small search engine written by hand, and it is usually slower and less correct than an existing one.
The middle step: database full-text search
Before adding a new system, check whether your database already has a full-text feature. PostgreSQL has tsvector and GIN indexes, and MySQL has FULLTEXT indexes. These tokenize text, apply stemming, and rank results.
ALTER TABLE products
ADD COLUMN search_vector tsvector
GENERATED ALWAYS AS (
to_tsvector('english', coalesce(name, '') || ' ' || coalesce(description, ''))
) STORED;
CREATE INDEX products_search_idx ON products USING GIN (search_vector);
SELECT id, name, ts_rank(search_vector, query) AS rank
FROM products, websearch_to_tsquery('english', 'running shoes') AS query
WHERE search_vector @@ query
ORDER BY rank DESC
LIMIT 10;This version handles word forms, uses an index, and ranks results. It also lives in the same transaction boundary as your data, so there is no sync pipeline and no lag.
For many internal tools, admin panels, and small catalogs, this is the right stopping point. Later chapters compare it with dedicated engines in detail.
Signals that you need a dedicated search service
Database full-text search starts to strain when requirements pile up. The table below lists common signals and why each one pushes past the database.
| Signal | Why the database struggles |
|---|---|
| Typo tolerance and "did you mean" | Few databases support edit-distance matching well, and where they do it is slow at scale. |
| Faceted navigation with counts (for example, "Brand: Nike (214)") | Computing counts across a large filtered result set repeatedly is expensive on a transactional store. |
| Tuned relevance, boosting, or synonyms | Weights are coarse, and synonyms and custom scoring are hard to configure and iterate on. |
| Autocomplete at keystroke latency | Prefix and n-gram lookups at tens of milliseconds under heavy load need specialized structures. |
| Multi-language content | Each language needs its own analysis rules, and mixing them in one column gets messy. |
| Search load competes with writes | Heavy read queries on the primary slow down checkouts and other critical transactions. |
| Millions of documents with sub-100 ms targets | Ranking large match sets in a row store becomes the bottleneck. |
| Searching across several data sources | Results from multiple databases or services must be merged into one ranked list. |
One signal alone rarely justifies a new system. Two or three together usually do.
Signals that you do not need one
A dedicated service is not a sign of maturity. Skip it when:
- Users filter by structured fields (status, date, owner) rather than typing free text.
- The data set is small, and a full-text index on the database responds in a few milliseconds.
- Exact-match lookups by ID, email, or SKU are the main use case. A normal index handles these.
- The team cannot yet operate another stateful system.
- Slightly stale or unranked results do not hurt the product.
A common mistake is adding a search engine for a feature that is really a filtered list. Filters on columns are a database job.
What a search service costs you
The new component brings its own work, and it should be part of the decision.
- A second copy of the data. The index duplicates data from the source of truth, so you need a pipeline that keeps it current.
- Eventual consistency. A write to the database is not visible in search immediately. Users may save a record and not find it for a moment.
- Operational load. You now run a cluster with its own capacity planning, upgrades, backups, and monitoring.
- Schema coupling. Changing how fields are analyzed often means rebuilding the index.
- Security surface. Permissions that the database enforces with row-level rules must be re-applied in search results.
- Failure handling. You must decide what the product does when search is down.
Each of these has a dedicated chapter later. For now, treat them as the price you pay for the benefits above.
A decision flow
The diagram summarizes the reasoning as a sequence of questions.
Worked example: a growing marketplace
A marketplace starts with 20,000 listings. Search uses LIKE '%term%' on the title. Response time is 30 ms and nobody complains.
At 2 million listings, the same query takes 4 seconds, and a scan on the primary slows checkout. The team moves to PostgreSQL full-text search with a GIN index. Latency drops to 40 ms and stemming works. This is a good outcome, and no new infrastructure was needed.
A year later, product asks for several things:
- Brand and size facets with counts.
- Synonyms ("sneakers" and "trainers").
- Typo tolerance.
- Boosting for listings with good reviews.
- Autocomplete.
Facet counts add load to the primary, and tuning ranking means rewriting SQL for every experiment. Now several signals from the table are present at once, and the marketplace has a team that can run a cluster. This is the point to add a search service.
The move was driven by concrete requirements and measured load. It was not driven by the table getting big alone.
Common mistakes
- Replacing the database. The search index is a derived, read-optimized copy. The database remains the source of truth.
- Adding search for filtering. If there is no free text, you are likely paying for a system you do not need.
- Skipping the measurement. Run
EXPLAIN ANALYZEon the current query and test with the database's full-text feature before concluding it is insufficient. - Ignoring the sync design. Teams choose an engine first and think about keeping it current last. Data sync is usually where most of the real effort goes.
- Assuming search is instantly consistent. Product and UX must accept a short delay between a write and its visibility.
Exercises
Exercise
A team's admin panel lets staff look up orders by order ID, customer email, or status. The table has 5 million rows. A teammate proposes adding a search engine. What do you recommend, and why?
Show answer
Keep the database. These are exact-match and structured lookups, which B-tree indexes on order ID, email, and status handle well. There is no free text, relevance ranking, or fuzzy matching, so a search engine would add a second copy of the data, a sync pipeline, and eventual consistency without any benefit.
Exercise
Name three reasons a LIKE '%shoes%' query fails as a product search, and name the lowest-cost next step before adding a dedicated search service.
Show answer
Any three of: the leading wildcard prevents index use so it scans the whole table; it has no stemming or language handling, so "shoe" and "running shoes" differ; it has no relevance ranking; it has no typo tolerance; weighting across multiple fields is awkward. The lowest-cost next step is the database's own full-text feature, such as PostgreSQL tsvector with a GIN index, which adds tokenization, stemming, and ranking without a new system.
Exercise
A catalog with 300,000 products needs facet counts, synonyms, and typo tolerance, and search traffic is slowing down checkout on the primary database. List two costs the team accepts by adding a dedicated search service.
Show answer
Any two of: maintaining a second copy of the data and the pipeline that syncs it; eventual consistency, so new writes are not immediately searchable; operating another stateful cluster; reapplying access control in search results; rebuilding the index when the schema or analysis rules change; and deciding what the product does when search is unavailable.