# Creating a new field through painless scripts

**URL:** <https://discuss.elastic.co/t/creating-a-new-field-through-painless-scripts/202251>\
**Category:** Kibana\
**Tags:** painless\
**Created:** [October 3, 2019, 10:04pm UTC](https://discuss.elastic.co/t/creating-a-new-field-through-painless-scripts/202251 "2019-10-03T22:04:41Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![maheshamruthaluri](https://avatars.discourse-cdn.com/v4/letter/m/3ec8ea/32.png) [@maheshamruthaluri](https://discuss.elastic.co/u/maheshamruthaluri)\
**Post date:** [October 3, 2019, 10:04pm UTC](https://discuss.elastic.co/t/creating-a-new-field-through-painless-scripts/202251/1 "2019-10-03T22:04:41Z")

</div>

Hello,  
I am trying to create a new field based on a particular condition.  
`if (doc['foo.keyword'].value == 'bar'){ doc['foo2.keyword'].value = 'bar2' }`  
But it gives my an error saying **Script is invalid. View script preview for details**

---

<div class="post-metadata">

**Author:** ![flash1293](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/flash1293/32/41227_2.png) [@flash1293](https://discuss.elastic.co/u/flash1293)\
**Post date:** [October 7, 2019, 7:10am UTC](https://discuss.elastic.co/t/creating-a-new-field-through-painless-scripts/202251/2 "2019-10-07T07:10:17Z")

</div>

Hi @maheshamruthaluri,

the way scripted fields work is that you provide a script which returns a value that becomes the value of the field.

If you want to only set `foo2.keyword` to `'bar2'` if `foo.keyword` equals `'bar'`, you have to create a scripted field with the name `foo2.keyword` and use the following script:

```auto
if (doc['foo.keyword'].value == 'bar'){ return 'bar2'; }

```

If the condition is not met, the field value is simply undefined

---

<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:** [November 4, 2019, 7:10am UTC](https://discuss.elastic.co/t/creating-a-new-field-through-painless-scripts/202251/3 "2019-11-04T07:10:17Z")

</div>

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