{ "query" : { "match_all": {} }, "script_fields" : { "timeSince" : { "script" : { "lang": "painless", "source": " long now = System.currentTimeMillis(); if (doc.get('closedLoopEventStatus.keyword').value == 'ABATED') { return now - doc.get('closedLoopAlarmEnd').value; } if (doc.get('closedLoopEventStatus.keyword').value == 'ONSET') { return now - doc.get('closedLoopAlarmStart').value; } if (doc.containsKey('notification.keyword')) { return now - doc.get('notificationTime').value; } return null " } } , "closedLoopAlarmStart" : { "script" : { "lang": "painless", "source": "doc['closedLoopAlarmStart']" } } , "closedLoopEventStatus" : { "script" : { "lang": "painless", "source": "doc['closedLoopEventStatus.keyword']" } } , "notification" : { "script" : { "lang": "painless", "source": "doc['notification.keyword']" } } , "notificationTime" : { "script" : { "lang": "painless", "source": "doc['notificationTime'].value" } } } }