Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum array length elasticsearch

I've got indexed documents that look like this:

{
  "fun_field": [...]
}

I'd very much like to sum the array lengths to get the total number of elements in all fun_field arrays. I've been trying lots of combinations and haven't been able to get it to work.

Does anyone speak the cryptic elasticsearch dialect fluently enough to describe what I'm asking?

like image 507
Eric Fulton Avatar asked Sep 15 '26 08:09

Eric Fulton


2 Answers

Well I found a roundabout way of answering this question without using scripts.

{
    "size": 0,
    "aggs" : {
        "outer_agg" : { 
            "nested" : { 
                "path" : "elements"   
            },
            "aggs": {
                "inner_agg": {
                    "top_hits": {
                        "from": 0,
                        "size": 1
                    }
                }
            }
        }
    }
}

This will return a doc_count which is what I'm looking for. ES's DSL will be the death of me.

like image 162
Eric Fulton Avatar answered Sep 17 '26 09:09

Eric Fulton


You can define your own scripts for aggregations (or script_fields), such that they're already summing the array up before the aggregation happens. Syntax may vary for different scripting languages but for Painless in Elasticsearch 5. You'll also need to enable inline scripts.

"aggs": {
  "array_sums" : {
    "sum": {
       "script": {
         "lang": "painless",
         "inline": "doc['fun_field'].length"
       }
    }
  }
}

There are other scripting languages, you can read about them here. There are some examples of scripts in aggregations here.

like image 41
Ho Man Avatar answered Sep 17 '26 09:09

Ho Man



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!