top_selling_products aggregation?{
"size": 0,
"aggs": {
"top_selling_products": {
"terms": {
"field": "product.keyword",
"size": 3
},
"aggs": {
"total_sales": {
"sum": {
"field": "sales"
}
}
}
}
}
}terms aggregation orders buckets by document count by default, but nested sum aggregation calculates total sales.The terms aggregation groups documents by product keyword and returns the top 3 terms by document count by default. However, the nested sum aggregation total_sales calculates the sum of the sales field for each product bucket. The output shows the top 3 products by document count, each with their total sales sum.
Pipeline aggregations operate on the output of other aggregations, allowing you to compute metrics like moving averages, derivatives, or cumulative sums. This is crucial in production for advanced analytics and trend detection.
{
"size": 0,
"aggs": {
"categories": {
"terms": {
"field": "category.keyword"
},
"aggs": {
"avg_rating": {
"avg": {
"field": "rating"
}
}
}
}
}
}If the field category.keyword does not exist or is not mapped as a keyword, the terms aggregation will fail. This is a common cause of aggregation errors.
In painless scripting, document fields must be accessed as doc['fieldname'].value. Option A correctly uses this syntax in the map_script. Option A misses the brackets, C misses .value, and D is a duplicate of A but with a subtle difference in spacing (which is valid but option A is canonical).
Using a date_histogram aggregation groups sales by day, and the moving_avg pipeline aggregation computes the moving average on these daily sums efficiently within Elasticsearch. This approach leverages Elasticsearch's aggregation framework and is scalable for production.