3

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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Any document to explain what those fields mean?
3

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.

3 Comments

I get the following error, but also If I'm reading that script right, it's adding together the values in the arrays. I the sum of the array sizes, not the sum of the values in the arrays. "script_stack": [ "org.elasticsearch.search.lookup.LeafDocLookup.get(LeafDocLookup.java:80)", "doc['fun_field'].length", " ^---- HERE" ],
(Scroll to the right of that code) From 0 -> length of that field, it adds the value of that element into total. Which is then used again in the aggregation. Please check the version of elasticsearch, and whether you've enabled inline scripts
Oh. I just realised you wanted the array LENGTH lol, that is even easier!
1

The accepted solution didn't work for me, but I was able to get the same answer as as the scripted version by Ho Man without any scripted fields.

{
    "size": 0,
    "aggs" : {
        "row_count" : { 
            "value_count": {
                "field": "fun_field.keyword"
            }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.