# Scripted Fields (String Length) Not So Painless

**URL:** <https://discuss.elastic.co/t/scripted-fields-string-length-not-so-painless/198315>\
**Category:** Kibana\
**Tags:** painless\
**Created:** [September 5, 2019, 8:25pm UTC](https://discuss.elastic.co/t/scripted-fields-string-length-not-so-painless/198315 "2019-09-05T20:25:52Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jchivian](https://avatars.discourse-cdn.com/v4/letter/j/838e76/32.png) [@jchivian](https://discuss.elastic.co/u/jchivian)\
**Post date:** [September 5, 2019, 8:25pm UTC](https://discuss.elastic.co/t/scripted-fields-string-length-not-so-painless/198315/1 "2019-09-05T20:25:52Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![tylersmalley](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/tylersmalley/32/8833_2.png) [@tylersmalley](https://discuss.elastic.co/u/tylersmalley)\
**Post date:** [September 5, 2019, 9:04pm UTC](https://discuss.elastic.co/t/scripted-fields-string-length-not-so-painless/198315/2 "2019-09-05T21:04:25Z")

</div>

I believe the type has to be a keyword.

This is what worked in my testing:

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

return -1

```

```auto
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"
      }
    }
  }
}

```

---

<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:** [October 3, 2019, 9:04pm UTC](https://discuss.elastic.co/t/scripted-fields-string-length-not-so-painless/198315/3 "2019-10-03T21:04:28Z")

</div>

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