What Is a Runtime Field in Elasticsearch?
A complete, no-prior-knowledge walkthrough of how Elasticsearch lets you define new fields at query time instead of indexing time — what they are, how they work internally, when to use them, and when to avoid them.
Imagine you rent a storage unit and, on moving day, you box up everything and label each box clearly — “kitchen,” “books,” “winter clothes.” That’s how a normal Elasticsearch field works: you decide the label (the field) before you put anything away, and it’s fixed on the box forever. Now imagine instead that you keep everything in unlabeled boxes, and whenever you need something, you open the boxes on the spot and figure out what’s inside, on demand, using whatever rule you like that day. That second approach — deciding what a “field” means only at the moment you ask for it, rather than when you stored the data — is the idea behind a runtime field in Elasticsearch. This post walks through exactly how that idea works, why Elastic built it, and how to use it responsibly.
1Core Concepts — What Exactly Is a Runtime Field?
Before we can talk about how runtime fields work, we need to agree on what a “field” is in Elasticsearch at all, and what makes the runtime kind different.
What Elasticsearch Normally Does With a Field
Elasticsearch stores information as JSON documents inside an index, which you can think of as a giant, searchable filing cabinet. Every document has fields — a name, a price, a timestamp, and so on. Normally, when you add a document, Elasticsearch immediately looks at each field, decides how to store it efficiently, and writes that decision down permanently in something called the mapping. From that point forward, that field is “baked in.” If you later realize you needed the price stored differently, or you want a brand-new field that combines two existing ones, you traditionally had only one real option: reprocess and reindex all your data from scratch, which for large datasets can take hours or days.
Think of a traditional Elasticsearch field like a printed label on a spice jar. Once you print “Cumin” on the label and glue it on, that jar is permanently the cumin jar. If you decide next month you’d rather group it under “Warm Spices” instead, you can’t just relabel one jar — you have to reprint and reglue every single jar in your kitchen. A runtime field is like a sticky note you attach to the shelf itself, computed fresh every time someone opens the cupboard, based on rules you can change any time you like — no reprinting required.
The Official Definition
A runtime field is a field that is evaluated at query time rather than at indexing time. Instead of being computed once when a document is written and stored on disk, its value is calculated on the fly, using a script, whenever a search, aggregation, or filter actually needs it. Elasticsearch does not store the resulting value anywhere; it recalculates it fresh for every query that touches it.
Why “Runtime” Is the Right Word
The word “runtime” refers to the period while a program is actually running, as opposed to when it was written or compiled. In this context, it means the field only comes into existence in the runtime of a query — the brief window while Elasticsearch is actively processing your search request. Before that moment, and after it, the field has no stored representation anywhere in the index.
Computed once, stored forever
Value is calculated when the document is indexed and written to disk in a data structure optimized for fast search.
Computed fresh, every query
Value is calculated on demand using a script, using the raw source data as its input, and then thrown away.
The recipe, not the ingredient
A small piece of logic, written in Elasticsearch’s Painless language, that tells the runtime field how to derive its value.
The raw document
The original JSON you sent in, kept alongside the index; runtime field scripts usually read from here.
A Concrete Mental Picture
Suppose every document in your index has a field called full_name, storing something like “Amit Verma.” You never anticipated needing to search only by first name. With a runtime field, you can define a field called first_name whose rule is simply “take everything in full_name before the first space.” The moment you define that rule, you can search, sort, or aggregate by first_name as if it had always existed — even though, physically, nothing was ever written to disk for it. Delete millions of documents, add a hundred more tomorrow, and the rule still applies automatically to every one of them, old and new, without ever touching the index again.
A runtime field is not a new kind of storage. It is a rule that Elasticsearch remembers and re-applies, every single time, to data that is already sitting in your index.
2Architecture and Components
Runtime fields don’t float around on their own — they slot into specific places inside Elasticsearch’s existing architecture. Let’s look at where.
Where Runtime Fields Live
Every Elasticsearch index has a mapping, which is essentially a schema describing every field’s name and data type. Runtime fields live inside this same mapping, in a dedicated section usually named runtime. This is important: they are declared alongside your ordinary indexed fields, and from a search request’s point of view, they look and behave almost identically to a “real” field. The difference is invisible to the person writing the search — it only matters to Elasticsearch internally, when it decides how to fetch the value.
The Mapping’s Runtime Section
A named list of runtime field definitions attached to the index, each with a declared type and a script.
The Painless Script Engine
Elasticsearch’s built-in, sandboxed scripting language used to write the logic behind each runtime field.
The Search Execution Layer
The part of Elasticsearch that plans and executes queries, deciding when a runtime field’s script must run.
Doc Values & _source
The stored data a runtime field script reads from — typically the original document contents.
Two Ways to Declare a Runtime Field
There are two places you can define a runtime field, and this choice matters for how flexible and how fast it is.
Defined in the Index Mapping
The runtime field is declared once, permanently, as part of the index’s schema. Every query against that index can use it without redefining it. This is the right choice for a field you expect to reuse constantly, such as a normalized version of a category name.
Defined Inside a Single Search Request
The runtime field exists only for the duration of one specific query, declared directly in the request body. It disappears the moment that request finishes. This is perfect for one-off, exploratory analysis — for example, a data analyst trying out a new way of bucketing values before deciding whether it’s worth making permanent.
How Runtime Fields Fit Beside Normal Fields
An index can freely mix indexed fields and runtime fields. In fact, a very common pattern is a “shadow” runtime field that has the same name conceptually as an indexed field but recalculates it differently — for instance, an indexed field storing a raw string price like “$45.00”, paired with a runtime field that strips the currency symbol and returns it as a proper decimal number for math and sorting.
| Aspect | Indexed Field | Runtime Field |
|---|---|---|
| When value is computed | At index time (once) | At query time (every time) |
| Where it’s stored | On disk, in the index | Nowhere — computed and discarded |
| Disk space used | Yes, proportional to data volume | Essentially none |
| Changing its logic | Requires reindexing all data | Instant — just edit the script |
| Query speed | Very fast (pre-computed) | Slower (computed on demand) |
Runtime fields are not a replacement for indexed fields across the board. They are a deliberate trade of some query speed in exchange for total schema flexibility. Both kinds of fields are meant to coexist.
3Internal Working — What Happens Under the Hood
This is the heart of the topic: how does Elasticsearch actually turn a script into a usable field, on demand, for potentially millions of documents?
The Role of Painless
Painless is a scripting language that Elastic built specifically for Elasticsearch. It looks similar to Java in its syntax, but it is deliberately restricted and sandboxed — it cannot read files, open network connections, or do anything that could destabilize the cluster. When you define a runtime field, you write a small Painless script that describes how to compute the value, using a special object called emit to hand the result back to Elasticsearch.
Think of Painless as a translator standing at the door of a library archive. You can’t wander into the archive and touch the original documents yourself — you hand the translator a short instruction (“tell me the year from this document’s date stamp”), and the translator goes in, reads the original, and hands you back exactly the answer you asked for, nothing more.
Step by Step: What Happens When a Query Touches a Runtime Field
Query arrives
A search, filter, sort, or aggregation request references the runtime field by name, exactly like it would reference any ordinary field.
Mapping lookup
Elasticsearch checks the index mapping, notices this field name is registered under “runtime” rather than as a normal field, and retrieves its script and declared type.
Candidate documents identified
Elasticsearch first narrows down which documents are even relevant, using any indexed fields in the query, to avoid running the script needlessly on documents that will be excluded anyway.
Script execution per document
For each remaining candidate document, the Painless script runs, typically reading from the stored _source or from doc values, and calls emit() with the computed result.
Result used in place
The emitted value is used immediately for whatever the query needed — comparing against a filter, sorting a result set, or being bucketed inside an aggregation.
Value discarded
Once the response is built and sent back, the computed value is not kept anywhere. The next query starts this entire process over from scratch.
flowchart TD
A[Search request references runtime field] --> B{Mapping lookup}
B --> C[Runtime field script found]
C --> D[Narrow candidate documents using indexed fields]
D --> E[For each candidate document]
E --> F[Run Painless script against _source / doc values]
F --> G[emit computed value]
G --> H[Use value in filter, sort, or aggregation]
H --> I[Return response]
I --> J[Computed value discarded]
Reading From Doc Values Instead of _source
By default, runtime field scripts commonly read from doc values — a special columnar, on-disk data structure Elasticsearch already builds for sorting and aggregations — rather than parsing the full JSON _source every time. Reading from doc values is considerably faster than re-parsing JSON text, because doc values are already stored in a compact, typed, ready-to-use format. This detail matters a lot for performance, which we’ll return to later.
A runtime field can also be layered on top of another runtime field, chaining logic — though each extra layer adds more computation per query, so this should be done sparingly.
4Data Flow and Lifecycle
Zooming out from a single query, let’s trace how a runtime field’s role changes across the entire lifetime of a piece of data, from the moment it’s created to the moment it’s searched.
The Journey of an Indexed Field
A traditional indexed field’s journey is short and final. A document arrives, Elasticsearch’s analysis and mapping logic processes each field once, and the resulting representation is written permanently into segments on disk. From that instant onward, every future query simply reads the already-computed result. The computation happens exactly once per document, no matter how many times it’s later searched.
The Journey of a Runtime Field
A runtime field’s journey looks completely different, because it has no “birth” tied to document indexing at all. Its only real event happens later and repeatedly: every time a query needs it, the script runs again, against whatever data currently exists for that document. If you update the document tomorrow, the runtime field automatically reflects the new value the very next time it’s queried — with zero extra indexing work.
sequenceDiagram
participant U as User/App
participant ES as Elasticsearch
participant IDX as Index (disk)
U->>ES: Index a document
ES->>IDX: Write indexed fields (computed once, stored)
Note over IDX: Runtime field NOT computed here
U->>ES: Search request using a runtime field
ES->>IDX: Read _source / doc values for candidates
ES->>ES: Run Painless script, emit() value
ES-->>U: Return results using freshly computed value
Note over ES: Computed value is discarded after response
What Happens When You “Promote” a Runtime Field
A very common real-world pattern is to start a field’s life as a runtime field, and only later, once you’re confident the logic is correct and it’s being queried heavily, convert it into a genuine indexed field through reindexing. This gives teams a safe way to experiment with new derived fields without committing to a slow, disk-hungry reindex until the value has been proven.
Lifecycle Across Schema Changes
Because a runtime field’s definition lives in the mapping but not in the stored document data, changing its script is as simple as updating the mapping — there is no reindexing step at all. This is one of the single biggest lifecycle advantages: a mistake in the logic, or a new business requirement, can be fixed in seconds rather than by rewriting an entire index.
5Advantages, Disadvantages, and Trade-offs
Nothing in engineering is free. Runtime fields trade one resource for another, and knowing exactly what you’re trading is essential to using them well.
Advantages
- No reindexing needed to add or change a field’s logic
- Zero additional disk space consumed by the field itself
- Safe way to experiment with new fields before committing to them
- Can apply retroactively to data that already exists, including historical records
- Great for exploratory analysis and one-off investigative queries
- Keeps mappings flexible in environments where the schema evolves quickly
Disadvantages / Trade-offs
- Slower per-query performance, since computation happens every single time
- Cost scales with the number of matching documents in a query
- Not ideal for fields queried extremely frequently at large scale
- Debugging script errors can be less obvious than debugging static data
- Some advanced query features work better, or only, on indexed fields
The Core Trade-off, in Plain Terms
Indexed fields spend disk space and indexing time up front so that every future query is as fast as possible. Runtime fields spend nothing up front and instead pay a small computational cost on every query. If a field is searched rarely, or its logic changes often, runtime is usually the smarter trade. If a field is searched constantly by thousands of users a second, paying the indexing cost once is usually the smarter trade.
It’s the difference between pre-cooking a large batch of meals and freezing them, versus cooking fresh every single time someone is hungry. Pre-cooking takes real freezer space and upfront effort, but each meal is ready instantly later. Cooking fresh needs no freezer space at all, but every single meal costs you active time in the kitchen.
The performance cost of a runtime field is not fixed — it grows with how many documents the query has to evaluate the script against. A runtime field used inside a tightly filtered query is cheap; the same field used across an entire, unfiltered multi-million document index can be very expensive.
6Security Considerations
Because runtime fields involve running scripts, it’s natural to ask whether they open any security risks — and Elasticsearch has specific protections built in for exactly this reason.
Sandboxing Through Painless
Painless was designed from the start to be a safe scripting language for a multi-tenant search engine. It has no access to the file system, no network access, no ability to spawn processes, and no reflection tricks that could reach outside its sandbox. This means a runtime field script, even a poorly written one, cannot be used to read arbitrary files on the server or reach out to other systems.
No File or Network Access
Scripts cannot read local files or make outbound network calls from within the cluster.
Resource Circuit Breakers
Elasticsearch tracks memory and computation used by scripts and can halt a query that consumes too much.
Role-Based Access Control
Standard Elasticsearch security features still apply — who can define or query a runtime field is governed by the same permission system as everything else.
No Persistent Side Effects
A runtime field script can only compute and emit a value; it cannot write back into the index or alter other documents.
Denial-of-Service Style Risks
The realistic security concern with runtime fields is less about data theft and more about resource exhaustion. Because a script runs per document, a poorly written or maliciously crafted runtime field query — especially one with an expensive script and a weak filter — could consume significant CPU across a cluster. This is why Elasticsearch enforces script complexity and execution limits, and why access to define arbitrary runtime fields, particularly ad-hoc ones inside search requests, should be restricted to trusted users or applications.
In a multi-tenant system where end users can send raw queries, avoid exposing the ability to define arbitrary runtime fields directly. Instead, predefine a safe, reviewed set of runtime fields in the mapping and let user queries reference them by name only.
Sensitive Data Exposure
Because runtime field scripts typically read from _source, they can technically access any field in the original document, including ones that may be intended to stay hidden from search results. Field-level security controls should be reviewed carefully, since a cleverly written runtime field could otherwise expose data that a role is supposed to be restricted from seeing.
7Monitoring, Logging, and Metrics
Since runtime fields shift cost from indexing time to query time, keeping an eye on that cost becomes an ongoing operational responsibility rather than a one-time concern.
What to Watch
Script Execution Time
How long, on average and at the tail end, runtime field scripts take to execute per query.
Query Latency
Overall response time for queries that touch runtime fields, compared against equivalent indexed-field queries.
CPU Utilization
Node-level CPU usage, watched for spikes correlated with heavy runtime field usage.
Circuit Breaker Trips
How often queries are rejected or halted for exceeding memory or computation limits.
Using the Profile API
Elasticsearch offers a built-in profiling capability that breaks down exactly how much time each part of a query took, including time spent inside runtime field scripts specifically. This is the most direct way to confirm whether a slow query is actually being caused by a runtime field, rather than guessing.
Logging Practices
It’s good practice to log slow queries — queries that exceed some acceptable time threshold — with enough detail to see which fields, including runtime fields, were involved. Over time, this log becomes a valuable dataset for deciding which runtime fields are hot enough to be worth promoting into real indexed fields.
Baseline
Measure typical query latency before introducing a new runtime field, so you have something to compare against.
Introduce and Watch
Roll the runtime field out and monitor latency, CPU, and circuit breaker metrics closely for the first period of real traffic.
Decide
If usage and cost both stay high, consider promoting the field to a real indexed field via reindexing.
Treat a runtime field’s ongoing cost the same way you’d treat a slow database query in production — something to be periodically reviewed, not something you set and forget.
8Design Patterns and Anti-Patterns
Over time, the Elasticsearch community has settled on a handful of patterns that work well with runtime fields, and a handful of traps that are easy to fall into.
Good Patterns
The “Explore First” Pattern
Use a runtime field to test a new derived value against real production data before deciding whether it’s worth the cost of reindexing it as a permanent field.
The “Backfill Bridge” Pattern
When you change how a value should be interpreted going forward, use a runtime field to apply the new interpretation uniformly across both old and new documents, without having to touch historical data at all.
The “Schema-on-Read” Pattern
In environments ingesting loosely structured or highly variable data, define runtime fields that normalize inconsistent source data into a consistent shape only when it’s actually queried.
Anti-Patterns to Avoid
Problem
Using a runtime field as the primary sort or filter field on a very large, unfiltered index that is queried extremely frequently.
Why It’s Harmful
Every query re-runs the script across a huge number of documents, causing latency and CPU cost to climb steadily as data volume grows, with no upper bound.
Correct Approach
Promote the field to a genuine indexed field once its logic is finalized and it is proven to be heavily used.
Problem
Chaining many layers of runtime fields, where one runtime field’s script depends on another runtime field’s output.
Why It’s Harmful
Each layer multiplies the computation happening per document per query, and makes debugging significantly harder because errors can originate several layers deep.
Correct Approach
Keep runtime field logic flat and self-contained; if multiple transformations are truly needed, consider consolidating them into a single, well-tested script.
Problem
Allowing untrusted end users to define ad-hoc runtime fields directly inside arbitrary search requests.
Why It’s Harmful
Opens the door to resource-exhaustion style abuse, and to scripts that unintentionally read fields that should be protected from certain roles.
Correct Approach
Predefine a curated, reviewed set of runtime fields at the mapping level and only allow user queries to reference them by name.
9Best Practices and Common Mistakes
A short, practical checklist for using runtime fields effectively in real systems.
Best Practices
Prefer Doc Values Over _source
Read from doc values inside the script whenever possible, since it is meaningfully faster than reparsing raw JSON each time.
Filter Before You Compute
Combine a runtime field with a strong, indexed-field filter so the script only runs against a small candidate set, not the entire index.
Test With the Profile API
Always measure actual script execution time before assuming a runtime field’s performance impact is acceptable.
Promote Proven Fields
Once a runtime field is heavily and permanently used, reindex it as a true indexed field to reclaim query speed.
Version Your Scripts
Keep runtime field script definitions in source control alongside your application code, so changes are reviewed and reversible.
Name Fields Predictably
Give runtime fields clear, self-explanatory names so future engineers can immediately tell they’re computed, not stored.
Common Mistakes
Mistakes to Avoid
- Assuming a runtime field is “free” simply because it uses no disk space
- Running heavy runtime field aggregations across an entire unfiltered index
- Forgetting that a runtime field’s declared type restricts what operations are valid on it
- Not handling missing or malformed source data inside the script, causing errors or wrong results
- Leaving experimental runtime fields in production mappings indefinitely without review
Quick Fixes
- Measure before assuming; profile every new runtime field
- Always pair with a selective filter on an indexed field
- Match the declared type carefully to the emitted value
- Add defensive checks in the script for missing values
- Schedule periodic mapping reviews to clean up unused fields
If you find yourself running the exact same runtime field, on the exact same data, hundreds of times a minute, that’s usually a strong signal it’s time to promote it to a real indexed field.
10Real-World and Industry Examples
Runtime fields are widely used in observability, security, and analytics platforms built on Elasticsearch. Here are common, realistic scenarios.
Log Analysis and Observability
Teams ingesting application logs into the Elastic Stack frequently need new derived fields — extracting an HTTP status category, or a normalized error code — from logs that were already indexed weeks ago. Runtime fields let them apply this new logic retroactively across historical logs instantly, without an expensive full reindex of months of data.
Security Information and Event Management (SIEM)
Security teams often need to test a new detection rule — for example, flagging events where a computed risk score crosses a threshold — against past events before trusting it. A runtime field lets analysts iterate on the scoring logic freely and see results against real historical data immediately.
E-Commerce Search
An online retailer might store raw price and currency fields separately, then use a runtime field to compute an on-the-fly converted price in the shopper’s local currency at query time, reflecting the latest exchange rate without reindexing millions of product documents every time rates change.
Business Intelligence Dashboards
Analysts using Kibana frequently want to slice data by a new dimension — such as grouping timestamps into custom business quarters that don’t match the calendar — and runtime fields let them do this exploration directly inside the dashboard without waiting on a data engineering team to change the underlying pipeline.
Across all of these cases, the underlying motivation is the same: the cost of being wrong about a schema decision made months ago should not require reprocessing an enormous amount of historical data. Runtime fields turn “we should have indexed it differently” from a multi-day data engineering project into a mapping edit that takes effect immediately.
11Frequently Asked Questions
Yes. Runtime fields can be used inside most aggregation types, though because the value must be computed per document on the fly, aggregations over very large document sets can be noticeably slower than the same aggregation over an equivalent indexed field.
Yes, a runtime field can shadow an existing indexed field by sharing its name, effectively overriding how that field behaves for queries, while the original indexed data remains untouched underneath.
The execution cost is essentially the same either way. The difference is scope and reusability — a mapping-level definition is available to every future query automatically, while a query-level definition only exists for that one request.
They are generally better suited to filtering, sorting, and simple transformations rather than full-text search, since they lack the specialized inverted index structures that make text search fast on genuinely indexed text fields.
Elasticsearch provides ways to handle this gracefully within the script logic itself, such as checking whether a source value exists before using it. If unhandled, an error on one document can affect the entire query’s results for that shard.
Ask how often it will be queried and how likely its logic is to change. Frequently queried, stable logic belongs as an indexed field. Rarely queried, evolving, or exploratory logic belongs as a runtime field.
Runtime fields support a defined but somewhat narrower set of types, covering the most common cases such as text, numbers, dates, booleans, and a few others, which is usually sufficient for most derived-value use cases.
12Summary and Key Takeaways
A runtime field flips the usual order of operations in Elasticsearch: instead of deciding what a field means before storing data and paying that cost once, you decide what it means the moment you need an answer, and pay a small cost every time you ask. That single shift unlocks enormous flexibility — instant schema changes, retroactive application to historical data, and a safe space to experiment — at the price of extra computation on every query that uses it. Used deliberately, alongside ordinary indexed fields rather than as a wholesale replacement for them, runtime fields let teams evolve their data model at the speed of a business question, instead of at the speed of a reindexing job.
Key Takeaways
- Definition — A runtime field is evaluated at query time using a script, and its value is never stored on disk.
- Location — Runtime fields are declared either in the index mapping, permanently, or inside a single search request, temporarily.
- Engine — Painless, Elasticsearch’s sandboxed scripting language, powers the logic behind every runtime field.
- Trade-off — Zero storage cost and total flexibility, in exchange for computation happening on every matching query.
- Security — Scripts run inside a sandbox with no file or network access, but resource abuse and unintended data exposure are still real risks to manage.
- Operations — Monitor script execution time and CPU usage the same way you’d monitor any other expensive query pattern.
- Best fit — Ideal for exploration, retroactive analysis, and evolving logic; promote heavily used, stable fields to indexed fields for speed.