Search is the feature teams postpone until someone asks why typing "3 bed bungalow near langley" returns nothing, while a listing with exactly that description sits in the database. That gap is where dedicated search engines live.
This is a practical guide to Elasticsearch for the team about to make that call: what it gives you, when your database is still enough, which alternatives beat it, and working code for Laravel, Symfony and Node.js.
A search index is a derived read model, never a system of record. If you cannot rebuild it from your database on a Tuesday afternoon, you have built a second database with no backups.
We have built and inherited search behind property portals, freight platforms and internal document systems. This is the version we would hand a team starting this week.
Why SQL Search Fails
The first attempt is always LIKE '%term%' against a text column. It works on the demo data, then it stops working, and no amount of database tuning will fix it.
- A leading wildcard cannot use a B-tree index. The index is sorted by prefix, so
'%bungalow%'scans every row. - There is no ranking. SQL returns a set, not an ordered list of how well each row matched. Every result is equally right, which is the same as having no answer.
- There is no tolerance. "bunglow", "3-bed" and "langley, b.c." are all misses against a literal substring.
- Facet counts need a second pass. Showing "Langley (24)" beside a filter means counting the filtered set as well as returning it, once per facet.
None of that is a flaw in the database. It is a mismatch. A relational index answers "which rows match this value"; a search box asks "which documents are most relevant to this text".
Why Elasticsearch Became the Default Search Engine
Elasticsearch was designed around that second question from the start. It stores documents rather than rows, and it ranks them rather than returning a set.
Underneath it sits Apache Lucene, the text-search library most of this category is built on. Elasticsearch adds the distribution, the JSON API and the tooling. That is why it became the default: one query can match text, apply filters, count facets and sort by distance, and Kibana, Logstash and Beats were already there when teams went looking.
The trade is that it is a second system: your database stays the system of record, and Elasticsearch holds a copy shaped for reading. Everything else follows from that.
What Elasticsearch Gives You That SQL Does Not
Most of the decision comes down to one comparison — the things users expect from a search box, and what each side does about them.
| User expectation | Traditional SQL | Elasticsearch |
|---|---|---|
| Typo tolerance | Difficult — an extension or hand-rolled matching | Built in, set per query |
| Autocomplete | Custom work | Built in |
| Relevance ranking | Limited | Native |
| Faceted filtering | Expensive — a second pass per facet | Native |
| Geo search | Limited without extensions | Excellent |
| Analytics over results | Separate tooling | Built in |
"Built in" is not the same as free — you still design the mapping, tune the analyzer and run the cluster. It means the behaviour ships with the engine instead of living in your application code.
When PostgreSQL Full-Text Search Is Enough
Before adding a cluster, spend an hour on what your database already does. Postgres has a real full-text implementation: tsvector for the analysed document, tsquery for the query, GIN for the index, and pg_trgm for fuzzy matching.
ALTER TABLE listings
ADD COLUMN document tsvector
GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(address, '')), 'B')
) STORED;
CREATE INDEX listings_document_idx ON listings USING GIN (document);
SELECT id, title, ts_rank(document, query) AS rank
FROM listings, websearch_to_tsquery('english', $1) AS query
WHERE document @@ query AND status = 'active'
ORDER BY rank DESC LIMIT 24;
The generated column is the point. The index updates inside the same transaction as the row — no sync pipeline, no queue, no lag, and no class of bug where search shows a price the database changed an hour ago. Teams give that up too casually.
Move off Postgres when you hit one of these, and not before.
- Analysis you must change without a migration.
setweightgives you four labels, not a synonym list the merchandising team edits. - Facet counts over the filtered set, on every query. A search engine builds structures for exactly that; Postgres counts rows.
- Search traffic competing with transactional traffic. Once a spike in searches slows checkout, the workloads want separate machines — and once they are separate, you have accepted a sync layer anyway.
- Geo and text scored together. PostGIS filters beautifully. Ranking a text match and a distance decay into one score is not its job.
How Elasticsearch Works: Index, Mapping, Shard and Replica
You do not need the internals to use Elasticsearch well. You do need five words, because every later decision is one of them.
| Word | What it is | Why it matters |
|---|---|---|
| Index | A named collection of documents | The unit everything attaches to: mapping, settings, permissions |
| Mapping | The field types, and how each one is indexed | A keyword sorts and aggregates; a text scores |
| Analyzer | The chain that turns text into stored tokens | You can only query what it produced |
| Shard | One slice of the data, searched independently | Parallelism, and a corpus larger than one machine |
| Replica | A copy of a shard on another node | Read capacity, and survival of a lost node |
Three ideas cover the rest of the model.
- It does not scan rows. An inverted index maps every term to the documents containing it, so matching a word is a lookup, not a pass over the table.
- It keeps a search-optimized copy of your data. New records become searchable within seconds rather than instantly, and that trade-off is what allows fast search across millions of records.
- It searches shards in parallel. Elasticsearch spreads a search across shards and combines the results, so a large dataset can be searched across several machines at once.
One consequence matters for design: replicas make reads cheaper by making writes more expensive, because every write runs on every copy.
Elasticsearch Alternatives: Solr, Meilisearch, Typesense, Algolia and OpenSearch
Elasticsearch is the default for good reasons, and the wrong default often enough to be worth ten minutes of thought. Each of these wins somewhere real.
| Engine | Wins when | Loses when |
|---|---|---|
| Elasticsearch | Text, filters, geo and aggregations must come back from one query | Nobody owns the cluster — it expects operators and degrades quietly without them |
| Apache Solr | Relevance is governed by configuration in version control, and JVM muscle exists already | You want managed hosting and a broad modern client ecosystem |
| Meilisearch | Search-as-you-type over a corpus one machine holds, with a first-party Scout driver | You need nested aggregations, analytics, or a corpus past what memory allows |
| Typesense | The same instant-search brief plus faceting, curation rules and a cluster you self-host | Analytical workloads and complex relevance pipelines — deliberately narrower |
| Algolia | Engineering time is scarcer than money, and someone wants a merchandising interface | Volume grows into the pricing curve, or the index must sit in your own network |
| Amazon OpenSearch | You are on AWS already and want IAM, VPC and managed lifecycle policies | You need a recent Elasticsearch feature — the two diverged after the fork |
| PostgreSQL full text | The data lives in Postgres already and the index updates in the same transaction | You need editable analysis, facet counts at scale, or search off the transactional box |
Semantic search sits outside this table deliberately. Vector retrieval answers what keyword search cannot — a user describing what they want in words the document never uses — and fails at exactly what keyword search is best at. Serious systems run both, which is covered in our hybrid retrieval walkthrough.
Running Elasticsearch Locally with Docker Compose
Per-operating-system install instructions age badly and nobody follows them anyway. A Compose file is the artifact worth having, because your continuous integration can start the same one.
# compose.yaml - a single-node cluster for development, not for production
services:
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:${ES_VERSION}
environment:
- discovery.type=single-node
- ES_JAVA_OPTS=-Xms1g -Xmx1g
- xpack.security.enabled=true
- xpack.security.http.ssl.enabled=false # auth stays on, local TLS does not
- ELASTIC_PASSWORD=${ELASTIC_PASSWORD}
ports: ["9200:9200"]
volumes: [esdata:/usr/share/elasticsearch/data]
healthcheck:
test: ["CMD-SHELL", "curl -fsS -u elastic:${ELASTIC_PASSWORD} localhost:9200/_cluster/health"]
interval: 10s
retries: 12
volumes:
esdata:
ES_VERSION lives in .env, so the file does not carry a point release into your repository forever. Two choices here are worth copying.
- Authentication stays on. Most tutorials set
xpack.security.enabled=falsebecause certificates are annoying locally. Disable transport TLS instead and keep auth, so the code path you develop against is the one you ship. - Yellow is the correct health status here. A single node cannot place replica shards, so it reports yellow forever — and scripts that wait for green hang until they time out.
Designing Your Elasticsearch Mapping
Create the index explicitly, before the first document arrives. Dynamic mapping lets that first document decide the type of every field, and a numeric-looking string that arrives as text is a rebuild with a date on it.
PUT /listings_v1
{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1,
"refresh_interval": "5s",
"analysis": {
"filter": {
"keep_ids": { "type": "keyword_marker", "keywords_path": "protected.txt" },
"en_stem": { "type": "stemmer", "language": "light_english" }
},
"analyzer": {
"listing_text": {
"tokenizer": "standard",
"filter": ["lowercase", "asciifolding", "keep_ids", "en_stem"]
}
}
}
},
"mappings": {
"dynamic": "strict",
"properties": {
"mls_id": { "type": "keyword" },
"title": { "type": "text", "analyzer": "listing_text" },
"address": { "type": "text", "analyzer": "listing_text",
"fields": { "raw": { "type": "keyword" } } },
"status": { "type": "keyword" },
"price": { "type": "integer" },
"beds": { "type": "short" },
"location": { "type": "geo_point" }
}
}
}
Four choices carry the weight here.
dynamic: strictrejects unexpected fields loudly instead of typing them silently.address.rawis akeywordbeside the analysedtext, because you cannot sort or facet on an analysed field.keyword_markerahead of the stemmer protects identifiers, which a stemmer built for English prose will mangle.geo_pointis what makes distance filters and distance-decay scoring available at all.
Name it listings_v1, never listings. The bare name is reserved for an alias, and application code must only ever see the alias.
Using Elasticsearch with Laravel
Install the official PHP client and register it as a singleton. Any snippet using Elasticsearch\ClientBuilder is from the version 7 client — version 8 moved everything under the Elastic\ namespace and returns response objects rather than arrays, which is why ->asArray() appears below.
// composer require elasticsearch/elasticsearch:^8.0
// app/Providers/AppServiceProvider.php
use Elastic\Elasticsearch\Client;
use Elastic\Elasticsearch\ClientBuilder;
public function register(): void
{
$this->app->singleton(Client::class, fn () => ClientBuilder::create()
->setHosts([config('services.elasticsearch.host')])
->setBasicAuthentication('elastic', config('services.elasticsearch.password'))
->setRetries(2)
->build());
}
Backfilling is a bulk operation. Two details separate an indexer that survives a retry from one that quietly corrupts the index.
- A bulk request answers 200 with per-item failures inside. Code that checks only the HTTP status reports a successful backfill that silently dropped every document with a malformed date.
- Send the row's
updated_atas an external version. The engine then rejects a write older than what it already holds, so a replayed batch cannot overwrite a newer live edit with a stale snapshot.
final class ListingIndexer
{
public function __construct(private readonly Client $es) {}
public function backfill(string $index): void
{
Listing::query()->where('status', 'active')->chunkById(500, function ($listings) use ($index) {
$body = [];
foreach ($listings as $listing) {
$body[] = ['index' => [
'_index' => $index,
'_id' => $listing->mls_id,
'version' => $listing->updated_at->getTimestamp(),
'version_type' => 'external',
]];
$body[] = $this->document($listing); // the projection the query needs
}
$response = $this->es->bulk(['refresh' => false, 'body' => $body])->asArray();
if ($response['errors'] === true) {
// The call answers 200 even when individual documents were rejected.
Log::error('bulk index rejected items', ['items' => $response['items']]);
}
});
}
}
On the query side, put anything binary in a filter rather than the scoring clause. A filter contributes nothing to the score, so its result is cached and reused — status, tenant, category and price range all belong there.
public function search(string $index, string $terms, ?int $maxPrice = null): array
{
$filters = [['term' => ['status' => 'active']]];
if ($maxPrice !== null) {
$filters[] = ['range' => ['price' => ['lte' => $maxPrice]]];
}
return $this->es->search([
'index' => $index,
'body' => [
'size' => 24,
'_source' => ['mls_id', 'title', 'price', 'location'],
'query' => ['bool' => [
'must' => [['multi_match' => [
'query' => $terms,
'fields' => ['title^3', 'address', 'description'],
'fuzziness' => 'AUTO',
]]],
'filter' => $filters,
]],
'aggs' => ['by_beds' => ['terms' => ['field' => 'beds']]],
],
])->asArray();
}
One note on Laravel Scout. It ships first-party drivers for Algolia, Meilisearch, Typesense and a database fallback — not for Elasticsearch. If Scout's ergonomics are what you want, that list is effectively your shortlist.
Using Elasticsearch with Symfony
Symfony's route is FOSElasticaBundle over the Elastica library. It maps Doctrine entities to an index and gives you a finder that returns hydrated objects.
# config/packages/fos_elastica.yaml
fos_elastica:
clients:
default: { url: '%env(ELASTICSEARCH_URL)%' }
indexes:
listings:
index_name: listings_v1
properties:
title: { type: text, analyzer: listing_text }
address: { type: text, analyzer: listing_text }
status: { type: keyword }
price: { type: integer }
persistence:
driver: orm
model: App\Entity\Listing
provider: ~
finder: ~
listener: { enabled: false }
That last line is the one to argue about. The Doctrine listener indexes on flush, inside the request, so a slow or unreachable cluster turns a customer's save into a failed request. Disable it and push index updates through Messenger, where a retry is a queue concern rather than a user-facing error.
use Elastica\Query;
use Elastica\Query\{BoolQuery, MatchQuery, Range, Term};
use FOS\ElasticaBundle\Finder\PaginatedFinderInterface;
final class ListingFinder
{
// Autowired by index name: the "listings" index exposes $listingsFinder.
public function __construct(private readonly PaginatedFinderInterface $listingsFinder) {}
public function search(string $terms, ?int $maxPrice = null): array
{
$bool = new BoolQuery();
$bool->addMust((new MatchQuery())->setFieldQuery('title', $terms));
$bool->addFilter(new Term(['status' => 'active']));
if ($maxPrice !== null) {
$bool->addFilter(new Range('price', ['lte' => $maxPrice]));
}
return $this->listingsFinder->find(Query::create($bool), 24);
}
}
If you are porting an older integration, one class has moved. Elastica\Query\Match became MatchQuery, because match is a reserved keyword in PHP 8. Every pre-8 snippet is now a parse error, which is the better kind of breakage.
Using Elasticsearch with Node.js and TypeScript
The JavaScript client's major version must match the cluster's. It is not a soft guarantee: a version 8 client against a version 7 cluster fails on the compatibility header rather than degrading gracefully.
For ingestion, use the bulk helper rather than assembling the alternating action/document array by hand. It chunks the stream, applies backpressure, retries what is retryable, and hands you the documents it gave up on.
// src/search/client.ts
import { Client } from "@elastic/elasticsearch";
export const es = new Client({
node: process.env.ELASTICSEARCH_URL!,
auth: { username: "elastic", password: process.env.ELASTICSEARCH_PASSWORD! },
maxRetries: 2,
});
export type ListingSource = {
mls_id: string;
title: string;
price: number;
location: { lat: number; lon: number };
};
export async function indexListings(index: string, listings: ListingSource[]) {
return es.helpers.bulk({
datasource: listings,
onDocument: (doc) => ({ index: { _index: index, _id: doc.mls_id } }),
onDrop: (doc) => logger.error({ id: doc.document.mls_id, error: doc.error }, "dropped"),
refreshOnCompletion: false,
concurrency: 2,
});
}
Searching changed shape in the version 8 client. Options are flat at the top level with no body wrapper, and search takes a generic, so _source stays typed all the way to the component that renders it.
// src/search/search-listings.ts
export async function searchListings(index: string, terms: string, maxPrice?: number) {
const res = await es.search<ListingSource>({
index,
size: 24,
_source: ["mls_id", "title", "price", "location"],
query: {
bool: {
must: [{ multi_match: { query: terms, fields: ["title^3", "address"], fuzziness: "AUTO" } }],
filter: [
{ term: { status: "active" } },
...(maxPrice ? [{ range: { price: { lte: maxPrice } } }] : []),
],
},
},
aggs: { by_beds: { terms: { field: "beds" } } },
});
return { hits: res.hits.hits.map((h) => h._source!), facets: res.aggregations };
}
Never accept a query object from the browser. Every search endpoint we have reviewed that forwarded client-supplied query bodies could be turned into an aggregation over the entire index.
Reindexing Elasticsearch Without Downtime
Some changes require rebuilding the index. Adding a field is free; changing a field's type or an analyzer is not, because the documents you already stored were written with the old tokens.
The common approach is to build a new index in the background and switch traffic once it is ready. That is why application code addresses an alias, never an index name — the cutover is one atomic request rather than a deployment.
POST /_aliases
{
"actions": [
{ "remove": { "index": "listings_v1", "alias": "listings" } },
{ "add": { "index": "listings_v2", "alias": "listings" } }
]
}
Rehearse it before you need it. If a reindex is a project, the team avoids it — and avoiding it is how one hasty analyzer decision becomes permanent.
Running Elasticsearch in Production: What Breaks First
"Search is broken" arrives through one support channel and means several unrelated things. This is the short version of the triage table we work from.
| What the report says | Look at first | Usually |
|---|---|---|
| "It finds nothing for X" | The analyze API, on the query and the document | An analyzer mismatch — the token you searched for was never produced |
| "It shows the old value" | Indexing lag, measured outside the cluster | The job copying changes across, not the engine |
| "It is slow for everyone" | How much of each document you ask for | Returning whole documents when the result card renders four fields |
| "The ranking got worse" | The score explanation for that one document | A boost added months ago to fix a different query |
One instrument beats a dashboard full of node metrics: write a synthetic document every minute carrying its own timestamp, and have a probe search for it. That measures the promise you made your users, not the health of a component.
Where Elasticsearch Shows Up in Real Systems
Three shapes cover most of what a search layer is asked to do.
- Real estate. On the LeadCity brokerage platform and the EstateBlock property portal, listings sync from MLS feeds into an Elasticsearch index that the map and the filter rail both read. Every pan and zoom re-runs a bounding-box filter, facet counts and a text match together — the wider architecture is in our guide to building a portal like Zillow.
- Logistics. Freight platforms like ShipPLX carry a modest corpus that churns constantly as shipments move, so the update pattern rather than the data volume decides the design.
- Internal documents. Contracts, tickets and knowledge bases — small corpora, hard vocabulary, and permissions applied as filters at query time. Filtering after ranking is how a document nobody should see ends up in a visible count.
If you take one thing from this guide, take the order. Prove your database is not enough, pick the engine on the row where it wins, write the mapping before the first document, and address it through an alias. Nearly every expensive search remediation we have been called into skipped one of those.
We design and operate search layers as part of our web application development work, and are asked just as often why an existing cluster has started misbehaving. If either is on your desk, tell us what your search is supposed to do and we will tell you what it is actually doing.
Frequently Asked Questions
When should I switch from PostgreSQL full-text search to Elasticsearch?
Switch only when you hit a specific limit: text analysis you must change without a migration, such as an editable synonym list; facet counts over the filtered set on every query; search traffic competing with transactional traffic; or text relevance and distance scored together. Until then, Postgres updates its index inside the same transaction as the row, with no sync pipeline and no lag.
Why is SQL LIKE search slow and inaccurate?
A LIKE query with a leading wildcard cannot use a B-tree index, so it scans every row. It also has no ranking, no tolerance for typos or variant spellings, and facet counts need a second pass per facet. That is not a database flaw but a mismatch: a relational index finds rows matching a value, while a search box asks which documents are most relevant.
How do you reindex Elasticsearch without downtime?
Build a new versioned index in the background and switch traffic once it is ready. Application code must always address an alias rather than an index name, so the cutover is one atomic aliases request that removes the old index from the alias and adds the new one. Rehearse it before you need it, so a reindex never becomes a project the team avoids.
What are the best alternatives to Elasticsearch?
It depends where you need to win. Apache Solr suits relevance governed by configuration with existing JVM skills; Meilisearch and Typesense suit instant search-as-you-type; Algolia suits teams with more money than engineering time; Amazon OpenSearch suits teams already on AWS; and PostgreSQL full-text search suits data already in Postgres. Elasticsearch wins when text, filters, geo and aggregations must return from one query.
Can Elasticsearch replace my main database?
No. A search index is a derived read model, never a system of record. Your database stays authoritative and Elasticsearch holds a copy shaped for reading, with new records becoming searchable within seconds rather than instantly. If you cannot rebuild the index from your database whenever you need to, you have built a second database with no backups.
