2

Is there a way to do a "multi value count" aggregation? It would work the same way as the regular value count: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html

But would be used to count multiple fields.

For example we have a mapping:

"properties" : {
        "lastName" : { "type" : "string" },
        "firstName" : { "type" : "string" },
        "age" : { "type" : "string" }
}

And the following 4 docs:

{"lastName":"Smith"}
{"lastName":"Jacobson", "firstName":"Scott"}
{"lastName":"Bush", "age": 68}
{"lastName":"Obama", "firstName":"Barack", "age":53}

I would like to count the number of documents with either an age OR a first name. In my case the aggregation would return 3.

Any idea ? I try a little bit using the script function:

"aggregation_name" : {
  "value_count" : {
    "script" : "doc['age'].value + doc['firstName'].value"
  }
}

but it did't seem to work.

Thanks!

1 Answer 1

1

You can achieve this using filter aggregation and Exists filter -

{
  "aggs": {
    "CountSpec": {
      "filter": {
        "bool": {
          "should": [
            {
              "exists": {
                "field": "age"
              }
            },
            {
              "exists": {
                "field": "firstName"
              }
            }
          ]
        }
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I managed to achieve what I wanted with: "count_name" : { "value_count" : { "script" : "if(doc.containsKey('age') || doc.containsKey('firstName')) { 1 }" } } Any idea what would be best : the filter aggregation or the value aggregation with a script ?
Certainly filter approach. Scripts are CPU intensive and filters are natively build. More importantly scripts have filter cache which means that the execution would be much faster once its cached

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.