Scripted Fields (String Length) Not So Painless

I'm trying to generate a scripted field to be the string length of an event field. I've tried more variants of...

if (doc.containsKey('msg')) {
def msg_length = doc['msg'].value.size(); * or value.length()
return msg_length;
} else {
return -1;
}

...that I can even count and am having difficulty understanding why what appears so simple doesn't work. I know I must be missing something fundamental about the language or data typing so any nudge or outright shove in the right direction is MUCH appreciated.

Note... any text field example will work, it doesn't have to be the "msg" object.

Thanks in advance!

I believe the type has to be a keyword.

This is what worked in my testing:

if (doc.containsKey('msg.keyword')) {
  return doc['msg.keyword'].value.length()
} 

return -1

PUT discuss-198315

POST discuss-198315/_doc
{
  "msg": "foo"
}

POST discuss-198315/_doc
{
  "msg": "bar"
}

POST discuss-198315/_doc
{
  "msg": "baz"
}

POST discuss-198315/_doc
{
  "msg": "quux"
}

POST discuss-198315/_doc
{}

GET discuss-198315/_search
{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "msg-length": {
      "script": {
        "lang": "painless",
        "source": "if (doc.containsKey('msg.keyword')) { return doc['msg.keyword'].value.length()} return -1"
      }
    }
  }
}
1 Like

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