Mapping and Data Modeling

7 min read

Imagine you are managing a massive international library. Thousands of books, magazines, and historical scrolls arrive every day. If you just dump them into a giant pile in the middle of the room, finding a specific recipe for apple pie from a 1990s magazine will take you years. You need a cataloging system. You need to know if a piece of text is a title, a date of publication, or an author's name.

In Elasticsearch, this cataloging system is called Mapping.

Problem: When you send JSON documents to Elasticsearch, it needs to know how to store and index that data to make it searchable. Should "2023-10-01" be treated as text, or as a date allowing for range searches?
Solution: Mapping. It is the schema definition that tells Elasticsearch exactly what kind of data each field contains and how it should be indexed.

Let's break down how Elasticsearch handles your data, how you can take control, and the industry standards for modeling.


1. Schema on Write: Understanding Dynamic Mapping 🚦

Problem: Setting up a rigid database schema before you even know what your data looks like slows down development. You just want to throw data at a database and see it work immediately.

Definition: Dynamic mapping is a feature where Elasticsearch automatically detects and assigns data types to new fields when it encounters them for the first time in a document.

How it solves the problem: You do not need to define an index or a mapping beforehand. You just send a JSON document, and Elasticsearch figures it out on the fly.

How it flows

Imagine an automated sorting machine at a post office. A package comes down the belt. The machine weighs it, scans its shape, and says, "This is a heavy rectangle; it must be a book." That is dynamic mapping. Elasticsearch looks at the JSON value:

  • If it sees "age": 25, it assigns the long (number) type.
  • If it sees "is_active": true, it assigns the boolean type.
  • If it sees "name": "John", it assigns it as a string.

The Catch (And why industry avoids it in production)

While amazing for local prototyping, dynamic mapping in production is a trap. If Elasticsearch sees a string like "name": "John", it doesn't know if you want to perform full-text searches on it or exact-match filtering.

To be safe, dynamic mapping defaults to mapping strings as both:

json
{
  "name": {
    "type": "text",
    "fields": {
      "keyword": {
        "type": "keyword",
        "ignore_above": 256
      }
    }
  }
}

Industry Reality: Doing this for every string wastes massive amounts of disk space and memory. If you let Elasticsearch guess your types in a heavy production environment, your cluster will eventually consume all your RAM, scream for mercy, and send a strongly worded error log to your monitoring dashboard.


2. Taking Control: Defining Explicit Mappings 🛠️

Problem: Dynamic mapping wastes resources by indexing data in ways you don't need, and it might guess wrong (e.g., mapping a tracking number like "8475938" as a number, when you actually just need it as a string).

Definition: Explicit mapping is the process of manually defining the fields and their exact data types for an index before any documents are ingested.

How it solves the problem: It gives you total control. You tell Elasticsearch exactly how to store the data, preventing wasted space and ensuring your search queries behave exactly as expected.

How to do it

You create an index and define the mappings block:

json
PUT /company-employees
{
  "mappings": {
    "properties": {
      "employee_id": { "type": "keyword" },
      "full_name": { "type": "text" },
      "age": { "type": "integer" },
      "hire_date": { "type": "date" }
    }
  }
}

Under the Hood: The Immutable Rule

Once a field is mapped, you cannot change its data type. Why? Because under the hood, Elasticsearch relies on Apache Lucene, which writes data into immutable segments. Changing a field type from integer to text would invalidate all the highly optimized data structures already written to disk.

If you make a mistake and need to change a type, you cannot just update the mapping. You must create a brand new index with the correct mapping and migrate (reindex) your data.


3. Core Data Types: Text, Keyword, Dates, and Numbers 🧱

To build a good schema, you need to understand the fundamental data types. We will only focus on the ones used in 99% of daily engineering tasks.

Text vs. Keyword (The most important distinction in Elasticsearch)

Problem: Sometimes you want to search for the word "apple" inside a 500-word product review. Other times, you want to filter an exact status like "ORDER_SHIPPED".

1. Text Type

  • Definition: Used for full-text search.
  • How it works: When you save a text field, the string passes through an analyzer. It breaks the sentence "The Quick Brown Fox!" into individual, lowercase words (tokens): [the, quick, brown, fox].
  • Use case: Product descriptions, emails, blog contents.

2. Keyword Type

  • Definition: Used for exact matches, sorting, and aggregations.
  • How it works: It stores the string exactly as it is. "The Quick Brown Fox!" is stored as a single literal block: ["The Quick Brown Fox!"].
  • Use case: Email addresses, tags, status codes, zip codes.

Dates 📅

  • Definition: A data type that handles temporal data.
  • How it works: JSON doesn't have a date type, so dates are sent as strings ("2023-10-01T12:00:00Z"). Elasticsearch parses these strings based on a format and stores them under the hood as long integers representing milliseconds since the Unix epoch.
  • Industry standard: Always use the standard ISO 8601 format (like the example above). It saves you from writing custom date parsers.

Numbers 🔢

  • Types: integer, long, float, double.
  • Rule of thumb: Choose the smallest type that fits your data. Don't use a double (floating point) if an integer will do. Lucene optimizes storage based on these types.

4. Advanced Types: Dealing with Arrays and Objects 🪆

Problem: Databases like MySQL are flat tables. JSON data is hierarchical. You have lists of things, and objects inside of objects. How does a flat search engine handle this?

Arrays (The Phantom Type)

Here is a fun fact: Elasticsearch does not have an array data type.

Definition: Any field in Elasticsearch can hold zero, one, or multiple values out of the box, as long as all values are of the same data type.

You don't need to tell the mapping it's an array. If you mapped "tags": { "type": "keyword" }, you can send:

json
{ "tags": "urgent" } 

OR

json
{ "tags": ["urgent", "server", "outage"] }

Elasticsearch just treats it as multiple keywords.

Objects (The Default Hierarchy)

Definition: JSON objects that contain inner fields. Mapped as object.

How it works under the hood: Lucene doesn't understand JSON objects. Elasticsearch flattens them using dot notation.
If you send:

json
{
  "manager": {
    "first": "Alice",
    "last": "Smith"
  }
}

Elasticsearch internally stores it as:

text
manager.first: ["Alice"]
manager.last:  ["Smith"]

The Array of Objects Trap (Why nested exists)

Problem: What happens if you have an array of objects?

json
{
  "employees": [
    { "first": "John", "last": "Smith" },
    { "first": "Alice", "last": "White" }
  ]
}

Because of the flattening behavior, Elasticsearch stores this as:

text
employees.first: ["John", "Alice"]
employees.last:  ["Smith", "White"]

The relationship between "John" and "Smith" is completely lost! If you search for an employee named "John White", Elasticsearch will return this document because it sees "John" in the first names array and "White" in the last names array.

Solution: The nested data type.
Definition: A specialized version of the object data type that allows arrays of objects to be queried independently.
How it works: Under the hood, Elasticsearch secretly stores each object in the array as a separate, hidden Lucene document, preserving the relationship between the fields.

Industry standard: Use nested fields only when absolutely necessary. Because they create hidden documents, indexing and querying nested data is computationally expensive. If an array has 100 objects, updating that document actually updates 101 documents under the hood.


📚 References for Extra Reading

To keep your knowledge sharp and strictly aligned with the latest architecture, check out the official documentation:

Challenge

You are tasked with designing the Elasticsearch mapping for a new index called corporate_events. Your goal is to create an optimized and explicit mapping that avoids the performance pitfalls of dynamic mapping and ensures accurate search capabilities for the data structure below.

Sample Document:

json
{
  "event_id": "CONF-2024-Q4-TECH",
  "event_name": "Annual Tech Innovators Summit 2024",
  "event_summary": "A deep dive into the future of cloud computing and decentralized applications.",
  "start_datetime": "2024-10-26T09:00:00Z",
  "is_public": true,
  "capacity": 5000,
  "venue": {
    "name": "Metro Convention Center",
    "address": "123 Tech Avenue, Silicon Valley, CA 94000",
    "geo_location": { 
      "lat": 37.3861,
      "lon": -122.0839
    }
  },
  "tags": ["cloud", "blockchain", "AI", "innovation"],
  "attendees": [
    {
      "full_name": "Dr. Evelyn Reed",
      "company": "NextGen Solutions"
    },
    {
      "full_name": "Marcus Chen",
      "company": "QuantumLeap Inc."
    }
  ]
}

Your Task:
Create a complete JSON mapping definition that satisfies the following requirements:

  • event_id: Must be treated as a single, un-analyzed token for exact matching and aggregations.
  • event_name & event_summary: Must be optimized for full-text search.
  • start_datetime: Must be indexed as a date.
  • capacity: Should be mapped using an efficient integer type.
  • venue.name: Must support both full-text search and exact-match sorting/aggregation.
  • venue.address: Only needs to support full-text search.
  • venue.geo_location: Must be mapped as a geographical point.
  • tags: This field is an array of strings that should be indexed for exact-match filtering.
  • attendees: This is an array of objects. The relationship between full_name and company within each object must be preserved to prevent incorrect search results. For instance, a search for a person named "Marcus Reed" should not match this document.

Expected result

Your solution should be a single, valid JSON object representing the complete Elasticsearch mapping.

The mapping should correctly define the type for each field according to the requirements:

  • event_id, tags, and attendees.company should be keyword.
  • event_name, event_summary, venue.address, and attendees.full_name should be text.
  • start_datetime should be date.
  • is_public should be boolean.
  • capacity should be integer.
  • venue.name should be a multi-field with a text type for searching and a keyword sub-field (e.g., named raw) for sorting/aggregation.
  • venue.geo_location should be geo_point.
  • The attendees field must be mapped with the nested type to correctly handle the array of objects and preserve their internal relationships.
json

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.