How to find the difference between current time and firsteventdetected time using scripting

Hi All,

I am trying to find the difference between the current time and firsteventdetected time from the index and below is the query,

POST transaction*/_search
{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "age": {
      "script": {
        "lang": "painless",
        "source": "(doc['FirstEventDetectedTime'].value - new Date().getTime() * 1000)"
      }
    }
  }
}

Below is the error I am getting,

{
  "error": {
    "root_cause": [
      {
        "type": "class_cast_exception",
        "reason": "class_cast_exception: Cannot apply [-] operation to types [org.joda.time.MutableDateTime] and [java.lang.Long]."
      }
    ],
    "type": "search_phase_execution_exception",
    "reason": "all shards failed",
    "phase": "query",
    "grouped": true,
    "failed_shards": [
      {
        "shard": 0,
        "index": "transaction",
        "node": "77dK4fb_Qw26iXZGPYy-Gg",
        "reason": {
          "type": "script_exception",
          "reason": "runtime error",
          "script_stack": [
            "doc['FirstEventDetectedTime'].value - new Date().getTime() * 1000",
            "                                                ^---- HERE"
          ],
          "script": "doc['FirstEventDetectedTime'].value - new Date().getTime() * 1000",
          "lang": "painless",
          "caused_by": {
            "type": "class_cast_exception",
            "reason": "class_cast_exception: Cannot apply [-] operation to types [org.joda.time.MutableDateTime] and [java.lang.Long]."
          }
        }
      }
    ],
    "caused_by": {
      "type": "class_cast_exception",
      "reason": "class_cast_exception: Cannot apply [-] operation to types [org.joda.time.MutableDateTime] and [java.lang.Long]."
    }
  },
  "status": 500
}

The data in the FirstEventDetectedTime field has like this "2019-01-10T12:55:30.000Z"

Below is the query I tried to get the current time,

POST transaction*/_search
{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "age": {
      "script": {
        "lang": "painless",
        "source": "new Date().getTime() * 1000"
      }
    }
  }
}

above Query response,

{
"_index": "transaction",
"_type": "1",
"_id": "QrhrZWgBaqAekAe-SdEr",
"_score": 1,
"fields": {
"age": [
1547903795164000
]
}
}

Please let me know your thoughts on finding the difference between the current time and firsteventdetected time.

Regards,
Ganeshbabu R

To get the difference between the two times in milliseconds you can use this Painless script:

doc['FirstEventDetectedTime'].value.getMillis() - System.currentTimeMillis()
1 Like

Thanks @abdon for your inputs and it's worked rightly.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.