Groovy script to calculate a value depending on a document parameter

Hi,

I'm trying to implement a Groovy script that calculates a value depending on a specific input parameter. An exemplary document looks as following:

{
"_id": "2217",
"_index": vm",
"_score": null,
"_source": {
"@timestamp": "2016-04-21T13:23:00.701Z",
"@version": "1",
"created_at": "2016-04-13T05:44:10.000Z",
"deleted": 0,
"deleted_at": null,
"id": 2217,
"vm_state": "active"
}

The field "vm_state" can either be "active" or "deleted". Depending on the vm_state I want to calculate the runtime of a vm:

  • vm_state: deleted --> runtime = deleted_at - created_at
  • vm_state: active --> runtime = now() - created_at

For this I tried to implement a small Groovy script but I'm not able to identify the vm_state correctly.
My Groovy script looks as following:

if (doc.vm_state == "deleted") {
runtime= 1
} else if (doc.vm_state == "active") {
runtime = 2
} else
runtime = 99

The corresponding query looks like this:

{
"query" : {
"query_string" : {
"query": "vm_state:deleted OR vm_state:active"
}
},
"script_fields": {
"runtime": {
"script": {
"file": "vm_lifetime"
}
}
},
"size": 1000
}

Running the query, runtime is always 99!
If I run a query for vm_state: active ten documents are found
{
"query" : {
"term" : { "vm_state" : "active" }
}
}
If I run a query for vm_state:deleted, then over 500 documents are found.

Any hint, why my script is not work is welcome

Thanks in advance
Elkonaut