Stats Aggregation

A multi-value metrics aggregation that computes stats over numeric values extracted from the aggregated documents. These values can be extracted either from specific numeric fields in the documents, or be generated by a provided script.

The stats that are returned consist of: min, max, sum, count and avg.

Assuming the data consists of documents representing exams grades (between 0 and 100) of students

  1. POST /exams/_search?size=0
  2. {
  3. "aggs": {
  4. "grades_stats": { "stats": { "field": "grade" } }
  5. }
  6. }

The above aggregation computes the grades statistics over all documents. The aggregation type is stats and the field setting defines the numeric field of the documents the stats will be computed on. The above will return the following:

  1. {
  2. ...
  3. "aggregations": {
  4. "grades_stats": {
  5. "count": 2,
  6. "min": 50.0,
  7. "max": 100.0,
  8. "avg": 75.0,
  9. "sum": 150.0
  10. }
  11. }
  12. }

The name of the aggregation (grades_stats above) also serves as the key by which the aggregation result can be retrieved from the returned response.

Script

Computing the grades stats based on a script:

  1. POST /exams/_search?size=0
  2. {
  3. "aggs": {
  4. "grades_stats": {
  5. "stats": {
  6. "script": {
  7. "lang": "painless",
  8. "source": "doc['grade'].value"
  9. }
  10. }
  11. }
  12. }
  13. }

This will interpret the script parameter as an inline script with the painless script language and no script parameters. To use a stored script use the following syntax:

  1. POST /exams/_search?size=0
  2. {
  3. "aggs": {
  4. "grades_stats": {
  5. "stats": {
  6. "script": {
  7. "id": "my_script",
  8. "params": {
  9. "field": "grade"
  10. }
  11. }
  12. }
  13. }
  14. }
  15. }

Value Script

It turned out that the exam was way above the level of the students and a grade correction needs to be applied. We can use a value script to get the new stats:

  1. POST /exams/_search?size=0
  2. {
  3. "aggs": {
  4. "grades_stats": {
  5. "stats": {
  6. "field": "grade",
  7. "script": {
  8. "lang": "painless",
  9. "source": "_value * params.correction",
  10. "params": {
  11. "correction": 1.2
  12. }
  13. }
  14. }
  15. }
  16. }
  17. }

Missing value

The missing parameter defines how documents that are missing a value should be treated. By default they will be ignored but it is also possible to treat them as if they had a value.

  1. POST /exams/_search?size=0
  2. {
  3. "aggs": {
  4. "grades_stats": {
  5. "stats": {
  6. "field": "grade",
  7. "missing": 0
  8. }
  9. }
  10. }
  11. }

Documents without a value in the grade field will fall into the same bucket as documents that have the value 0.