I have stored the 3 date datatype variable (date1, date2, date3) in my index using a stored script. I have calculated duration between two date variables(date2 - date1) and stored in the third date variable (date3). Here is my complete mapping, scripts and update requests that I have used.
PUT /myindex
POST /myindex/_mappings
{
"properties":{
"date1":{
"type":"date"
},
"date2":{
"type":"date"
},
"date3":{
"type":"date"
}
}
}
POST _scripts/myindexscript/
{
"script":{
"source" :"""
if (ctx._source.date1==null) {
ctx._source.date1 = new Date().getTime();
}
ctx._source.status.add(params.status);
if (!(params.status).equalsIgnoreCase('Info')) {
ctx._source.date2 = new Date().getTime();
ctx._source.date3=ctx._source.date2 - ctx._source.date1;
}
""",
"lang": "painless"
}
}
POST /myindex/_update/1
{
"script":{
"id":"myindexscript",
"params":{
"status": "Infoa"
}
}
, "upsert": {
"date1":null,
"date2":null,
"date3":null,
"status": []
},
"scripted_upsert": true
}
I have inserted 1 document as you can see here. For insertion in the document I first run the _update request with field status='Info' and then field status!='Infoa'. Here you can see output of GET /myindex/_search
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "myindex",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"date3" : 5589,
"date2" : 1590062272146,
"date1" : 1590062266557,
"status" : [
"Info",
"Infoa"
]
}
}
]
}
}
Now I run this particular aggregation request
GET /myindex/_search
{
"query": {
"term": {
"status.keyword": {
"value": "Infoc"
}
}
},
"aggs": {
"NAME": {
"avg": {
"field": "date3"
}
}
},
"size": 20
}
Which give this weird output :
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.8025915,
"hits" : [
{
"_index" : "myindex",
"_type" : "_doc",
"_id" : "1",
"_score" : 0.8025915,
"_source" : {
"date3" : 5589,
"date2" : 1590062272146,
"date1" : 1590062266557,
"status" : [
"Info",
"Infoa"
]
}
}
]
},
"aggregations" : {
"NAME" : {
"value" : 1.142046432E14,
"value_as_string" : "5589-01-01T00:00:00.000Z"
}
}
}
why in aggregation result the value is not 5589 but "value" : 1.142046432E14 . I am not able to understand how date3 field is processed for average calculation. Kindly help ?