0
0
ElasticsearchHow-ToBeginner · 4 min read

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 like text, keyword, date, integer, etc.
  • Optional settings like analyzer for 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 text type when you want exact matches instead of keyword.
  • 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 TypeDescriptionUse Case
textFull-text searchable stringSearchable text fields like titles, descriptions
keywordExact value stringTags, IDs, categories, exact matches
dateDate or timePublish dates, timestamps
integerWhole numbersCounts, ages, quantities
floatDecimal numbersPrices, ratings
booleanTrue or falseFlags, 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.