Double to long conversion

Hi,

How to convert (default) double type value returned by aggregation( Sum).
I am receiving this exception while trying to explicitly convert to long type. Appreciate any advice. thank you.

=====================================
type" : "illegal_argument_exception",
"reason" : "unexpected token ['long'] was expecting one of [ID]."

GET logstash-2022.01.18/_search?size=0
{
"query": {
"exists": {
"field":"message.keyword"
}
},

"aggs": {
"msgsize": {
"sum": {
"script": {
"lang": "painless",
"source": """
double msglen = "doc['message.keyword'].value.length()",
long msgcast = msglen
return msgcast
"""
}
}
}
}
}

Hi @makudu, try adding a semicolon at the end of these statements.

The first statement wasn't terminated (there's a comma at the end of the line), so the next token when parsing the script, long is unexpected.

double msglen = doc['message.keyword'].value.length();
long msgcast = msglen;
return msgcast;

Tried, but this error.

"class_cast_exception",
"reason" : "Cannot cast from [double] to [long]."

Because of the potential for loss of precision, painless does not implicitly cast from double to long, the script will have to explicitly cast it.

long msgcast = (long) msglen;

or

return (long) msglen;

Tried providing explicit cast, this is the exception
"type" : "class_cast_exception",
"reason" : "Cannot cast from [java.lang.String] to [long].

"source": """
long msglen = "doc['message.keyword'].value.length()";
return (long) msglen;
"""

"source": """
double msglen = "doc['message.keyword'].value.length()";
return (long) msglen;
"""

That's a string literal due to the quotes, you'll want:

doc['message.keyword'].value.length()

Without the quotes.

"type" : "class_cast_exception",
"reason" : "Cannot cast from [double] to [long]."

"source": """
double msglen = doc['message.keyword'].value.length();
long msgcast = (double) msglen;
return (long) msgcast;
"""

What is the goal of the script? The type of doc['message.keyword'].value.length() is int, it can be returned directly.

Check out the painless docs on casting for more details.