Elasticsearch is a distributed search and analytics engine that stores data as JSON documents and uses an inverted index to find matching documents almost instantly. It works by splitting data into shards, replicating them across nodes, and using Lucene-based indexing and querying to return ranked results in near real time.
Background: From Lucene to Distributed Search
Elasticsearch is built on Apache Lucene, a high-performance Java library for full-text search. Lucene provides the core indexing and search capabilities, but it is a library, not a server: it lacks distribution, replication, and a REST API. Elasticsearch wraps Lucene to add those features, turning a single-node search library into a clustered, scalable system.
Originally released in 2010, Elasticsearch has become a common choice for log analytics, application search, and data exploration. It stores data in JSON documents, each belonging to an index (roughly comparable to a table in a relational database). Documents are schema-free by default, though mappings can define field types explicitly.
How Elasticsearch Works: Indexing and Sharding
When you send a document to Elasticsearch, it is assigned to an index. Each index is divided into primary shards, which are independent Lucene instances. The number of primary shards is fixed at index creation (though reindexing or splitting can change it later). Sharding allows an index to scale beyond the storage and processing limits of a single machine.
Each shard is a self-contained Lucene index. Within a shard, Elasticsearch builds an inverted index: a mapping from terms (words or tokens) to the documents that contain them. This is the opposite of a forward index, which maps documents to their contents. The inverted index enables fast full-text queries because the engine can look up terms directly instead of scanning every document.
Before indexing, text fields are analyzed: the analyzer breaks text into tokens, lowercases them, removes stop words (common words like "the"), and applies stemming or other filters. The resulting terms are stored in the inverted index. For example, the sentence "The quick brown fox" might be tokenized to [quick, brown, fox].
Replicas are copies of primary shards. They provide redundancy and can serve read requests, improving search throughput. By default, each primary shard has one replica, but this can be configured.
How Queries Are Processed
When a search request arrives at a node, that node becomes the coordinating node for the request. It routes the query to a copy of every shard in the target index (primary or replica). Each shard executes the query locally and returns its top matching documents, along with scores. The coordinating node then merges these partial results, sorts them by relevance score (or another sort field), and returns the final page of results to the client.
This scatter-gather approach means query latency depends on the slowest shard. Too many shards can increase overhead; too few can limit parallelism. A common guideline is to keep shard sizes in the range of a few gigabytes to a few tens of gigabytes, though the ideal size depends on the workload.
Elasticsearch uses a relevance scoring algorithm (BM25 by default) that considers term frequency, inverse document frequency, and field length. This allows results to be ranked by how well they match the query, not just whether they match.
Near Real-Time Behavior and Refresh
Elasticsearch is often described as near real-time. When a document is indexed, it is first written to an in-memory buffer and a translog (transaction log) for durability. The document is not immediately searchable. A refresh operation, which happens automatically every second by default, writes the in-memory buffer to a new Lucene segment, making the document visible to search. This is why there is a short delay between indexing and searchability.
The translog ensures that documents are not lost if the node crashes before a refresh. On restart, Elasticsearch replays the translog to recover unflushed data. Periodically, a flush operation commits the translog to disk and clears it.
Segments are immutable: once written, they are not modified. Deletes and updates are handled by marking old documents as deleted and indexing new versions. Background merges combine smaller segments into larger ones and purge deleted documents, keeping the index efficient.
Cluster Architecture: Nodes, Master, and Discovery
A cluster is a group of nodes (Elasticsearch instances) that share the same cluster name. Nodes communicate over a transport protocol. One node is elected as the master, which manages cluster state: index creation, shard allocation, and node membership. Data nodes store shards and handle indexing and search. In larger clusters, dedicated master-eligible nodes can be used to avoid master bottlenecks.
Shard allocation is the process of assigning shards to nodes. The master tries to balance shards across nodes and avoid placing a primary and its replica on the same node. If a node fails, the master promotes replicas to primaries and reallocates shards to maintain redundancy.
Discovery mechanisms (such as seed hosts) allow nodes to find each other and form a cluster. Split-brain, where two masters are elected, is prevented by requiring a quorum of master-eligible nodes to elect a master.
Common Problems and Misconceptions
A frequent misconception is that Elasticsearch is a primary database. It can store data, but it lacks transactions, joins, and strong consistency guarantees. It is better suited as a secondary store for search and analytics, with a primary database as the source of truth.
Another common issue is shard overallocation. Creating an index with many small shards increases cluster overhead and can degrade performance. Conversely, very large shards can make recovery slow. Monitoring shard size and count is important.
Mapping explosions can occur when documents have many distinct fields, leading to excessive memory use. Defining explicit mappings and avoiding dynamic mapping for uncontrolled data helps prevent this.
Deep pagination is another pitfall: querying far into results (e.g., page 1000) is expensive because each shard must return a large number of hits. The search_after parameter or scroll API is preferred for deep pagination.
Elasticsearch vs. Relational Databases
Relational databases excel at transactions, joins, and strict schema enforcement. Elasticsearch excels at full-text search, relevance ranking, and aggregations over large datasets. They are often used together: a relational database stores the authoritative data, and Elasticsearch provides a searchable copy. Synchronization is typically handled by an application or a change data capture pipeline.
Elasticsearch also supports aggregations (similar to GROUP BY) and can perform analytics, but it is not a replacement for a data warehouse in all cases. Its strength is combining search with basic analytics in near real time.
Frequently Asked Questions
Is Elasticsearch a database?
Elasticsearch is a search and analytics engine that stores documents, but it is not a general-purpose database. It lacks ACID transactions and joins, and it is usually used alongside a primary database rather than as the system of record.
How does Elasticsearch achieve fast search?
It uses an inverted index, which maps terms to the documents containing them. This allows the engine to look up terms directly instead of scanning every document, making full-text queries very fast.
What is a shard in Elasticsearch?
A shard is a self-contained Lucene index that holds a subset of an index's documents. Shards enable horizontal scaling by distributing data and queries across multiple nodes.
Why is my newly indexed document not immediately searchable?
Elasticsearch refreshes indices periodically (every second by default) to make new documents visible. Until a refresh occurs, the document is not searchable. You can force a refresh, but doing so frequently can hurt performance.
Can Elasticsearch handle large datasets?
Yes, it scales horizontally by adding nodes and distributing shards. However, proper sizing, mapping, and query design are important to maintain performance as data grows.
What is the difference between a primary shard and a replica?
A primary shard is the original shard that handles indexing and search. A replica is a copy of a primary shard that provides redundancy and can serve read requests, improving search throughput and fault tolerance.