Dynamic templates in Elasticsearch - Time & Space Complexity
When Elasticsearch applies dynamic templates, it decides how to map new fields automatically.
We want to understand how the time to process these templates grows as the number of fields increases.
Analyze the time complexity of the following dynamic templates configuration.
PUT /my_index
{
"mappings": {
"dynamic_templates": [
{
"strings_as_keywords": {
"match_mapping_type": "string",
"mapping": { "type": "keyword" }
}
}
]
}
}
This code sets a rule: any new string field is mapped as a keyword automatically.
Look for repeated checks or loops when new fields arrive.
- Primary operation: For each new field, Elasticsearch checks each dynamic template in order.
- How many times: Once per new field, and once per template until a match is found.
As the number of new fields (n) grows, Elasticsearch tests each field against the templates.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 template checks |
| 100 | About 100 template checks |
| 1000 | About 1000 template checks |
Pattern observation: The work grows directly with the number of new fields.
Time Complexity: O(n)
This means the time to apply dynamic templates grows in a straight line as more fields appear.
[X] Wrong: "Dynamic templates apply instantly no matter how many fields there are."
[OK] Correct: Each new field must be checked against templates, so more fields mean more checks and more time.
Understanding how dynamic templates scale helps you explain how Elasticsearch handles flexible data efficiently.
"What if we added many dynamic templates instead of just one? How would the time complexity change?"