Scripted terms always returns stringified values

Hello,
we are using script to execute terms on fields that are run-time created by source and we don't know their name in advance.
Source documents:

{
                 "@timestamp": "2020-11-24T06:06:14.0058521+01:00",
                        "UnknownFieldName": 1,
                        "VariableName": "UnknownFieldName",
                  }

Here VariableName tells name of field that contains value and we want to execute term on field "UnknownFieldName".

We use the following query to retrieve values for each runtime variable:

       {
       "RunTimeVariableTerms":{
          "aggs":{
             "name":{
                "terms":{
                   "field":"Raw.VariableName.keyword"
                },
                "aggs":{
                   "RunTimeVarValues":{
                      "terms":{
                         "size":99,
                         "script":{
                            "lang":"painless",
                            "source":"String varName = doc[ 'VariableName.keyword'].value; return doc[varName]"
                         }
                      }
                   }
                }
             }
          }
       }
    }

We obtain:

"RunTimeVariableTerms":{
   "doc_count":5,
   "Name":{
      "doc_count_error_upper_bound":0,
      "sum_other_doc_count":0,
      "buckets":[
         {
            "key":"UnknownFieldName",
            "doc_count":5,
            "RunTimeVarValues":{
               "doc_count_error_upper_bound":0,
               "sum_other_doc_count":0,
               "buckets":[
                  {
                     "key":"1",
                     "doc_count":5,
                     "type":{
                        "doc_count_error_upper_bound":0,
                        "sum_other_doc_count":0,
                        "buckets":[
                           {
                              "key":"int",
                              "doc_count":5
                           }
                        ]
                     }
                  }
               ]
            }
         }
      ]
   }
}

Values in the key field are always returned stringified, no matter the variable type while if we execute terms directly on field we obtain keys with original type. We need variable with it's own real type. How can we achieve it?

Thanks

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