I need to add a date field type such that the document will take the current system date time as the default value. I'm using Elasticsearch 7.5.
PUT /myindex/_mappings
{
"properties": {
"create_date": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss",
"null_value": "now"
}
}
}
There's no such functionality in Elasticsearch. At least not directly.
What you can do, however, is create an ingest pipeline that assigns the current datetime from inside a script processor:
PUT _ingest/pipeline/auto_now_add
{
"description": "Assigns the current date if not yet present",
"processors": [
{
"script": {
"source": """
// don't overwrite if present
if (ctx['create_date'] == null) {
ctx['create_date'] = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
"""
}
}
]
}
After that, as you PUT
your index, you'll specify the default_pipeline
:
PUT myindex
{
"settings": {
"index": {
"default_pipeline": "auto_now_add" <---
}
},
"mappings": {
"properties": {
"create_date": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
}
}
}
}
Then, as you insert a doc with a missing create_date
:
PUT myindex/_doc/1
{
"abc": "def"
}
Elasticsearch will have auto-added the current timestamp. Verify with:
POST myindex/_search