Mapping in Elasticsearch
Mapping serves as the schema definition for an index, similar to table structures in relational databases. Its primary responsibilities include:
- Declaring field names within the index
- Specifying data types for each field
- Configuring inverted index settings
When documents are indexed, Elasticsearch transforms the JSON structure into the flat format required by Apache Lucene.
Field Data Types
Simple Types
- Text / Keyword
- Date
- Integer / Floating
- Boolean
- IPv4 / IPv6
Complex Types
- Object and nested types
Specialized Types
- Geolocation types
Dynamic Mapping
During document creation, Elasticsearch automatically infers field types based on the document content. This dynamic mapping capability eliminates the need to manual schema definition.
Example workflow:
// creating the employee_info index
POST employee_info/_doc
{
"username":"john",
"hireDate":"2021-05-14",
"location":"usa"
}
// retrieving the inferred mapping
GET /employee_info/_mapping
Response structuree:
{
"employee_info" : {
"mappings" : {
"properties" : {
"hireDate" : {
"type" : "date"
},
"location" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"username" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
}
}
Dynamic Field Control
The dynamic parameter governs how Elasticsearch handles new fields discovered during indexing:
true(default): Documents are indexed normally, and new fields become searchablefalse: Documents are indexed, but new fields cannot be searchedstrict: Document indexing is rejected if unknown fields are present
Configuration example:
PUT employee_info/_mapping
{
"dynamic":"strict"
}
Explicit Mapping Definition
Manual mapping configuraton provides precise control over field behavior:
PUT staff_directory
{
"mappings": {
"properties": {
"firstName": {
"type": "text"
},
"lastName": {
"type": "text"
},
"joinDate": {
"type": "date",
"index": false
}
}
}
}