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.
Date field types in 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 ||.
PUT /events
{
"mappings": {
"properties": {
"event_date": {
"type": "date",
"format": "yyyy-MM-dd"
}
}
}
}PUT /logs
{
"mappings": {
"properties": {
"timestamp": {
"type": "date",
"format": "epoch_millis"
}
}
}
}PUT /mixed_dates
{
"mappings": {
"properties": {
"date_field": {
"type": "date",
"format": "yyyy-MM-dd||yyyy/MM/dd||epoch_millis"
}
}
}
}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.
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"
}
}
}
}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.
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.