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.