Q:

Return only one element from strings array in elasticsearch

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:

Scripting - use function like as substring and get only "correct" values.
Filtering - it's possible to filter one value (which contains string "device:") from array.
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.

A:

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.

