6

Is there a way to dynamically add fields using scripts? I am running a script that checks whether a field exists. If not then creates it.

I'm trying out:

script: 'if (ctx._source.attending == null) { ctx._source.attending = { events: newField } } else if (ctx._source.attending.events == null) { ctx._source.attending.events = newField } else { ctx._source.attending.events += newField }'

Except unless I have a field in my _source explicitly named attending in my case, I get:

[Error: ElasticsearchIllegalArgumentException[failed to execute script];
nested: PropertyAccessException[
    [Error: could not access: attending; in class: java.util.LinkedHashMap]

2 Answers 2

17

To check whether a field exists use the ctx._source.containsKey function, e.g.:

curl -XPOST "http://localhost:9200/myindex/message/1/_update" -d'
{
   "script": "if (!ctx._source.containsKey(\"attending\")) { ctx._source.attending = newField }",
   "params" : {"newField" : "blue" },
   "myfield": "data"
}'
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks will test this out when I get a chance. Is there a site with all the methods like contains and containsKey? If I knew where to look I would tried them.
I'm not aware of any single resource - my info comes from a variety of forums. When I ran into this problem, I eventually decided to store the fields in a separate child document - this seems more robust and simpler.
0

I would consider if it's really necessary to see if the field exists at all. Just apply the new mapping to ES and it will add it if it's required and do nothing if it already exists.

Our system re-applies the mappings on every application startup.

2 Comments

The field exists in the mapping, but it would throw the error regardless
If it was a simple field - then yes, upsert would work. However this looks like an array of values, the script needs to add to the array if it exists or create it if it doesn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.