Combining Aggregations
One of the powerful features of Elasticsearch is the ability to combine multiple aggregations together to perform complex analytics. This allows you to gain deeper insights into your data.
Example: Calculating Average Price by Category
Suppose we want to calculate the average price of products in each category. We can combine the terms aggregation with the average aggregation to achieve this.
GET /products/_search
{
"aggs": {
"categories": {
"terms": {
"field": "category.keyword"
},
"aggs": {
"avg_price": {
"avg": {
"field": "price"
}
}
}
}
}
}
Output:
{
"aggregations": {
"categories": {
"buckets": [
{
"key": "electronics",
"doc_count": 5,
"avg_price": {
"value": 75.5
}
},
{
"key": "clothing",
"doc_count": 3,
"avg_price": {
"value": 30.0
}
},
{
"key": "books",
"doc_count": 2,
"avg_price": {
"value": 20.0
}
}
]
}
}
}
In this example, we calculate the average price of products in each category.
Elasticsearch Aggregations
Elasticsearch is not just a search engine; it’s a powerful analytics tool that allows you to gain valuable insights from your data. One of the key features that make Elasticsearch so powerful is its ability to perform aggregations.
In this article, we’ll explore Elasticsearch aggregations in detail, explaining what they are, how they work, and providing examples with outputs to help you understand them better.