简体   繁体   中英

Elasticsearch - Create field using script if doesn't exist

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]

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

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"
}'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM