0

How does one perform a complex calculation in ElasticSearch which requires finding the maximum and minimum values across an entry in an index?

The following example is silly, but for illustration it serves the purpose.

Given an object User which is being saved to an index:

class User {
   String name
   int age;
}

the requirement is, for all users with the same name, to get the difference between the youngest and oldest age.

For instance, given the following data set:

Name    Age
Tom     20
Tom     35
Tom     45
Sam     10
Sam     50
Sam     90

the calculation would yield the following results:

Tom = (45-20) = 25
Sam = (90-10) = 80

Having calculated the values in ElasticSearch, they then need to be accessible within Kibana.

I'm new to ElasticSearch, and any code examples are very much appreciated.

user1052610
  • 4,440
  • 13
  • 50
  • 101

1 Answers1

0

You can get min and max per user , then the rest you need to do from the client side -

{
  "aggs": {
    "users": {
      "terms": {
        "field": "Name"
      },
      "aggs": {
        "maxAge": {
          "max": {
            "field": "age"
          }
        },
        "minAge": {
          "min": {
            "field": "age"
          }
        }
      }
    }
  }
}

Here , you need to make a bucket per name using terms aggregation. Per bucket , you need to get max and min value using max and min aggregation.

Rest you need to take care on the client side.

Vineeth Mohan
  • 18,633
  • 8
  • 63
  • 77