Handling Relationships in Elasticsearch

8 min read

Imagine you are running a pizza shop (the server). You have customers (requests) coming in constantly. If you, the chef, forget where you put the cheese every time a new customer walks in, you are going to have a bad time. You need a way to remember things—ingredients, recipes, and the cash register—while handling hundreds of orders at once.

In the database world, remembering how an order relates to a customer, or how a pizza relates to its toppings, is called handling relationships. If you are coming from a traditional database background, you might be used to neatly tying these things together with foreign keys. But in Elasticsearch, the rules of the kitchen are completely different.

Let's explore how to handle relationships in Elasticsearch progressively, focusing on what you will actually use in real-world industry applications.


1. The Challenge of Relational Data in a NoSQL World 🗄️

The Definition

A Relational Database (like PostgreSQL or MySQL) stores data in separate, normalized tables to avoid duplicating information. A NoSQL Database like Elasticsearch stores data as independent, flat JSON documents.

The Problem

Relational databases use operations called JOINs to stitch data together at query time. For example, joining a Customers table with an Orders table.

Elasticsearch is built on top of Apache Lucene, a full-text search engine library. Lucene is designed for one thing: blistering fast search speeds. It achieves this speed by keeping data as flat as possible. Elasticsearch does not support traditional SQL-style JOIN operations.

If you try to mimic relational joins in Elasticsearch by constantly cross-referencing different documents during a search query, your search performance will plummet. In the industry, Elasticsearch is utilized for read-heavy operations, meaning we gladly sacrifice storage space (by duplicating data) to guarantee millisecond response times.

To solve relationship mapping without traditional JOINs, Elasticsearch provides specific data structures and indexing strategies.


2. Using Arrays of Objects and Their Limitations ⚠️

The Concept

An Array of Objects is a standard JSON structure where a single field contains a list of complex objects. In Elasticsearch, any field can contain multiple values by default, so passing an array of JSON objects into a document feels completely natural.

Let's look at a pizza shop order containing an array of pizza objects:

json
PUT /orders/_doc/1
{
  "customer_name": "Alice",
  "pizzas": [
    {
      "type": "Margherita",
      "size": "Large"
    },
    {
      "type": "Pepperoni",
      "size": "Small"
    }
  ]
}

The Problem: The Flattening Steamroller

When you send this document to Elasticsearch, Lucene has no concept of inner objects. To index this data, Elasticsearch acts like a steamroller and flattens your complex hierarchy into simple key-value pairs.

Under the hood, Elasticsearch translates your document into this:

json
{
  "customer_name": "Alice",
  "pizzas.type": ["Margherita", "Pepperoni"],
  "pizzas.size": ["Large", "Small"]
}

The Limitation

Because the data is flattened into separate arrays, the relationship between the properties of each object is permanently lost.

Imagine a customer complains and asks, "Did Alice order a Small Margherita?"

If you write a query searching for pizzas.type: "Margherita" AND pizzas.size: "Small", Elasticsearch will return a match.
Why? Because "Margherita" exists in the pizzas.type array, and "Small" exists in the pizzas.size array. Elasticsearch doesn't know that the "Small" belonged to the Pepperoni pizza.

This is a critical bug in production systems. To safely query relationships within arrays of objects, we need a specialized tool.


3. The Nested Data Type: Querying Complex Objects Safely 📦

The Definition

The nested data type is a specialized version of the standard object data type. It allows arrays of objects to be indexed in a way that ensures each object can be queried completely independently of the others.

How it Solves the Problem

When you map a field as nested, Elasticsearch stops flattening the array into a single massive list of values. Instead, it takes each object inside the array and indexes it as a completely separate, hidden document under the hood. It then tightly binds these hidden documents to the main parent document.

Because they are indexed as separate documents, the relationships between the inner fields (e.g., "Size" and "Type") remain perfectly intact.

Hands-on Setup

To use nested objects, you must explicitly define the mapping before you index the data. If you rely on dynamic mapping, Elasticsearch will default to a standard array of objects and flatten everything.

Step 1: Create the Mapping

json
PUT /orders
{
  "mappings": {
    "properties": {
      "customer_name": { "type": "keyword" },
      "pizzas": {
        "type": "nested", 
        "properties": {
          "type": { "type": "keyword" },
          "size": { "type": "keyword" }
        }
      }
    }
  }
}

Step 2: Querying Nested Data
Because the nested objects are technically separate hidden documents, standard queries will not work on them. You must wrap your query in a nested query block.

To correctly check if Alice ordered a "Small Margherita":

json
GET /orders/_search
{
  "query": {
    "nested": {
      "path": "pizzas",
      "query": {
        "bool": {
          "must": [
            { "match": { "pizzas.type": "Margherita" } },
            { "match": { "pizzas.size": "Small" } }
          ]
        }
      }
    }
  }
}

Result: No match. The system correctly identifies that Alice did not order a Small Margherita.

Industry Standards & Performance Considerations

Nested documents are incredibly useful, but they come with a heavy cost.

  • The Multiplier Effect: If you index 1 document with an array of 100 nested objects, Elasticsearch actually creates 101 documents behind the scenes.
  • Limits: Because of the performance tax on memory and indexing speed, Elasticsearch enforces strict limits. By default, index.mapping.nested_objects.limit caps the number of nested objects per document to 10,000.
  • When to use: Use nested when you strictly need to query multiple fields within an array element simultaneously (like finding an exact product in an order log). Do not use it for simple lists of tags or strings.

4. Application-side Joins and Denormalization Strategies 🚀

In a high-traffic production environment, even nested queries can become too slow if abused. So, how do industry giants handle millions of relationships efficiently? They stop relying on the database to do the heavy lifting.

Strategy 1: Denormalization (The Industry Standard)

Definition: Denormalization is the process of intentionally duplicating data across multiple documents to avoid the need for relationship queries entirely.

How it works:
Instead of maintaining a User index and an Order index, you inject the user's details directly into every single order they make.

json
{
  "order_id": "9941",
  "total_price": 24.99,
  "user": {
    "user_id": "U-123",
    "name": "Alice",
    "country": "Nepal",
    "loyalty_tier": "Gold"
  }
}

Why this is great: If you need to find "All orders over $20 made by Gold tier users in Nepal", Elasticsearch scans a single flat index. It returns results in microseconds. Storage is cheap; CPU time is expensive. Flattening out data like this is the most common and performant pattern in Elasticsearch.

The Trade-off: If Alice changes her name, you have to run an _update_by_query operation to update her name across all her past order documents.

Strategy 2: Application-Side Joins

Definition: An application-side join means performing multiple, sequential database queries within your backend application code (Node.js, Python, Java, etc.) to manually stitch data together.

How it works:
If denormalization is too punishing (e.g., the user data changes constantly and updating millions of orders takes too long), you manage the relationship in your backend server.

  1. Query 1: The application asks Elasticsearch, "Get me the ID for the user named Alice." -> Returns ID U-123.
  2. Query 2: The application asks Elasticsearch, "Get me all orders where user_id is U-123."

Why this is used: It keeps documents clean and small. Doing two extremely fast flat queries is often faster than doing one complex nested query or maintaining aggressively denormalized data that updates every few seconds.

What about the Elasticsearch join data type?
You might see the join data type in the Elasticsearch documentation. It creates a parent-child relationship between documents. However, it is widely avoided in the industry for heavy search workloads. Parent-child queries can be hundreds of times slower than standard queries because they force Elasticsearch to do complex routing and memory mapping. Stick to Denormalization, Application-side joins, or nested arrays.


Summary

Handling relationships in Elasticsearch requires a shift in mindset from traditional relational databases:

  1. Arrays of Objects flatten data. They are fine for display purposes but terrible if you need to query relationships within the arrays.
  2. Nested Types index array items as hidden documents, allowing safe querying. Use them when array boundaries matter, but be mindful of the 10,000 object limit.
  3. Denormalization is the king of Elasticsearch performance. Duplicate your data to keep it flat, fast, and highly searchable.
  4. Application-side Joins are your fallback when data changes too frequently to reasonably duplicate.

Welcome to the world of NoSQL, where storage is cheap, joins are forbidden, and speed is everything! 🏎️💨


Extra Reading & References 📚

Challenge

You are working with an Elasticsearch index named orders. Each document in this index represents a pizza order and contains a field called pizzas. The pizzas field has been mapped with the nested data type to preserve the relationships within each pizza object in its array. Each object in the pizzas array has two properties: type (e.g., "Pepperoni") and size (e.g., "Large").

Your task is to construct a complete Elasticsearch _search query. This query must find all order documents that contain at least one pizza that is both of type "Margherita" and of size "Small". Your query must correctly ensure that these two conditions apply to the same single pizza object within the pizzas array.

Expected result

Your answer should be a valid JSON object representing the body of an Elasticsearch _search request. The core of the solution is a nested query targeting the path named pizzas. Inside this nested query, you must use a bool query with a must clause containing two match queries. One match query will target the pizzas.type field for "Margherita", and the other will target the pizzas.size field for "Small", ensuring both conditions are met on the same nested document.

json

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.