Compare elements in array

Hi,

I am trying to create new script field.

def pages = new ArrayList();
if(doc['formular.pages'].length > 1) {
for(int i = 0; i < doc['formular.pages'].length - 1; i++) {
if(doc['formular.pages'][i] > doc['formular.pages'][i + 1]) {
pages.add(doc['formular.pages'][i]);
}
}
}else{
pages.add(0);
}
return pages;

It seems to be that it is not possible to access element in array using [i + 1].
Any idea how i can resolve this issue?

Hey @aleksa what error are you getting when trying to use this scripted field? Also, which version of Kibana/Elasticsearch are you using?

Hi,
im using Version 6.2. There is no error message, however, when if statement (if(doc['formular.pages'][i] > doc['formular.pages'][i + 1])) is true no new scripted field is added, only when the statement is false, a new field with 0 is added.

I also tried to rewrite this script:
def pages = new ArrayList();
def j;
if(doc['formular.pages'].length > 1) {
for(int i = 0; i < doc['formular.pages'].length - 1;) {
j = i;
++i;
if(doc['formular.pages'][i] < doc['formular.pages'][j]){
pages.add(doc['formular.pages'][j]);
}
}
}else{
pages.add(0);
}
return pages;

It does not work as well.

@aleksa I believe that you're running into an issue with the way that Elasticsearch indexes and orders arrays. If you query your index for only the formular.pages you'll always see the pages always returned in order.

If you'd like to get the formular.pages in the original order when they were indexed, you can use the params._source.formular.pages to access this and use it throughout your script:

def output = new ArrayList();
def input = params._source.formular.pages;
if(input.length > 1) {
  for(int i = 0; i < input.length - 1; i++) {
    if(input[i] > input[i + 1]) {
      output.add(input[i]);
   }
  }
} else {
  output.add(0);
}

return output;

Thank you. It works now.

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