0
0
ElasticsearchHow-ToBeginner · 3 min read

How to Use avg Aggregation in Elasticsearch

Use the avg aggregation in Elasticsearch to calculate the average of a numeric field across matching documents. Define it inside the aggs section of your query with the field name you want to average.
📐

Syntax

The avg aggregation calculates the average value of a numeric field. It is placed inside the aggs part of your search query.

Key parts:

  • aggs: Defines aggregations.
  • avg_name: A name you give to this aggregation.
  • avg: The aggregation type.
  • field: The numeric field to average.
json
{
  "aggs": {
    "avg_name": {
      "avg": {
        "field": "numeric_field"
      }
    }
  }
}
💻

Example

This example calculates the average price of products in an Elasticsearch index called products. It returns the average price value.

json
{
  "size": 0,
  "aggs": {
    "average_price": {
      "avg": {
        "field": "price"
      }
    }
  }
}
Output
{ "aggregations": { "average_price": { "value": 23.45 } } }
⚠️

Common Pitfalls

Common mistakes when using avg aggregation include:

  • Using a non-numeric field, which causes no results or errors.
  • Not setting size to 0 when only aggregation results are needed, which returns unnecessary documents.
  • Misnaming the aggregation or field, leading to empty results.
json
{
  "size": 10,
  "aggs": {
    "avg_price": {
      "avg": {
        "field": "price"
      }
    }
  }
}

// Better way:
{
  "size": 0,
  "aggs": {
    "avg_price": {
      "avg": {
        "field": "price"
      }
    }
  }
}
📊

Quick Reference

Tips for using avg aggregation:

  • Always use a numeric field.
  • Set size to 0 if you only want aggregation results.
  • Name your aggregation clearly for easy access in results.
  • Combine with filters to average specific subsets.

Key Takeaways

Use avg inside aggs to calculate average of a numeric field.
Set size to 0 to avoid returning documents when only aggregation results are needed.
Ensure the field used is numeric to get valid average results.
Name your aggregation to easily find the average value in the response.
Combine avg with filters to calculate averages on specific data subsets.