0
0
Elasticsearchquery~5 mins

Date field types in Elasticsearch

Choose your learning style9 modes available
Introduction

Date field types help you store and search dates easily in Elasticsearch. They let you work with times and dates like birthdays or event times.

You want to save a user's birthday and find users born before a certain date.
You need to record when an event happened and search events by date range.
You want to sort documents by the date they were created.
You want to filter logs by specific time periods.
You want to calculate how old something is based on stored dates.
Syntax
Elasticsearch
PUT /my_index
{
  "mappings": {
    "properties": {
      "my_date": {
        "type": "date",
        "format": "yyyy-MM-dd||epoch_millis"
      }
    }
  }
}

The type must be set to date for date fields.

The format defines how dates are written and read. You can list multiple formats separated by ||.

Examples
This example stores dates in the format year-month-day like 2024-06-01.
Elasticsearch
PUT /events
{
  "mappings": {
    "properties": {
      "event_date": {
        "type": "date",
        "format": "yyyy-MM-dd"
      }
    }
  }
}
This example stores dates as milliseconds since 1970-01-01 (epoch time).
Elasticsearch
PUT /logs
{
  "mappings": {
    "properties": {
      "timestamp": {
        "type": "date",
        "format": "epoch_millis"
      }
    }
  }
}
This example accepts three date formats for the same field.
Elasticsearch
PUT /mixed_dates
{
  "mappings": {
    "properties": {
      "date_field": {
        "type": "date",
        "format": "yyyy-MM-dd||yyyy/MM/dd||epoch_millis"
      }
    }
  }
}
Sample Program

This program creates an index with a date field that accepts two formats. It adds two documents with dates in different formats. Then it searches for documents created on June 1, 2024.

Elasticsearch
PUT /my_index
{
  "mappings": {
    "properties": {
      "created_at": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss||epoch_millis"
      }
    }
  }
}

POST /my_index/_doc
{
  "created_at": "2024-06-01 14:30:00"
}

POST /my_index/_doc
{
  "created_at": 1717252200000
}

GET /my_index/_search
{
  "query": {
    "range": {
      "created_at": {
        "gte": "2024-06-01 00:00:00",
        "lte": "2024-06-02 00:00:00"
      }
    }
  }
}
OutputSuccess
Important Notes

Always specify the date format if your dates are not in the default ISO format.

Elasticsearch stores dates internally as milliseconds since epoch, no matter the input format.

Using multiple formats helps when your data comes from different sources.

Summary

Date fields store time and date information in Elasticsearch.

You define the format so Elasticsearch knows how to read your dates.

You can search, sort, and filter documents by date easily.