Elasticsearch Max Aggregation - Syntax, Example, and Tips

Pulse - Elasticsearch Operations Done Right

On this page

Syntax Example Usage Common Issues Best Practices Frequently Asked Questions

The Max Aggregation (max) is a single-value metrics aggregation that computes the maximum value of numeric values extracted from the aggregated documents.

Syntax

{
  "aggs": {
    "max_price": {
      "max": {
        "field": "price"
      }
    }
  }
}

For more details, refer to the official Elasticsearch documentation.

Example Usage

Here's an example of using the Max Aggregation to find the highest price in a product catalog:

GET /products/_search
{
  "size": 0,
  "aggs": {
    "max_price": {
      "max": {
        "field": "price"
      }
    }
  }
}

This query will return the maximum price across all documents in the "products" index.

Common Issues

  1. Missing field: If the specified field doesn't exist in any document, the aggregation will return null.
  2. Non-numeric data: The Max Aggregation only works on numeric fields. Using it on non-numeric fields will result in an error.
  3. Scaled float: When using scaled_float data type, be aware that the max value is calculated on the scaled value, not the original one.

Best Practices

  1. Use the "size": 0 parameter in your search query to improve performance when you only need the aggregation results.
  2. Consider using the missing parameter to specify a default value for documents where the field is missing.
  3. For large datasets, you might want to use sampling or filtering to reduce the amount of data processed.

Frequently Asked Questions

Q: Can I use Max Aggregation on nested fields?
A: Yes, you can use Max Aggregation on nested fields by combining it with a Nested Aggregation.

Q: How does Max Aggregation handle null values?
A: By default, Max Aggregation ignores null values. You can use the missing parameter to specify a value to use for documents that are missing the field.

Q: Can I use script to calculate the max value instead of a field?
A: Yes, you can use a script instead of a field. This allows for more complex calculations before determining the max value.

Q: Is Max Aggregation affected by the search query?
A: Yes, Max Aggregation is calculated only on the documents that match the search query.

Q: How can I get both the max and min values in a single query?
A: You can use both Max and Min Aggregations in the same query, or alternatively, use the Stats Aggregation which provides min, max, sum, count, and avg in one go.

Subscribe to the Pulse Newsletter

Get early access to new Pulse features, insightful blogs & exclusive events , webinars, and workshops.