# Groovy script to calculate a value depending on a document parameter

**URL:** <https://discuss.elastic.co/t/groovy-script-to-calculate-a-value-depending-on-a-document-parameter/48151>\
**Category:** Elasticsearch\
**Created:** [April 22, 2016, 9:06am UTC](https://discuss.elastic.co/t/groovy-script-to-calculate-a-value-depending-on-a-document-parameter/48151 "2016-04-22T09:06:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![elkonaut](https://avatars.discourse-cdn.com/v4/letter/e/bc8723/32.png) [@elkonaut](https://discuss.elastic.co/u/elkonaut)\
**Post date:** [April 22, 2016, 9:06am UTC](https://discuss.elastic.co/t/groovy-script-to-calculate-a-value-depending-on-a-document-parameter/48151/1 "2016-04-22T09:06:50Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 5, 2017, 10:57pm UTC](https://discuss.elastic.co/t/groovy-script-to-calculate-a-value-depending-on-a-document-parameter/48151/2 "2017-07-05T22:57:03Z")

</div>

Closed on July 5, 2017, 10:57pm UTC


