Explicit Mapping and the Mapping Explosion
Dynamic mapping guessed that rating was text. The cure is to stop letting Elasticsearch guess: write the mapping yourself when you create the index. Doing so also protects you from a quieter disaster — a mapping that grows without limit.
The rule
Declare the fields you know; you may add fields later, never retype them.
An explicit mapping is sent with the index creation request:
PUT /books
{
"mappings": {
"dynamic": "strict",
"properties": {
"title": { "type": "text" },
"author": { "type": "keyword" },
"genre": { "type": "keyword" },
"price": { "type": "float" },
"pages": { "type": "integer" },
"in_stock": { "type": "boolean" },
"published": { "type": "date" }
}
}
}Every field now has the type you intended, and "dynamic": "strict" rejects any document carrying a field you did not declare.
The rules for changing it afterwards:
- Adding a new field is allowed at any time:
PUT /books/_mapping
{ "properties": { "rating": { "type": "half_float" } } }- Changing an existing field's type is not allowed. Documents already indexed were stored the old way. The fix is to create a new index with the right mapping and copy the documents across with the Reindex API.
A mapping explosion happens when documents keep inventing new field names. Imagine the shop logs every search with the shopper's filters as keys: {"filters": {"price_under_20": true, "author_mira_das": true, ...}}. With dynamic mapping on, each new key becomes a new field. The mapping — which lives in the cluster state that the master shares with every node — swells, and the cluster slows down. Elasticsearch caps an index at 1,000 fields by default (index.mapping.total_fields.limit) and rejects documents that would go past it.
The cures: design with fixed field names ({"filter": "author", "value": "Mira Das"}), set dynamic to false or strict for the risky part, or use the flattened type, which you will meet in the next section.
The shortcut
Before each field ships, ask "is this name a label or a value?" Labels (price, author) belong in the mapping. Values pretending to be names (author_mira_das, a user id as a key) will explode it.
Create the right index
PUT /books_v2withratingmapped ashalf_float.
Drills
Answer fast — trust the rule.
price is mapped as keyword by mistake. How do you fix it?
Which change to an existing index's mapping is allowed?
Which document design is most likely to cause a mapping explosion?
What is the default limit on the number of fields in one index?
Remember
- Declare the fields you know; you may add fields later, never retype them.
- A wrong type means new index + reindex.
- Field names are labels, not values — or the mapping explodes past its 1,000-field limit.
