HomeBlogHow to Build a Search System...

Engineering Guide · 9 min read · September 26, 2026

How to Build a Search System Using Elasticsearch

Relational LIKE queries fall apart once users expect typo tolerance, weighted field relevance, and fast faceted filters. This engineering guide explains when Elasticsearch beats PostgreSQL full-text search, how to lock down explicit index mappings, swap aliases with zero downtime, keep databases synchronized, and paginate deeply without crashing JVM heap.

Author
Smit Desai
Published
September 26, 2026
Read time
9 min read
Topic
Data & Databases
Services
Custom Web · Mobile Apps · All Services

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:

  1. 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.
  2. Centralize multi-tenant isolation: Inject account_id filters inside a single repository or search gateway class—never trust client parameters. For deeper tenant boundary patterns, review multi-tenant SaaS database design.
  3. 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.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Infrastructure Proof

300+ WordPress & Cloud Server Fleet

From server-level management of 300+ WordPress sites for a Finland client to PostgreSQL query tuning (3,982 -> 52 queries).

Pillar 2 · Legacy Rescue

Upgrade Old Software (10 Hrs Free)

Audit bottlenecks, eliminate security vulnerabilities, and stabilize production servers—starting with 10 free engineering hours.

01 — Frequently asked questions

data & databases

When is PostgreSQL full-text search enough instead of deploying Elasticsearch?

PostgreSQL tsvector paired with pg_trgm works well below a couple million rows when you need straightforward keyword matching without heavy multi-facet aggregations. Adopt Elasticsearch once you need weighted multi-field BM25 tuning, synonyms, typo tolerance at scale, and sub-50ms facet counts.

Why does dynamic field mapping cause production outages in Elasticsearch?

Dynamic mapping infers field types from whichever document lands first. Indexing an all-numeric SKU as a long rejects later alphanumeric SKUs, while arbitrary user-defined JSON keys trigger mapping explosions that bloat cluster state across every node.

How do you prevent data drift between PostgreSQL or MySQL and Elasticsearch?

Never write to Elasticsearch synchronously inside HTTP controllers. Record mutations in a transactional outbox table or dispatch queued sync jobs after commit, batch with _bulk upserts, and guard against out-of-order updates using external version numbers.

Why do deep from-and-size queries trigger Elasticsearch memory errors?

Fetching page 500 with 20 results forces every shard to collect, score, and sort 10,020 hits in heap before discarding 10,000. Replace deep offsets with search_after cursors anchored by a unique tie-breaker field.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.