Count array size in all document

Hi all and sorry for my poor english
I have a document like

{
 
"uuid": "SkDHvXr9ES",
 
"userRole": "9qvfWg3isp",

"devices":[

{"uuid": "hwb258pc7x", "macAddress":["9DGSsuAX4M", "ChypSa8tWx", "fIWrArQyDA", "PQjcvOkHYh",…},

{"uuid": "NpfJtvNYiQ", "macAddress":["Jj3zHklLQF", "pYbovxzI29", "Ic8wgRa_eE", "eLYktPz2Js",…},

{"uuid": "kGLJzGdgft", "macAddress":["XT7BUrUm5q", "OQNpRg7oRk", "9khaKN_3OV", "7wrWWlG51z",…},

{"uuid": "_yUh1Icaex", "macAddress":["xJ1MkTj10D", "j5YJhOQjZF", "EVVN2A4Di8", "2yysRuUTfp",…},

{"uuid": "thDqf3yKJw", "macAddress":["X233a9UN8p", "uGwxy38nWW", "3zAPY_P5QK", "z7pDSzf1Dl",…}

]

 

}

and I like to count length of devices array for all documents.

It would be much better to do that at index time and index something like:

{
  "uuid": "SkDHvXr9ES",
  "userRole": "9qvfWg3isp",
  "devices_size": 5,
  "devices":[
    {"uuid": "hwb258pc7x", "macAddress":["9DGSsuAX4M", "ChypSa8tWx", "fIWrArQyDA", "PQjcvOkHYh",…}, 
    {"uuid": "NpfJtvNYiQ", "macAddress":["Jj3zHklLQF", "pYbovxzI29", "Ic8wgRa_eE", "eLYktPz2Js",…},
    {"uuid": "kGLJzGdgft", "macAddress":["XT7BUrUm5q", "OQNpRg7oRk", "9khaKN_3OV", "7wrWWlG51z",…},
    {"uuid": "_yUh1Icaex", "macAddress":["xJ1MkTj10D", "j5YJhOQjZF", "EVVN2A4Di8", "2yysRuUTfp",…},
    {"uuid": "thDqf3yKJw", "macAddress":["X233a9UN8p", "uGwxy38nWW", "3zAPY_P5QK", "z7pDSzf1Dl",…}
  ]
}

Ideally, do that from your application.
If you can't, you can think of using a script processor that will process your documents on the fly to modify the _source.

I tried this

{
  "aggs": {
    "type_count": {
      "value_count": {
        "script": {
          "inline": "params._source.containsKey('devices') && params._source['devices'] != null  ? params._source.devices.size() : 0"
        }
      }
    }
  }
}

but it return 1 and not 5
Any idea why?

I think you want a sum agg.

But again I'd change the source.

I found a solution

POST entities/_search
{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "number-of-devices": {
      "script": {
        "source": "params['_source']['devices']!=null ? params['_source']['devices'].length:-1"
      }
    } 
  },
  "size": 10000
}

for all my fans :grinning:

1 Like

But that's not the sum of all. It's "just" per document right?

What I post in title

Ok. I thought you wanted the total.

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