How to Define Mapping in Elasticsearch: Syntax and Examples
In Elasticsearch, you define a
mapping to specify how documents and their fields are stored and indexed. You create a mapping by sending a JSON object to the index with field names and their data types using the PUT API on the index or when creating it.Syntax
The mapping is defined as a JSON object specifying field names and their data types. You use the PUT request on an index's _mapping endpoint or during index creation. The main parts are:
properties: Defines fields and their types.type: Specifies the data type liketext,keyword,date,integer, etc.- Optional settings like
analyzerfor text fields.
json
{
"mappings": {
"properties": {
"field_name": {
"type": "data_type"
}
}
}
}Example
This example creates an index named library with mapping for a book document. It defines title as text for full-text search, author as keyword for exact matches, and publish_date as date.
json
PUT /library
{
"mappings": {
"properties": {
"title": {
"type": "text"
},
"author": {
"type": "keyword"
},
"publish_date": {
"type": "date"
}
}
}
}Output
{
"acknowledged": true,
"shards_acknowledged": true,
"index": "library"
}
Common Pitfalls
Common mistakes when defining mappings include:
- Not defining a mapping before indexing data, which causes Elasticsearch to guess types and may lead to wrong field types.
- Using
texttype when you want exact matches instead ofkeyword. - Changing a field type after data is indexed, which is not allowed without reindexing.
Always plan your mapping before adding documents.
json
/* Wrong: indexing a field as text but expecting exact match */ PUT /wrong_index { "mappings": { "properties": { "status": { "type": "text" } } } } /* Right: use keyword for exact matches */ PUT /correct_index { "mappings": { "properties": { "status": { "type": "keyword" } } } }
Quick Reference
| Field Type | Description | Use Case |
|---|---|---|
| text | Full-text searchable string | Searchable text fields like titles, descriptions |
| keyword | Exact value string | Tags, IDs, categories, exact matches |
| date | Date or time | Publish dates, timestamps |
| integer | Whole numbers | Counts, ages, quantities |
| float | Decimal numbers | Prices, ratings |
| boolean | True or false | Flags, binary states |
Key Takeaways
Define mapping before indexing data to control field types and indexing behavior.
Use
text for searchable text and keyword for exact matches.Mapping is a JSON object sent via
PUT to the index's _mapping endpoint or during index creation.Changing field types after indexing requires reindexing the data.
Common field types include text, keyword, date, integer, float, and boolean.