How to calculate timestamp difference using Kibana scripted field feature?

I have two date fields in my Elasticsearch index: 1. Submit_Date & 2. Completed_Date.
I want to add new field which will be diff between Completed_Date and Submit_Date...
but if Completed_Date is empty I want the diff between current system timestamp and Submit_Date...

I have written following code but getting error:

if(doc['Completed_Date'] && doc['Submit_Date']) {
return doc['Completed_Date'] - doc['Submit_Date']
} else {
return new Date().getTime() - doc['Submit_Date']

please help..what wrong thing I'm doing here...

Here is an example

GET my-index/_search
  "_source": ["Submit_Date", "Completed_Date"],  
  "script_fields": {
    "daysBetween": {
      "script": {
        "source": "(doc['Completed_Date'].value.toInstant().toEpochMilli() - doc['Submit_Date'].value.toInstant().toEpochMilli()) / params.factor",
        "params": {
          "factor": 86400000

Computing data on the fly with scripted fields can be very resource intensive and can have a direct impact on Kibana performance. Keep in mind that there’s no built-in validation of a scripted field. If your scripts are buggy, you’ll get exceptions whenever you try to view the dynamically generated data.

Use something like this to check if field exist in the doc

if (!doc.containsKey('myfield') || doc['myfield'].empty) { return "unavailable" } else { return doc['myfield'].value }

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