0
0
ElasticsearchHow-ToBeginner · 3 min read

How to Use Min and Max Aggregation in Elasticsearch

In Elasticsearch, use the min and max aggregations inside an aggs clause to find the smallest and largest values of a numeric field. These aggregations return the minimum or maximum value found in the documents matching your query.
📐

Syntax

The min and max aggregations are used inside the aggs section of a search request. You specify the field to aggregate on. The structure looks like this:

  • aggs: The aggregation container.
  • min or max: The aggregation type.
  • field: The numeric field to find the minimum or maximum value.
json
{
  "aggs": {
    "min_value": {
      "min": {
        "field": "your_numeric_field"
      }
    },
    "max_value": {
      "max": {
        "field": "your_numeric_field"
      }
    }
  }
}
💻

Example

This example shows how to find the minimum and maximum price from a list of products indexed in Elasticsearch.

json
{
  "size": 0,
  "aggs": {
    "min_price": {
      "min": {
        "field": "price"
      }
    },
    "max_price": {
      "max": {
        "field": "price"
      }
    }
  }
}
Output
{ "aggregations": { "min_price": { "value": 5.99 }, "max_price": { "value": 199.99 } } }
⚠️

Common Pitfalls

Common mistakes when using min and max aggregations include:

  • Using a non-numeric field, which causes the aggregation to fail.
  • Not setting size to 0 when you only want aggregation results, which returns unnecessary hits.
  • Misnaming the aggregation keys, which can cause confusion when reading results.
json
{
  "size": 10,  
  "aggs": {
    "max_price": {
      "max": {
        "field": "price"
      }
    }
  }
}

// Better:
{
  "size": 0,
  "aggs": {
    "max_price": {
      "max": {
        "field": "price"
      }
    }
  }
}
📊

Quick Reference

AggregationPurposeField TypeNotes
minFinds the smallest valueNumericUse inside aggs; returns single value
maxFinds the largest valueNumericUse inside aggs; returns single value

Key Takeaways

Use min and max aggregations inside aggs to find smallest and largest numeric values.
Always set size to 0 if you only want aggregation results to avoid unnecessary data.
Ensure the field used is numeric; otherwise, the aggregation will fail.
Aggregation results are returned under the keys you define in the aggs section.