Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Elasticsearch Mapping: The Basics, Two Types, and a Few Examples

DZone's Guide to

Elasticsearch Mapping: The Basics, Two Types, and a Few Examples

In this post we take a deep dive into Elasticsearch, including the basics as well as some different field types, replete with examples to help get you going with both static and dynamic mappings!

· Database Zone
Free Resource

Learn how to create flexible schemas in a relational database using SQL for JSON.

elasticsearch mapping

Within a search engine, mapping defines how a document is indexed and how its fields are indexed and stored. We can compare mapping to a database schema in how it describes the fields and properties that documents hold, the datatype of each field (e.g., string, integer, or date), and how those fields should be indexed and stored by Lucene. It is very important to define the mapping after we create an index — an inappropriate preliminary definition and mapping may result in the wrong search results.

In a previous article, we ran an elaborate comparison of the two search engine market leaders, Elasticsearch and Apache Solr. Here, we will delve deep into the Elasticsearch mappings using a stable Elasticsearch v2.4 configuration. We will discuss the basics, the different field types, and then give examples for both static and dynamic mapping.

About Mapping

Mapping is intended to define the structure and field types as required based on the answers to certain questions. For example:

  • Which string fields should be full text and which should be numbers or dates (and in which formats)?
  • When should you use the _all field, which concatenates multiple fields to a single string and helps with analyzing and indexing?
  • What custom rules should be set to update new field types automatically as they are added (e.g., the dynamic mapping type, which we will discuss further later on)?

Each index has one or more mapping types that are used to divide documents into logical groups. Basically, a type in Elasticsearch represents a class of similar documents and it has a name such as “customer” or “item.” Lucene has no concept of document data types, so the type name of each document is stored in a metadata field of a document called _type. When we search for documents within a particular type, Elasticsearch simply uses a filter on the _type field to restrict the search.

In addition, mappings is the layer that Elasticsearch uses to map complex JSON documents into the simple flat documents that Lucene expects to receive. Each mapping type has fields or properties defined by meta-fields and various data types.

Data-Type Fields

When we create mapping, each mapping type will be a combination of multiple fields or lists with various types. For example, a “user” type may contain fields for title, first name, last name, and gender whereas an “address” type might contain fields for city, state, and zip code.

Elasticsearch supports a number of different data types for the fields in a document:

Core Data Types

String, Date, Numeric (long, integer, short, byte, double, and float), Boolean, Binary.

Complex Data Types

  • Array: Array support does not require a dedicated type.

  • Object: Object for single JSON objects.

  • Nested: Nested for arrays of JSON objects.

Geo Data Types

  • Geo-point: Geo_point for latitude/longitude points.

  • Geo-shape: Geo_shape for complex shapes such as polygons.

Specialized Data Types

  • IPv4: IP for IPv4 addresses.

  • Completion: completion to provide autocomplete suggestions.

  • Token count: token_count to count the number of tokens in a string.

  • Attachment: Mapper-attachments plugin which supports indexing attachments in formats such as Microsoft Office, Open Document, ePub, and HTML, into an attachment datatype.

Note: In versions 2.0 to 2.3, dots are not permitted in field names. Elasticsearch 2.4.0 adds a system property called mapper.allow_dots_in_name that disables the check for dots in field names.

Meta Fields

Meta fields are used to customize how a document’s associated metadata is treated. Each document has associated metadata such as the _index, mapping _type, and _id meta-fields. The behavior of some of these meta fields can be customized when a mapping type is created.

Identity Meta Fields

  • _index: The index to which the document belongs.

  • _uid: A composite field consisting of the _type and the _id.

  • _type: The document’s mapping type.

  • _id: The document’s ID.

Document Source Meta Fields

  • _source: The original JSON representing the body of the document.

  • _size:The size of the _source field in bytes, provided by the mapper-size plugin.

Indexing meta-fields

  • _all: A catch-all field that indexes the values of all other fields.

  • _field_names: All fields in the document that contain non-null values.

  • _timestamp: A timestamp associated with the document, either specified manually or auto-generated.

  • _ttl: How long a document should live before it is automatically deleted.

Routing Meta Fields

  • _parent: Used to create a parent-child relationship between two mapping types.

  • _routing: A custom routing value that routes a document to a particular shard.

Other Meta Field

  • _meta: Application-specific metadata.

An Example

To create a mapping, you will need the Put Mapping API that will help you to set a specific mapping definition for a specific type, or you can add multiple mappings when you create an index.

An example of mapping creation using the Mapping API:

PUT 'Server_URL/Index_Name/_mapping/Mapping_Name'
{
            "type_1" : {
                        "properties" : {
                                    "field1" : {"type" : "string"}
                        }
            }
}


  • Index_Name: Provides the index name to be created
  • Mapping_Name: Provides the mapping name
  • type_1 : Defines the mapping type
  • Properties: Defines the various properties and document fields
  • {“type”}: Defines the data type of the property or field

Below is an example of mapping creation using an index API:

PUT /index_name

{
  "mappings":{
            "type_1":{
                        "_all" : {"enabled" : true},
                        "properties":{
                                    "field_1":{ "type":"string"},
                                    "field_2":{ "type":"long"}
                        }
            },
            "type_2":{
                        "properties":{
                                    "field_3":{ "type":"string"},
                                    "field_4":{ "type":"date"}
                        }
            }
  }
}


In the above code:

  • Index_Name: The name of the index to be created.
  • type_1: Defines the mapping type.
  • _all: The configuration metafield parameter. If “true,” it will concatenate all strings and search values.
  • Properties: Defines the various properties and document fields.
  • {“type”}: Defines the data type of the property or field.

Two Mapping Types

Elasticsearch supports two types of mappings: “Static Mapping” and “Dynamic Mapping.” We use Static Mapping to define the index and data types. However, we still need ongoing flexibility so that documents can store extra attributes. To handle such cases, Elasticsearch comes with the dynamic mapping option that was mentioned at the beginning of this article.

Static Mapping

In a normal scenario, we know well in advance which kind of data will be stored in the document, so we can easily define the fields and their types when creating the index. Below is an example in which we are going to index employee data into an index named “company” under the type “employeeInfo.”

Sample document data:

{
"name" : {"first" :"Alice","last":"John"},
"age" : 26,
"joiningDate" : "2015-10-15"
}


Example:

PUT /company

{
  "mappings":{
            "employeeinfo":{
                        "_all" : {"enabled" : true},
                        "properties":{
                                    "name":{
                                                "type":"object",
                                                "properties":{
                                                            "field_1":{
                                                                       "type":"string"
                                                           },
                                                           "field_2":{
                                                                      "type":"string"
                                                           }
                                               }
                                    },
                                    "age":{
                                                "type":"long"
                                    },
                                    "joiningDate":{
                                                "type":"date"
                                    }
                        }
            }
 }
}


In the above API:

  • employeeinfo: Defines the mapping type name.
  • _all: The configuration metafield parameter. If “true,” it will concatenate all strings and search values.
  • Properties: Defines various properties and document fields.
  • {“type”}: Defines the data type of the property or field.

Dynamic Mapping

Thanks to dynamic mapping, when you just index the document, you do not always need to configure the field names and types. Instead, these will be added automatically by Elasticsearch using any predefined custom rules have been defined. New fields can be added both to the top-level mapping type and to inner objects and nested fields. In addition, dynamic mapping rules can be configured to customize the existing mapping.

Custom rules help to identify the right data types for unknown fields, such as mapping true/false in JSON to boolean, while integer in JSON maps to long in Elasticsearch. Rules can be configured using dynamic field mapping or a dynamic template. When Elasticsearch encounters an unknown field in a document, it uses dynamic mapping to determine the data type of the field and automatically adds the new field to the type mapping.

However, there will be cases when this will not be your preferred option. Perhaps you do not know what fields will be added to your documents later, but you do want them to be indexed automatically. Perhaps you just want to ignore them. Or, especially if you are using Elasticsearch as a primary data store, maybe you want unknown fields to have an exception to alert you of the problem. Fortunately, you can control this behavior with the dynamic setting, which accepts the following options:

  • true: Add new fields dynamically — this is the default.
  • false: Ignore new fields.
  • strict: Throw an exception if an unknown field is encountered.

Example:

PUT /index_name

{
            "mappings": {
            "my_type": {
            "dynamic": "strict",
                        "properties": {
                               "title":  { "type":"string"},
                               "stash":  {
                                     "type": "object",
                                     "dynamic":  true
                                     }
                        }
            }
            }
}


In the above API:

  • index_name: creates an index with this name
  • my_type: defines the mapping type name
  • “dynamic”: “strict”: – the “my_type” object will throw an exception if an unknown field is encountered
  • “dynamic”:  true: – the “stash” object will create new fields dynamically
  • _all: The configuration metafield parameter. If “true,” it will concatenate all strings and search values
  • properties: defines the various properties and document fields
  • {“type”}: defines the data type of the property or field

With dynamic mapping, you can add new searchable fields into the stash object:

Example:

PUT /my_index/my_type/1

{
   "title": "This doc adds a new field",
   "stash": { "new_field": "Success!" }
}


But trying to do the same at the top level will fail:

PUT /my_index/my_type/1

{
   "title": "This throws a StrictDynamicMappingException",
   "new_field": "Fail!"
}


What’s New in Elasticsearch 5.0 for Mapping?

Elasticsearch 2.X had a “string” data type for full-text search and keyword identifiers. Full-text search is basically used to discover relevant text in documents, while keyword identifiers are used for sorting, aggregating, and filtering the documents. In Elasticsearch 2.x, we cannot explicitly tell the Elasticsearch engine which fields are used for full-text search and which are used for sorting, aggregating, and filtering the documents.

Elasticsearch 5.X — see our full post on the full ELK Stack 5.0 as well as our Complete Guide to the ELK Stack — comes with two new data types called “text” and “keyword,” replacing the “string” data type in the earlier version.

  • “Text”: Full-text and relevancy search in documents
  • “Keyword”: Exact-value search for sorting, aggregation and filtering documents

Text fields support the full analysis chain while keyword fields will support only a limited analysis — just enough to normalize values with lower casing and similar transformations. Keyword fields support document values for memory-friendly sorting and aggregations while text fields have field data disabled by default to prevent the loading of massive amounts of data into the memory by mistake.

Note: The “string” field type continue to work during the 5.x series, but it will likely be removed in 6.0.

When to Use “Text” or “Keyword” Data Type

Ending this article with a practical tip, here is a rule of thumb for mapping in Elasticsearch:

  • “Text” data types: Use when you require full-text search for particular fields such as the bodies of e-mails or product descriptions
  • “Keyword” data types: Use when you require an exact-value search, particularly when filtering (“Find me all products where status is available”), sorting, or using aggregations. Keyword fields are only searchable by their exact value. Use keyword data types when you have fields like email addresses, hostnames, status codes, zip codes, or tags.

Summary

Mapping in Elasticsearch can seem daunting at times, especially if you’re just starting out with ELK. At Logz.io, this is part of the service we provide our users. But if you’re using your own Elasticsearch deployment, pay careful attention to the details. We hope this article will help you to understand the basics.

Create flexible schemas using dynamic columns for semi-structured data. Learn how.

Topics:
mapping ,elasticsearch ,database ,search engine

Published at DZone with permission of Daniel Berman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}