Script fields in query not showing up in Kibana visualize aggregation

I am using the following search query in Kibana. Its returning the expected results. I am trying to aggregate vertical bar chart visualization using the script field. But the script fields "duration" and "state" isn't showing up in the drop down. Any idea why?

{
"index": "logs_test",
"query": {
"regexp": {
"body.message": ".* ended ."
}
},
"script_fields": {
"duration": {
"type": "double",
"script": {
"lang": "groovy",
"file": "extract_time"
}
},
"state": {
"type": "string",
"script": {
"lang": "groovy",
"file": "extract_state"
}
}
},
"filter": [],
"highlight": {
"pre_tags": [
"@kibana-highlighted-field@"
],
"post_tags": [
"@/kibana-highlighted-field@"
],
"fields": {
"
": {}
},
"require_field_match": false,
"fragment_size": 2147483647
}
}

If I understand correctly, you've put the above query in the Kibana filter bar? Script fields from the filter bar won't show up as an option in the Viz editor. Only fields added via Kibana's scripted field UI will show up. In 4.x you can only use lucene expressions for scripted fields, but in 5.x you'll be able to use the Painless scripting language which should allow you to do what you want.

Thank you for the reply. I am using groovy scripts now. I wasn't sure why script fields won't show up. Now I understand. I think script fields can't be referenced in elastic search query aggregations. That rules out the Kibana use case mentioned in my question.