Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 477
Maruf Avatar asked Nov 17 '14 15:11

Maruf


People also ask

How do I add a scripted field?

Create scripted fieldsedit Select the data view you want to add a scripted field to. Select the Scripted fields tab, then click Add scripted field. Enter a Name for the scripted field, then enter the Script you want to use to compute a value on the fly from your index data. Click Create field.

What is CTX in Elasticsearch?

ctx is a special variable that allows you to access the source of the object that you want to update. The ctx. _source is a writable version of the source . NOTE: You can modify this document in the script and the modified source will be persisted as the new version of the document.

How do I write a script in Elasticsearch?

Wherever scripting is supported in the Elasticsearch APIs, the syntax follows the same pattern; you specify the language of your script, provide the script logic (or source), and add parameters that are passed into the script: "script": { "lang": "...", "source" | "id": "...", "params": { ... } }

What is painless script in Elasticsearch?

Painless is a simple, secure scripting language designed specifically for use with Elasticsearch. It is the default scripting language for Elasticsearch and can safely be used for inline and stored scripts.


1 Answers

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"
}'
like image 193
Olly Cruickshank Avatar answered Nov 15 '22 11:11

Olly Cruickshank