0
0
Elasticsearchquery~5 mins

Metric aggregations (avg, sum, min, max) in Elasticsearch

Choose your learning style9 modes available
Introduction

Metric aggregations help you quickly find numbers like averages, totals, smallest, or biggest values in your data.

You want to know the average price of products in your store.
You need the total sales amount for a month.
You want to find the cheapest or most expensive item in a list.
You want to summarize data like total clicks or minimum response time.
Syntax
Elasticsearch
{
  "aggs": {
    "aggregation_name": {
      "avg" : {
        "field": "field_name"
      }
    }
  }
}

Replace aggregation_name with any name you choose to identify the result.

Choose one metric type: avg, sum, min, or max.

Examples
This finds the average value of the price field.
Elasticsearch
{
  "aggs": {
    "average_price": {
      "avg": {
        "field": "price"
      }
    }
  }
}
This calculates the total sum of the sales field.
Elasticsearch
{
  "aggs": {
    "total_sales": {
      "sum": {
        "field": "sales"
      }
    }
  }
}
This finds the smallest value in the age field.
Elasticsearch
{
  "aggs": {
    "min_age": {
      "min": {
        "field": "age"
      }
    }
  }
}
This finds the largest value in the score field.
Elasticsearch
{
  "aggs": {
    "max_score": {
      "max": {
        "field": "score"
      }
    }
  }
}
Sample Program

This query finds the average price, total sales, minimum age, and maximum score from all documents.

Elasticsearch
{
  "query": {
    "match_all": {}
  },
  "aggs": {
    "average_price": {
      "avg": {
        "field": "price"
      }
    },
    "total_sales": {
      "sum": {
        "field": "sales"
      }
    },
    "min_age": {
      "min": {
        "field": "age"
      }
    },
    "max_score": {
      "max": {
        "field": "score"
      }
    }
  }
}
OutputSuccess
Important Notes

If a field has no values, the aggregation result will be null.

You can combine multiple metric aggregations in one query to get many results at once.

Summary

Metric aggregations calculate numbers like average, sum, min, and max from your data.

Use them to quickly understand key statistics in your Elasticsearch documents.

You write them inside the aggs part of your query with the field name.