Backend

Implementing Search with Elasticsearch

Mayur Dabhi
Mayur Dabhi
May 13, 2026
15 min read

The search box usually starts as WHERE name LIKE '%term%', and for a few thousand rows that's fine. Then the products table grows, the query starts showing up in the slow log, and someone files a bug because searching "macbok" returns nothing. LIKE has no idea about relevance, typos, or plurals, and it gets slower as the table grows.

This post walks through how I set up Elasticsearch for that kind of problem: running it locally, designing a mapping, writing queries with the Query DSL, building facets with aggregations, and wiring it into a Laravel app so the index stays in sync with MySQL.

Why Elasticsearch Over SQL LIKE?

A SELECT * FROM products WHERE name LIKE '%laptop%' has a leading wildcard, so MySQL can't use a normal B-tree index and ends up scanning rows. Elasticsearch uses an inverted index (the same idea as the index at the back of a book): it maps each term to the documents that contain it, so lookups stay fast as the data grows, and every hit comes back with a relevance score.

How Elasticsearch Works

You send JSON documents to Elasticsearch and it stores them in indices, which play roughly the role of database tables. Each index is split into shards, and each shard is its own Lucene index that can live on a different node. That's how it scales out: add nodes, and shards get spread across them.

The vocabulary you'll keep running into:

Client REST / HTTP Elasticsearch Cluster Node 1 (Master) Shard P0 Replica R1 Inverted Index (Lucene) Node 2 Shard P1 Replica R0 Inverted Index Node 3 Shard P2 Replica R2 Inverted Index JSON

Elasticsearch cluster with 3 nodes, 3 primary shards (P0 to P2), and 3 replicas. Each replica sits on a different node from its primary.

Installation and Setup

Elasticsearch runs on the JVM. Recent versions bundle their own JDK, but for local work I still just use Docker so nothing gets installed on my machine.

1

Run Elasticsearch with Docker

Quickest way to get a node up. Nothing to install besides Docker, and you can throw it away when you're done.

Terminal: Docker
# Pull and run Elasticsearch 8.x (single-node dev mode)
docker run -d \
  --name elasticsearch \
  -p 9200:9200 \
  -e "discovery.type=single-node" \
  -e "xpack.security.enabled=false" \
  docker.elastic.co/elasticsearch/elasticsearch:8.12.0

# Verify it's running
curl http://localhost:9200

# Expected output:
# {
#   "name" : "...",
#   "cluster_name" : "docker-cluster",
#   "version" : { "number" : "8.12.0", ... }
# }
2

Or Install Natively (Ubuntu/Debian)

On a production VM, the apt package gives you a systemd service, so the node comes back after a reboot or crash.

Terminal: Ubuntu
# Import GPG key
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo gpg --dearmor -o /usr/share/keyrings/elasticsearch-keyring.gpg

# Add repository
echo "deb [signed-by=/usr/share/keyrings/elasticsearch-keyring.gpg] https://artifacts.elastic.co/packages/8.x/apt stable main" | sudo tee /etc/apt/sources.list.d/elastic-8.x.list

# Install
sudo apt update && sudo apt install elasticsearch

# Enable and start
sudo systemctl enable elasticsearch
sudo systemctl start elasticsearch
Security in Production

Elasticsearch 8.x ships with TLS and authentication enabled by default. The xpack.security.enabled=false flag above is for local development only. In production, keep security on and put the cluster behind a firewall. Port 9200 should never be reachable from the public internet; open clusters get found and wiped by bots.

If the Container Exits Right Away

On Linux hosts, a common startup failure is max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]. Fix it on the host with sudo sysctl -w vm.max_map_count=262144 (and add it to /etc/sysctl.conf so it survives a reboot). Check docker logs elasticsearch first when the node won't come up.

Designing Your Index Mapping

The mapping is your schema, and it's worth getting right before you load real data, because most mapping changes require a full reindex. You can add new fields later, but you can't change the type of a field that already has documents. If you skip the mapping, dynamic mapping will guess types for you, and its guesses (every string becomes text plus a .keyword subfield) are rarely what you want. The two field types you'll use most:

HTTP: Create Index with Mapping
PUT /products
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1,
    "analysis": {
      "analyzer": {
        "product_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": ["lowercase", "asciifolding", "stop"]
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "analyzer": "product_analyzer",
        "fields": {
          "keyword": { "type": "keyword" }
        }
      },
      "description": { "type": "text", "analyzer": "product_analyzer" },
      "category": { "type": "keyword" },
      "price": { "type": "float" },
      "rating": { "type": "float" },
      "in_stock": { "type": "boolean" },
      "tags": { "type": "keyword" },
      "created_at": { "type": "date" }
    }
  }
}

The name field uses a multi-field mapping: name for full-text search and name.keyword for exact match and sorting. You send the value once and Elasticsearch indexes it both ways. If you try to sort on a plain text field you'll get an error about fielddata being disabled; sorting on name.keyword is the fix.

Field Type Use Case Analyzable Aggregatable
text Full-text search (articles, descriptions) Yes No
keyword Filtering, facets, exact match No Yes
integer / float Numeric ranges, sorting, math No Yes
date Date ranges, time-based sorting No Yes
boolean Binary flags No Yes
nested Arrays of objects with independent queries Depends Yes

Indexing Documents

Documents go in with a PUT or POST. Elasticsearch will generate an ID if you don't pass one, but I always use the database primary key. That way an update to row 42 overwrites document 42 instead of creating a duplicate.

HTTP: Index, Update, Delete Documents
# Index a document with explicit ID (recommended: use the DB primary key)
PUT /products/_doc/1
{
  "name": "MacBook Pro 16-inch M3",
  "description": "Apple's most powerful laptop with M3 Pro chip, 18GB RAM, and 512GB SSD.",
  "category": "Laptops",
  "price": 2499.99,
  "rating": 4.8,
  "in_stock": true,
  "tags": ["apple", "laptop", "m3", "professional"],
  "created_at": "2026-01-15"
}

# Update a specific field (partial update)
POST /products/_update/1
{
  "doc": {
    "price": 2299.99,
    "in_stock": false
  }
}

# Delete a document
DELETE /products/_doc/1

# Bulk indexing (much more efficient for large datasets)
POST /_bulk
{ "index": { "_index": "products", "_id": "2" } }
{ "name": "Dell XPS 15", "category": "Laptops", "price": 1799.99, "rating": 4.5, "in_stock": true, "tags": ["dell", "laptop"] }
{ "index": { "_index": "products", "_id": "3" } }
{ "name": "Sony WH-1000XM5", "category": "Headphones", "price": 349.99, "rating": 4.9, "in_stock": true, "tags": ["sony", "headphones", "noise-cancelling"] }

For initial imports, use the Bulk API. One request per document means one HTTP round trip per document, and that adds up fast. Batching usually makes imports many times faster. Note that a bulk request can partly fail: the response has "errors": true and per-item errors, so check it instead of assuming a 200 means everything was indexed.

Query DSL: Searching Your Data

Queries are written as JSON in the Query DSL. The distinction that matters most is which context a clause runs in:

Match Query: Basic Full-Text Search

HTTP: Match and Multi-Match Queries
# Simple match: searches a single field
GET /products/_search
{
  "query": {
    "match": {
      "name": "macbook pro"
    }
  }
}

# Multi-match: search across multiple fields with field boosting
GET /products/_search
{
  "query": {
    "multi_match": {
      "query": "macbook pro",
      "fields": ["name^3", "description", "tags^2"],
      "type": "best_fields",
      "fuzziness": "AUTO"
    }
  },
  "_source": ["name", "price", "rating"],
  "from": 0,
  "size": 10
}
# name^3 means "name" is 3x more important than description
# fuzziness: AUTO handles typos (e.g. "macbok" still finds "MacBook")

Bool Query: Combining Conditions

Almost every real search ends up as a bool query. It wraps other queries in four kinds of clause:

HTTP: Bool Query with Filters
GET /products/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "multi_match": {
            "query": "laptop",
            "fields": ["name^3", "description"],
            "fuzziness": "AUTO"
          }
        }
      ],
      "filter": [
        { "term": { "in_stock": true } },
        { "term": { "category": "Laptops" } },
        {
          "range": {
            "price": { "gte": 1000, "lte": 3000 }
          }
        },
        {
          "range": {
            "rating": { "gte": 4.0 }
          }
        }
      ],
      "must_not": [
        { "term": { "tags": "refurbished" } }
      ]
    }
  },
  "sort": [
    { "_score": { "order": "desc" } },
    { "rating": { "order": "desc" } }
  ],
  "from": 0,
  "size": 20
}

The full-text part is in must because its score matters, while category, price, stock and rating are in filter (yes/no match). That's the split you want: filters skip scoring and Elasticsearch can cache them, so repeated facet clicks are cheap.

One gotcha here: term does no analysis. A term query for "Laptops" against a text field returns nothing, because the indexed token is laptops (lowercased). Use term on keyword fields and match on text fields.

Highlight and Autocomplete

HTTP: Highlighting and Suggest
# Highlight matching terms in results
GET /products/_search
{
  "query": {
    "match": { "description": "M3 chip performance" }
  },
  "highlight": {
    "fields": {
      "description": {
        "pre_tags": ["<mark>"],
        "post_tags": ["</mark>"],
        "number_of_fragments": 3,
        "fragment_size": 150
      }
    }
  }
}

# Completion suggester (autocomplete as-you-type)
# First, add completion field to mapping:
# "name_suggest": { "type": "completion" }

POST /products/_search
{
  "suggest": {
    "product-suggest": {
      "prefix": "mac",
      "completion": {
        "field": "name_suggest",
        "size": 5,
        "skip_duplicates": true
      }
    }
  }
}

Aggregations: Analytics and Facets

The sidebar on a shop page ("Laptops (124)", "Under $500 (38)") is the usual reason to reach for aggregations. They compute counts, ranges and stats over the documents that matched your query, in the same request that returns the hits. If you know SQL, think GROUP BY that runs on every shard in parallel and gets merged at the end.

HTTP: Faceted Search with Aggregations
GET /products/_search
{
  "query": {
    "bool": {
      "must": { "match": { "name": "laptop" } },
      "filter": { "term": { "in_stock": true } }
    }
  },
  "aggs": {
    "by_category": {
      "terms": {
        "field": "category",
        "size": 10
      }
    },
    "price_ranges": {
      "range": {
        "field": "price",
        "ranges": [
          { "to": 500, "key": "Under $500" },
          { "from": 500, "to": 1000, "key": "$500 - $1000" },
          { "from": 1000, "to": 2000, "key": "$1000 - $2000" },
          { "from": 2000, "key": "Over $2000" }
        ]
      }
    },
    "avg_rating": {
      "avg": { "field": "rating" }
    },
    "price_stats": {
      "stats": { "field": "price" }
    },
    "top_tags": {
      "terms": { "field": "tags", "size": 20 }
    }
  },
  "size": 10
}

# Response includes:
# hits.hits[]: matched documents
# aggregations.by_category.buckets[]: facet counts per category
# aggregations.price_ranges.buckets[]: count per price range
# aggregations.avg_rating.value: 4.6
# aggregations.price_stats: { min, max, avg, sum, count }

PHP and Laravel Integration

I use the official PHP client and wrap it in a small service class, so controllers never build query arrays themselves. Install it with Composer (make sure the client's major version matches your cluster's, 8.x for 8.x):

Terminal: Install PHP Client
composer require elasticsearch/elasticsearch

Service Class Pattern

app/Services/SearchService.php
<?php

namespace App\Services;

use Elastic\Elasticsearch\ClientBuilder;
use Elastic\Elasticsearch\Client;

class SearchService
{
    private Client $client;
    private string $index = 'products';

    public function __construct()
    {
        $this->client = ClientBuilder::create()
            ->setHosts([config('services.elasticsearch.host', 'localhost:9200')])
            ->build();
    }

    public function indexProduct(array $product): void
    {
        $this->client->index([
            'index' => $this->index,
            'id'    => $product['id'],
            'body'  => [
                'name'        => $product['name'],
                'description' => $product['description'],
                'category'    => $product['category'],
                'price'       => (float) $product['price'],
                'rating'      => (float) $product['rating'],
                'in_stock'    => (bool) $product['in_stock'],
                'tags'        => $product['tags'] ?? [],
                'created_at'  => $product['created_at'],
            ],
        ]);
    }

    public function deleteProduct(int $id): void
    {
        $this->client->delete([
            'index' => $this->index,
            'id'    => $id,
        ]);
    }

    public function search(
        string $query,
        array $filters = [],
        int $page = 1,
        int $perPage = 20
    ): array {
        $must = [];
        $filterClauses = [];

        if (!empty($query)) {
            $must[] = [
                'multi_match' => [
                    'query'     => $query,
                    'fields'    => ['name^3', 'description', 'tags^2'],
                    'fuzziness' => 'AUTO',
                ],
            ];
        } else {
            $must[] = ['match_all' => new \stdClass()];
        }

        if (!empty($filters['category'])) {
            $filterClauses[] = ['term' => ['category' => $filters['category']]];
        }

        if (isset($filters['in_stock']) && $filters['in_stock']) {
            $filterClauses[] = ['term' => ['in_stock' => true]];
        }

        if (!empty($filters['min_price']) || !empty($filters['max_price'])) {
            $range = [];
            if (!empty($filters['min_price'])) $range['gte'] = (float) $filters['min_price'];
            if (!empty($filters['max_price'])) $range['lte'] = (float) $filters['max_price'];
            $filterClauses[] = ['range' => ['price' => $range]];
        }

        $params = [
            'index' => $this->index,
            'body'  => [
                'query' => [
                    'bool' => [
                        'must'   => $must,
                        'filter' => $filterClauses,
                    ],
                ],
                'aggs' => [
                    'categories'   => ['terms' => ['field' => 'category', 'size' => 20]],
                    'price_ranges' => [
                        'range' => [
                            'field'  => 'price',
                            'ranges' => [
                                ['to' => 500],
                                ['from' => 500, 'to' => 1000],
                                ['from' => 1000, 'to' => 2000],
                                ['from' => 2000],
                            ],
                        ],
                    ],
                    'avg_rating' => ['avg' => ['field' => 'rating']],
                ],
                'highlight' => [
                    'fields' => [
                        'name'        => ['number_of_fragments' => 0],
                        'description' => ['number_of_fragments' => 2, 'fragment_size' => 150],
                    ],
                ],
                'from' => ($page - 1) * $perPage,
                'size' => $perPage,
                'sort' => [
                    ['_score'  => ['order' => 'desc']],
                    ['rating'  => ['order' => 'desc']],
                ],
            ],
        ];

        $response = $this->client->search($params);

        return [
            'total'          => $response['hits']['total']['value'],
            'hits'           => $response['hits']['hits'],
            'aggregations'   => $response['aggregations'] ?? [],
            'took_ms'        => $response['took'],
        ];
    }
}

Note the match_all => new \stdClass() line. An empty PHP array would be encoded as [], and Elasticsearch rejects that because it expects an object ({}). That one trips people up the first time.

Keeping Elasticsearch in Sync with MySQL

Treat Elasticsearch as a read-optimized copy of your data. MySQL stays the source of truth, and you should be able to rebuild the index from it at any time. In Laravel, the simplest way to push changes across is a Model Observer:

app/Observers/ProductObserver.php
<?php

namespace App\Observers;

use App\Models\Product;
use App\Services\SearchService;

class ProductObserver
{
    public function __construct(private SearchService $search) {}

    public function saved(Product $product): void
    {
        $this->search->indexProduct($product->toArray());
    }

    public function deleted(Product $product): void
    {
        $this->search->deleteProduct($product->id);
    }
}

// Register in AppServiceProvider::boot():
// Product::observe(ProductObserver::class);
1

Initial Bulk Import

For existing data, write an Artisan command that walks the table in chunks and indexes them, 500 to 1000 records at a time. The version below indexes one document per call to keep it short; for a big table, build one Bulk API request per chunk instead.

2

Real-Time Sync via Observer

The observer picks up creates, updates and deletes made through Eloquent, so controllers don't need to know about search. Two caveats: if the save happens inside a DB transaction that later rolls back, the index already has the change, so implement ShouldHandleEventsAfterCommit on the observer (Laravel 10+). And in production I'd push the indexing onto a queue so a slow or unreachable cluster doesn't fail the user's request.

3

Nightly Re-Index (Optional)

A scheduled reindex catches whatever the observer missed. Mass updates like Product::where(...)->update([...]) run straight SQL and never fire model events, so they're the usual cause of drift.

Artisan Bulk Reindex Command

app/Console/Commands/ReindexProducts.php
<?php

namespace App\Console\Commands;

use App\Models\Product;
use App\Services\SearchService;
use Illuminate\Console\Command;

class ReindexProducts extends Command
{
    protected $signature   = 'search:reindex {--fresh : Delete index before reindexing}';
    protected $description = 'Reindex all products in Elasticsearch';

    public function handle(SearchService $search): int
    {
        $total = Product::count();
        $bar   = $this->output->createProgressBar($total);

        Product::query()
            ->with('category')
            ->chunkById(500, function ($products) use ($search, $bar) {
                foreach ($products as $product) {
                    $search->indexProduct($product->toArray());
                    $bar->advance();
                }
            });

        $bar->finish();
        $this->newLine();
        $this->info("Indexed {$total} products successfully.");

        return Command::SUCCESS;
    }
}

Performance Best Practices

Small indexes are fast no matter what you do. These are the settings and habits that start to matter once the data grows:

Zero-Downtime Reindexing Pattern

Create products_v2, index all data into it, then swap the products alias in one call: POST /_aliases with {"actions": [{"remove": {"index": "products_v1", "alias": "products"}}, {"add": {"index": "products_v2", "alias": "products"}}]}. Both actions apply together, so the app never queries a half-built index. This only works if the app was pointing at the alias from day one, which is why I create the alias before the first deploy.

When I'd Use Elasticsearch (and When I Wouldn't)

I reach for it when search is a real product feature: relevance ranking matters, users make typos, there are facets in a sidebar, or the catalog is big enough that LIKE queries hurt. Logs and analytics over large volumes of documents are another good fit.

I'd hold off when:

If you do go ahead, check a few things before production: security is on, the app talks to an alias rather than a raw index, the mapping is explicit, the sync path handles rolled-back transactions and mass updates, and you've actually run a full reindex end to end at least once so you know how long it takes.

Elasticsearch Search Database Full-text Search Query DSL PHP Laravel Backend
Mayur Dabhi

Mayur Dabhi

Full Stack Developer with 5+ years of experience building scalable web applications with Laravel, React, and Node.js.