Nearly every search bar begins with the same quick SQL snippet: WHERE title LIKE '%adapter%' OR sku LIKE '%adapter%'. With 500 products, it ships before lunch and feels instant. Six months later, your catalog holds 300,000 items, shoppers type "usb-c adpater", toggle four brand and price facets at once, and your database CPU pins at 100% because leading-wildcard LIKE expressions ignore B-tree indexes completely.
Across 170+ production builds shipped since 2017, search quality directly drives both B2B SaaS usability and marketplace conversion. Yet introducing Elasticsearch carelessly trades slow SQL for new failure modes: silent index drift, dynamic mapping conflicts, and JVM out-of-memory crashes. Here is how to build a search pipeline that remains accurate, fast, and predictable in production.
Verify You Actually Need a Separate Search Cluster
Spinning up a JVM search cluster adds deployment, monitoring, and synchronization complexity. Before adding another stateful datastore, measure whether tuning your relational database solves the immediate problem.
| Capability | SQL LIKE / ILIKE |
PostgreSQL tsvector + pg_trgm |
Elasticsearch / OpenSearch | Typesense / Meilisearch |
|---|---|---|---|---|
| Operational Overhead | Zero | Low (single DB) | High (JVM heap, shards, sync) | Low–Medium |
| Typo & Fuzzy Matching | None | Basic trigram similarity | Mature (fuzziness, phonetic) |
Strong defaults |
| Dynamic Facet Counts | Expensive COUNT(*) |
Degrades on high cardinality | Fast (aggs in < 50ms) |
Built-in |
| Relevance Weighting | None | Manual ts_rank formulas |
BM25, boosts, function scores | Rule-based weights |
| Practical Dataset Range | < 50k records | 50k – 2M records | 1M – billions of docs | 50k – 10M records |
If your dataset sits under 150,000 rows with light filtering, optimize PostgreSQL indexes first—consult the PostgreSQL performance tuning guide and our breakdown of fixing slow database queries. Reach for Elasticsearch when multi-field relevance boosting, custom synonyms, nested attributes, and instant facet aggregations become core user expectations.
Lock Down Explicit Index Mappings Early
Leaving dynamic: true enabled in production is an invitation for corrupted indexes. One malformed payload can lock a field into the wrong type until you reindex the entire catalog.
Separate Analyzed text From Exact keyword Fields
Set dynamic: "strict" (or "false" to ignore unmapped keys safely) and define explicit analyzers for searchable text versus exact filters and aggregations:
PUT /catalog_v1
{
"settings": {
"number_of_shards": 2,
"number_of_replicas": 1,
"analysis": {
"analyzer": {
"catalog_search_analyzer": {
"tokenizer": "standard",
"filter": ["lowercase", "asciifolding"]
}
}
}
},
"mappings": {
"dynamic": "strict",
"properties": {
"id": { "type": "long" },
"account_id": { "type": "long" },
"sku": { "type": "keyword" },
"name": {
"type": "text",
"analyzer": "catalog_search_analyzer",
"fields": { "exact": { "type": "keyword" } }
},
"summary": { "type": "text", "analyzer": "english" },
"vendor": { "type": "keyword" },
"price_cents": { "type": "integer" },
"in_stock": { "type": "boolean" },
"modified_at": { "type": "date" }
}
}
}
Reindex Without Downtime Using Aliases
Elasticsearch forbids changing existing field types in place. Never hardcode physical index names like catalog_v1 in application code—route every read and write through a stable alias such as catalog_active:
POST /_aliases
{
"actions": [
{ "remove": { "index": "catalog_v1", "alias": "catalog_active" } },
{ "add": { "index": "catalog_v2", "alias": "catalog_active" } }
]
}
Whenever analyzer rules or mappings evolve, create catalog_v2, backfill documents in the background, verify hit counts and test queries, then flip the alias atomically in milliseconds.
Synchronize Relational Writes Without Drift
Your primary database remains the single source of truth; Elasticsearch acts strictly as an eventually consistent read projection.
Avoid Dual Writes Inside Request Handlers
Updating PostgreSQL and immediately firing an HTTP call to Elasticsearch inside a controller introduces split-brain failures:
- If PostgreSQL commits and the Elasticsearch request times out, new items stay invisible in search.
- If Elasticsearch indexes a record before a database validation hook rolls back, search results link to missing 404 pages.
Combine Post-Commit Outbox Events With _bulk Upserts
Dispatch indexing jobs strictly after database commit (DB::afterCommit(...) or a durable search_outbox table). Group updates into _bulk payloads of 500–1,000 documents rather than single-document HTTP calls, and pass a monotonic timestamp or revision number with version_type: "external" so delayed queue retries can never overwrite fresher updates.
Pair event-driven syncing with a scheduled nightly sweep comparing recently modified database IDs against the index to repair any dropped events automatically.
Tune Query Structure to Prevent Heap Exhaustion
Even modest traffic can stall cluster nodes if queries skip filter caching or request deep paginated offsets.
Push Non-Scored Predicates Into filter
Reserve must and should clauses exclusively for text queries that require BM25 relevance scoring. Place account_id, in_stock, vendor, and numeric ranges inside filter so Elasticsearch skips scoring math and caches bitsets automatically across requests.
Paginate Deep Result Sets With search_after
Elasticsearch limits from + size to 10,000 hits because deep offsets force coordinating nodes to merge giant sorted arrays in JVM memory. Implement deterministic cursor pagination using search_after paired with a unique tie-breaker field (id):
POST /catalog_active/_search
{
"size": 24,
"query": {
"bool": {
"filter": [
{ "term": { "account_id": 42 } },
{ "term": { "in_stock": true } },
{ "range": { "price_cents": { "lte": 15000 } } }
],
"must": [
{
"multi_match": {
"query": "usb-c adapter",
"fields": ["name^3", "sku^5", "summary"],
"fuzziness": "AUTO"
}
}
]
}
},
"sort": [
{ "_score": "desc" },
{ "id": "asc" }
],
"search_after": [14.821, 109482]
}
Shield Hot Queries With Redis Response Caching
Autocomplete prefixes, landing categories, and empty-search browse views repeat constantly. Normalize query keys, store serialized hit IDs in Redis for 30–120 seconds (refer to the Redis developer docs and AWS architecture articles for cache-aside patterns), and serve repeated lookups in ~1ms without touching search nodes.
Production Checklist Before Launch
Lock down three operational habits before exposing your search cluster to live customer traffic:
- Right-size shard counts: Target 10–50 GB per shard; allocating 15 shards for a 400 MB catalog wastes heap and file descriptors for zero throughput gain.
- Centralize multi-tenant isolation: Inject
account_idfilters inside a single repository or search gateway class—never trust client parameters. For deeper tenant boundary patterns, review multi-tenant SaaS database design. - Test relevance with golden queries: Save 25 real customer queries (typos, part numbers, multi-word phrases) and assert top-five expectations in CI whenever you adjust analyzers or field boosts.
Shipping Production Search With SmitDev
Whether you are adding instant faceted discovery inside bespoke web software or replacing sluggish legacy SQL search during a legacy platform upgrade, SmitDev builds clean, test-covered search pipelines you own completely. Engagements operate transparently at $55 daily (8–9 focused engineering hours), $1,999 monthly for dedicated roadmap delivery, or flexible hourly development support.
Tell us about your catalog size and latency goals and we will design an index mapping, sync worker topology, and relevance strategy tailored to your stack.