2

I have array of strings in one field "strArray":

strArray: ['browser:IE', 'device:PC', 'country:USA', 'state:CA']

I need do aggregations by browser (device, country or state). It's not a problem, if I know order of these values in strArray field.

I could to use those structure:

"aggs": {
  "deviceAggs": {
    "terms": {
      "script": "doc['strArray'][1]"
    }
  }
}

But problem is that order of inserting these strings can be different.

How can I do this ? I think about several ways:

  1. Scripting - use function like as substring and get only "correct" values.

  2. Filtering - it's possible to filter one value (which contains string "device:") from array.

  3. Sorting strArray values to put all values in definite order, but "sort" give me strange result - return only one element (without any filtering).

Don't ask me, why I have this structure (this is not my choice), if we have structure key: value - we would not have problems.

yAnTar
  • 4,269
  • 9
  • 47
  • 73

1 Answers1

3

Scripting is only directly possible here. To get an idea on how to use scripting in aggregations, you can refer this blog.

Something like below should work

for(element in doc['strArray'].values){
      if(element.startsWith('browser')){
          return element;
      }
};
return null;

Both sorting and filtering is done on document level and not element level. On element level if you can make this array as nested , filtering is possible. That is first you need to change the structure to -

strArray: [
  { "name" : 'browser:IE' } , 
  { "name" : 'device:PC' } 
 ]

And then make the strArray field as nested. In that case you can do a nested filter based on prefix query ( Using query filter ) and then , do a nested aggregation on the data.

yAnTar
  • 4,269
  • 9
  • 47
  • 73
Vineeth Mohan
  • 18,633
  • 8
  • 63
  • 77
  • Thank you very much. You script works. You saved me hours of my work. Also you can fix "returns" to "return" and add semicolon before return null, because I use this script in one line and without semicolon script is failed. One more time thank you. – yAnTar Aug 28 '15 at 14:34