Core Architecture and Terminology

8 min read

Welcome to the foundation of Elasticsearch. Before you start firing off search queries to find the exact log that crashed your production server at 3:00 AM, you need to understand how Elasticsearch organizes its brain.

In this module, we will break down the physical and logical architecture of Elasticsearch. We will learn how it scales, how it stores data, and why it can return search results faster than you can blink.


1. Clusters and Nodes: The Brains of the Operation

Definition

A Node is a single running instance of Elasticsearch.
A Cluster is a collection of one or more connected nodes working together to store your data and process search requests.

The Problem

A single computer (server) has physical limits. It only has so much CPU, memory, and hard drive space. If your application grows and you need to store terabytes of data, a single server will run out of space. Furthermore, if that single server loses power or its hard drive dies, your search engine is entirely offline.

The Solution

Instead of buying one massive, extremely expensive supercomputer, Elasticsearch is designed to be distributed. You start multiple instances of Elasticsearch (nodes) across several smaller, cheaper machines. These nodes connect to form a single network (cluster). They share the data and the workload. If one node bursts into flames, the cluster reroutes the work to the surviving nodes without downtime.

Real-Life Scenario

Imagine you run a large warehouse.

  • The Cluster is the entire warehouse facility.
  • The Nodes are the individual warehouse workers.

If you have one worker (one node), they have to receive shipments, place them on shelves, and find items when customers order them. If they get overwhelmed or call in sick, the warehouse stops operating. By hiring 10 workers (a 10-node cluster), they divide the labor. They can process 10 times the orders, and if one worker goes on vacation, the other 9 seamlessly cover the shift.

Industry Practice

In industry, you rarely run a single-node cluster in production. A standard highly-available setup starts with at least three nodes.
Nodes can also be assigned specific "roles" so they don't have to do everything:

  • Master-eligible nodes: The managers. They don't process data; they just keep track of the cluster state (which nodes are alive, where data is stored).
  • Data nodes: The heavy lifters. They store the actual data and execute search queries.
  • Ingest nodes: The receptionists. They pre-process documents (like modifying or enriching data) before it is saved.

Hands-on Example

When you spin up Elasticsearch, you can check the health of your entire cluster using a simple HTTP GET request.

http
GET /_cluster/health

Response:

json
{
  "cluster_name": "production-logs-cluster",
  "status": "green",
  "number_of_nodes": 3,
  "number_of_data_nodes": 3,
  "active_primary_shards": 15,
  "active_shards": 30
}

Note: The status can be green (perfect), yellow (all data is safe, but some backups are missing), or red (data is missing/unavailable).


2. Indices and Documents: Organizing Your Data

Definition

A Document is a basic unit of information that can be indexed, represented as a JSON object.
An Index is a logical namespace (a collection) that groups multiple documents together based on their characteristics.

The Problem

If you throw millions of user profiles, server logs, and product listings into one giant, unorganized digital pile, querying it becomes an absolute nightmare. The system would have to figure out how to compare a "price" field from a product with an "error_code" field from a server log.

The Solution

Elasticsearch groups similar documents into an Index. By grouping documents with similar structures, Elasticsearch can optimize how it searches through them.

Real-Life Scenario

Think of an office filing system.

  • The Index is a specific filing cabinet drawer labeled "Invoices 2024".
  • The Document is a single piece of paper inside that drawer containing the actual invoice details.

If your boss asks for "Invoice #502", you don't search the drawer labeled "Employee Resumes." You go straight to the "Invoices" index.

Industry Practice

In the relational database world (like MySQL or PostgreSQL), an Index is roughly equivalent to a Database/Table, and a Document is a Row.

  • Standard Indices: Used for entities like users, products, or orders.
  • Rolling Indices / Data Streams: For time-series data (like server logs or metrics), the industry standard is to create a new index periodically (e.g., logs-2024.01, logs-2024.02). This prevents a single index from growing infinitely large and allows easy deletion of old data just by dropping the old index.

Hands-on Example

Let's add a document to an index called movies. If the index doesn't exist, Elasticsearch will automatically create it for you.

http
POST /movies/_doc/1
{
  "title": "The Matrix",
  "director": "Wachowskis",
  "year": 1999,
  "genre": ["Sci-Fi", "Action"]
}

The data payload is pure JSON. Elasticsearch will automatically inspect the data and assign types (e.g., recognizing that 1999 is a number).


3. Shards and Replicas: Scaling and Resilience

Definition

A Shard is a physical subdivision of an index. It is essentially a standalone, fully functional search engine (a Lucene index) in its own right.
A Replica is an exact copy of a primary shard.

The Problem

Imagine you have an index called global_transactions that holds 2 Terabytes of data.

  1. A single node in your cluster might only have a 1 Terabyte hard drive. It literally cannot hold the index.
  2. Even if it could hold it, a single CPU trying to search through 2 Terabytes of data will be painfully slow.
  3. If that node crashes, your global_transactions index is gone.

The Solution

Elasticsearch solves this by splitting the index into smaller pieces called Primary Shards. A 2TB index can be split into four 500GB shards, which are then distributed across four different nodes.
To solve the crashing problem, Elasticsearch creates Replica Shards. These are exact backup copies of the primary shards, but they are always stored on a different node than the primary.

Real-Life Scenario

Imagine you are writing a massive, 10,000-page encyclopedia.

  • Splitting it into Shards means binding it into 10 separate volumes (1,000 pages each). Now, 10 different readers can search through different volumes at the exact same time without waiting in line.
  • Creating Replicas means using a photocopy machine to print a backup set of all 10 volumes. If someone spills coffee on Volume 4, you just bring out the backup copy of Volume 4, and no knowledge is lost.

Industry Practice

  • Shard Sizing: In the industry, a golden rule is to keep the size of a single shard between 10GB and 50GB. If your shards are too small, the cluster wastes resources managing them. If they are too large, moving them around during node failures takes too long.
  • Modern Defaults: In older versions, Elasticsearch defaulted to 5 primary shards per index. In modern Elasticsearch (7.x and 8.x), the default is 1 primary shard and 1 replica. This is because many users were creating thousands of tiny indices, leading to "oversharding" which crashes the master node's memory.

Hands-on Example

When creating an index, you can define exactly how many shards and copies you want:

http
PUT /high_traffic_logs
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 2
  }
}

This creates 3 Primary Shards. Because number_of_replicas is 2, it creates 2 backups for EACH primary shard. Total shards = 3 Primary + 6 Replicas = 9 Shards.


4. Under the Hood: The Inverted Index Explained

Definition

An Inverted Index is a data structure that maps content (words or terms) to its physical locations (the documents that contain them).

The Problem

If you search for the word "error" in a standard text file or a relational database column, the computer has to start at the first row, scan every single word, and check if it matches "error". This is called a full-table scan. If you have billions of log lines, scanning every word could take minutes or hours.

The Solution

Elasticsearch is fundamentally built on top of Apache Lucene, which uses an Inverted Index. When you save a document, Elasticsearch doesn't just dump the text onto the hard drive. It breaks the text down into individual words (tokens), standardizes them (lowercasing, removing punctuation), and builds a dictionary mapping each word to the ID of the document it belongs to.

Real-Life Scenario

Think of the index at the back of a textbook.
If you want to read about "Photosynthesis", you don't start on Page 1 and read the entire book until you spot the word. You go to the back of the book, find the word "Photosynthesis" alphabetically, and it tells you: "Pages 42, 89, 115."

Industry Practice

The process of breaking text down into the inverted index is called Analysis. By default, Elasticsearch splits strings by whitespace and lowercases them.
This means if you index the sentence "The Quick Brown Fox!", the inverted index stores:

  • the -> Doc 1
  • quick -> Doc 1
  • brown -> Doc 1
  • fox -> Doc 1

When a user searches for "FOX", Elasticsearch lowercases the search query to "fox", instantly looks it up in the dictionary, and immediately knows Doc 1 is the answer without ever scanning the actual document. This "write-heavy, read-light" approach is exactly why Elasticsearch can search millions of records in milliseconds.

Hands-on Example

You can actually ask Elasticsearch how it will parse your text into an inverted index using the _analyze API.

http
POST /_analyze
{
  "analyzer": "standard",
  "text": "System CRASHED at 3:00 AM!"
}

Response snippet (Simplified):

json
{
  "tokens": [
    { "token": "system" },
    { "token": "crashed" },
    { "token": "at" },
    { "token": "3" },
    { "token": "00" },
    { "token": "am" }
  ]
}

Notice how it removed the punctuation (: and !) and lowercased "CRASHED"? This is the magic that populates the inverted index.


References and Extra Reading 📚

Challenge

You are a DevOps engineer responsible for managing a high-traffic logging system. Your task is to create the complete API request to provision a new Elasticsearch index named app_logs_v1.

Requirements:

  1. Index Settings:

    • The index must be configured to survive the failure of a single data node without data loss or downtime.
    • Define a custom text analyzer named log_message_analyzer. This analyzer should use the standard tokenizer and apply a lowercase token filter.
  2. Document Mapping:

    • The index will store documents with the following fields and data types:
      • @timestamp: A date field for when the event occurred.
      • log_level: A non-analyzed string suitable for exact-match filtering and aggregations (e.g., "INFO", "ERROR").
      • service_name: A non-analyzed string for the application service name.
      • message: A full-text searchable field. This field must use the log_message_analyzer you defined in the settings.

Write the single, complete PUT request, including the endpoint and the JSON body, to create this index with the specified settings and mappings.

Expected result

Your solution should be a single PUT request. The request body must be a valid JSON object containing top-level settings and mappings keys.

  • The settings object must specify the number_of_replicas to ensure data is safe if one node fails. It must also contain an analysis block defining the log_message_analyzer with a standard tokenizer and a lowercase filter.
  • The mappings object must define the properties for the @timestamp, log_level, service_name, and message fields.
  • The field types must be appropriate: date for the timestamp, keyword for log_level and service_name, and text for message.
  • The message field mapping must explicitly assign the custom log_message_analyzer to be used for analysis.
json

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.