1

I'm trying to store the number of elements of an array into a field with an update. (updating the record with the count of the array).

Like for example

{
  array = [ { "a" : "b" }, { "c" : "d" } ]
  nb_elements = 2
}

I have tried an update with the following script

{
  "script" : "ctx._source.nb_elements= ctx._source.array.values.length"
}

But it don't work. I also tried :

{
"script" : "ctx._source.nb_elements = count",
"params" : {
   "count" : ctx._source.array.values.length
   }
}

But i wasn't more successfull.

Does anybody know if this is possible and if, how to do it ?

1 Answer 1

1

First of all you need to enable dynamic scripting by adding script.disable_dynamic: false to your config file.

Secondly, I'm supposing that you are using groovy (It's the default scripting language from 1.4).

Using the update api with this script should work:

{
  "script": "ctx._source.nb_elements=ctx._source.array.size"
}
Sign up to request clarification or add additional context in comments.

4 Comments

It works , thank you. Where did you find this information ?
I've put some links to the documentation in the answer :) I've also checked this answer: stackoverflow.com/questions/24711168/…
Ok, for reenabling the dynamic scripting, but where did you find that i had to use size rather than count or length (i can find nothing about that).
Well, I have no idea about groovy, but I know it is a JVM language and collection classes tend to have size method in Java. So, it was a bit of intuition. If you have doubts about the language you can check its documentation: groovy-lang.org/documentation.html

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.