### Example Composite Aggregation Sources Source: https://docs.opensearch.org/latest/aggregations/bucket/composite This example shows how to define sources for a composite aggregation, using terms aggregation on 'city' and 'place' fields. ```json "sources": [ { "marathon_city": { "terms": { "field": "city" }}}, { "participant_medal": { "terms": { "field": "place" }}} ], ... ``` -------------------------------- ### Stats Aggregation Response Example Source: https://docs.opensearch.org/latest/aggregations/metric/stats Example response showing the computed count, min, max, avg, and sum for the 'kwh' field. ```json { "...": "...", "hits": { "total": { "value": 3, "relation": "eq" }, "max_score": null, "hits": [] }, "aggregations": { "consumption_stats": { "count": 3, "min": 0.699999988079071, "max": 1.5, "avg": 1.1333333452542622, "sum": 3.400000035762787 } } } ``` -------------------------------- ### Multi-terms Aggregation Example Source: https://docs.opensearch.org/latest/aggregations/bucket/multi-terms This example demonstrates how to use the multi_terms aggregation to group documents by 'region' and 'host', and then order the results by the maximum CPU and memory usage. It also includes sub-aggregations to calculate these maximum values. ```json GET sample-index100/_search { "size": 0, "aggs": { "hot": { "multi_terms": { "terms": [ { "field": "region" },{ "field": "host" } ], "order": [ { "max-cpu": "desc" },{ "max-memory": "desc" } ] }, "aggs": { "max-cpu": { "max": { "field": "cpu" } }, "max-memory": { "max": { "field": "memory" } } } } } } ``` -------------------------------- ### Stats Aggregation per Bucket Response Example Source: https://docs.opensearch.org/latest/aggregations/metric/stats Example response showing statistics (count, min, max, avg, sum) computed for each device ID bucket. ```json { "...": "...", "hits": { "total": { "value": 3, "relation": "eq" }, "max_score": null, "hits": [] }, "aggregations": { "per_device": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "A1", "doc_count": 1, "device_usage_stats": { "count": 1, "min": 1.2000000476837158, "max": 1.2000000476837158, "avg": 1.2000000476837158, "sum": 1.2000000476837158 } }, { "key": "A2", "doc_count": 1, "device_usage_stats": { "count": 1, "min": 0.699999988079071, "max": 0.699999988079071, "avg": 0.699999988079071, "sum": 0.699999988079071 } }, { "key": "A3", "doc_count": 1, "device_usage_stats": { "count": 1, "min": 1.5, "max": 1.5, "avg": 1.5, "sum": 1.5 } } ] } } } ``` -------------------------------- ### Truncate and Sort Buckets Source: https://docs.opensearch.org/latest/aggregations/pipeline/bucket-sort Use 'from' and 'size' with 'sort' to paginate through sorted buckets. This example returns two buckets, starting from the second bucket, sorted by 'total_bytes' in descending order. ```json GET opensearch_dashboards_sample_data_logs/_search { "size": 0, "aggs": { "sales_per_month": { "date_histogram": { "field": "@timestamp", "calendar_interval": "month" }, "aggs": { "total_bytes": { "sum": { "field": "bytes" } }, "bytes_bucket_sort": { "bucket_sort": { "sort": [ { "total_bytes": { "order": "desc" } } ], "from": 1, "size": 2 } } } } } } ``` -------------------------------- ### Field Collapsing with Top Hits Aggregation Source: https://docs.opensearch.org/latest/aggregations/metric/top-hits This example demonstrates how to group search results by manufacturer and retrieve the top product from each group. It uses a terms aggregation to group by 'manufacturer.keyword' and a top_hits aggregation to get the most relevant product within each manufacturer group. A max aggregation is used to order the manufacturer buckets by the highest score. ```json GET /opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, "query": { "match": { "products.product_name": "shirt" } }, "aggs": { "top_manufacturers": { "terms": { "field": "manufacturer.keyword", "size": 3, "order": { "top_score": "desc" } }, "aggs": { "top_hits_per_manufacturer": { "top_hits": { "_source": { "includes": ["products.product_name", "manufacturer"] }, "size": 1 } }, "top_score": { "max": { "script": { "source": "_score" } } } } } } } ``` -------------------------------- ### Moving Average Calculation Example Source: https://docs.opensearch.org/latest/aggregations/pipeline/moving-avg Illustrates how a moving average is calculated with a window size of 5 on a sample dataset. ```text (1 + 5 + 8 + 23 + 34) / 5 = 14.2 (5 + 8 + 23 + 34 + 28) / 5 = 19.6 (8 + 23 + 34 + 28 + 7) / 5 = 20 and so on ... ``` -------------------------------- ### Nested Aggregation Response Example Source: https://docs.opensearch.org/latest/aggregations This is an example response for a nested aggregation query, showing buckets for each category with document counts and calculated average prices. ```json { "took" : 22, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : { "value" : 4675, "relation" : "eq" }, "max_score" : null, "hits" : [ ] }, "aggregations" : { "categories" : { "doc_count_error_upper_bound" : 0, "sum_other_doc_count" : 572, "buckets" : [ { "key" : "Women's Shoes", "doc_count" : 1136, "avg_price" : { "value" : 92.8513836927817 } }, { "key" : "Women's Clothing", "doc_count" : 1903, "avg_price" : { "value" : 70.99312352207042 } }, { "key" : "Women's Accessories", "doc_count" : 830, "avg_price" : { "value" : 73.28953313253012 } }, { "key" : "Men's Shoes", "doc_count" : 944, "avg_price" : { "value" : 97.24356130826271 } }, { "key" : "Men's Clothing", "doc_count" : 2024, "avg_price" : { "value" : 73.81122043292984 } } ] } } } ``` -------------------------------- ### Example Aggregation Structure Source: https://docs.opensearch.org/latest/aggregations/pipeline/index An example of a nested aggregation structure with a parent and child aggregation. ```json { "aggs": { "parent_agg": { "terms": { "field": "category" }, "aggs": { "child_agg": { "stats": { "field": "price" } } } } } } ``` -------------------------------- ### Stats Aggregation Response Example Source: https://docs.opensearch.org/latest/aggregations/metric/stats Example response of the stats aggregation, showing computed values for count, min, max, avg, and sum. ```json { "...", "hits": { "total": { "value": 3, "relation": "eq" }, "max_score": null, "hits": [] }, "aggregations": { "usage_wh_stats": { "count": 3, "min": 699.999988079071, "max": 1500, "avg": 1133.3333452542622, "sum": 3400.000035762787 } } } ``` -------------------------------- ### Composite Aggregation Response Example Source: https://docs.opensearch.org/latest/aggregations/bucket/composite This is an example response from a composite aggregation query. It shows the structure of the results, including the 'after_key' for pagination and the 'buckets' with their respective keys and calculated subaggregation values. ```json { "took": 30, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 4675, "relation": "eq" }, "max_score": null, "hits": [] }, "aggregations": { "composite_buckets": { "after_key": { "weekday": "Saturday", "gender": "MALE" }, "buckets": [ { "key": { "weekday": "Friday", "gender": "FEMALE" }, "doc_count": 399, "avg_spend": { "value": 71.7733395989975 } }, { "key": { "weekday": "Friday", "gender": "MALE" }, "doc_count": 371, "avg_spend": { "value": 79.72514108827494 } }, { "key": { "weekday": "Monday", "gender": "FEMALE" }, "doc_count": 320, "avg_spend": { "value": 72.1588623046875 } }, { "key": { "weekday": "Monday", "gender": "MALE" }, "doc_count": 259, "avg_spend": { "value": 86.1754946911197 } }, { "key": { "weekday": "Saturday", "gender": "FEMALE" }, "doc_count": 365, "avg_spend": { "value": 73.53236301369863 } }, { "key": { "weekday": "Saturday", "gender": "MALE" }, "doc_count": 371, "avg_spend": { "value": 72.78092360175202 } } ] } } } ``` -------------------------------- ### Example response for value count aggregation Source: https://docs.opensearch.org/latest/aggregations/metric/value-count This is an example of the response structure when using the value_count aggregation, showing the total count for the specified field. ```json { "aggregations" : { "number_of_values" : { "value" : 4675 } } } ``` -------------------------------- ### Moving Average Aggregation Example Source: https://docs.opensearch.org/latest/aggregations/pipeline/moving-avg This example shows how to use the moving average aggregation to calculate the average of a sum of bytes over a specified window. It requires a preceding aggregation that produces numeric values. ```json { "key": 1751241600000, "doc_count": 0, "moving_avg_of_sum_of_bytes": { "value": 8297293.6 } } ``` -------------------------------- ### Index Sample Documents Source: https://docs.opensearch.org/latest/aggregations/bucket/auto-interval-date-histogram Documents are indexed with a 'date_posted' field. This setup is necessary before running aggregations. ```json PUT blogs1/_doc/1 { "name": "Semantic search in OpenSearch", "date_posted": "2022-04-17T01:00:00.000Z" } ``` ```json PUT blogs1/_doc/2 { "name": "Sparse search in OpenSearch", "date_posted": "2022-04-17T04:00:00.000Z" } ``` -------------------------------- ### Moving Function Aggregation Example Source: https://docs.opensearch.org/latest/aggregations/pipeline/moving-function This example demonstrates a moving function aggregation to calculate a 5-day moving average of sales. It uses a histogram aggregation on dates and applies a script to compute the average within a sliding window. ```json { "query": { "bool": { "filter": [ { "range": { "@timestamp": { "gte": "now-90d/d", "lt": "now/d" } } } ] } }, "aggs": { "sales_over_time": { "date_histogram": { "field": "@timestamp", "fixed_interval": "1d", "min_doc_count": 0 }, "aggs": { "moving_avg_sales": { "moving_fn": { "buckets_path": "_count", "script": { "source": "MovingFunctions.DOC_COUNT.moving_average(values)", "lang": "painless" }, "window": 5 } } } } } } ``` -------------------------------- ### Nested Aggregation Response Example Source: https://docs.opensearch.org/latest/aggregations/bucket/nested This is an example of the response structure returned by OpenSearch after executing a nested aggregation query. It shows the document count and the calculated minimum load time. ```json "hits": { "total": { "value": 1, "relation": "eq" }, "max_score": 1, "hits": [ { "_index": "logs-nested", "_id": "0", "_score": 1, "_source": { "response": "200", "pages": [ { "page": "landing", "load_time": 200 }, { "page": "blog", "load_time": 500 } ] } } ] }, "aggregations": { "pages": { "doc_count": 2, "min_load_time": { "value": 200 } } } ``` -------------------------------- ### Calculate Maximum Monthly Bytes Source: https://docs.opensearch.org/latest/aggregations/pipeline/max-bucket This example demonstrates how to find the maximum sum of bytes per month using date_histogram and sum aggregations, followed by a max_bucket aggregation. ```json POST opensearch_dashboards_sample_data_logs/_search { "size": 0, "aggs": { "visits_per_month": { "date_histogram": { "field": "@timestamp", "interval": "month" }, "aggs": { "sum_of_bytes": { "sum": { "field": "bytes" } } } }, "max_monthly_bytes": { "max_bucket": { "buckets_path": "visits_per_month>sum_of_bytes" } } } } ``` -------------------------------- ### Buckets Path Mapping Example Source: https://docs.opensearch.org/latest/aggregations/pipeline/bucket-script Maps script variable names to bucketed metrics for use in scripts. 'total_sales' is mapped to the 'sales_sum' metric, and 'item_count' to the 'item_count' metric. ```json { "buckets_path": { "total_sales": "sales_sum", "item_count": "item_count" } } ``` -------------------------------- ### Field Collapsing Aggregation Example Source: https://docs.opensearch.org/latest/aggregations/metric/top-hits This snippet demonstrates how to configure a field collapsing aggregation to group documents by 'product_name'. It shows the structure of the aggregation request. ```json { "aggregations": { "collapsed_docs": { "collapse": { "field": "product_name" }, "aggregations": { "top_tags": { "top_hits": { "size": 1, "_source": [ "product_name" ] } } } } } } ``` -------------------------------- ### Terms Aggregation Response Source: https://docs.opensearch.org/latest/aggregations/bucket/composite This is an example response from a terms aggregation query. It shows the composite buckets, including the `after_key` for pagination and the `doc_count` for each bucket. ```json { "took": 51, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 4675, "relation": "eq" }, "max_score": null, "hits": [] }, "aggregations": { "composite_buckets": { "after_key": { "day": "Monday", "gender": "MALE" }, "buckets": [ { "key": { "day": "Friday", "gender": "FEMALE" }, "doc_count": 399 }, { "key": { "day": "Friday", "gender": "MALE" }, "doc_count": 371 }, { "key": { "day": "Monday", "gender": "FEMALE" }, "doc_count": 320 }, { "key": { "day": "Monday", "gender": "MALE" }, "doc_count": 259 } ] } } } ``` -------------------------------- ### Aggregation Response Example Source: https://docs.opensearch.org/latest/aggregations Shows the structure of a response containing aggregation results, specifically the calculated average value. ```json { "took" : 1, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : { "value" : 4675, "relation" : "eq" }, "max_score" : null, "hits" : [ ] }, "aggregations" : { "avg_taxful_total_price" : { "value" : 75.05542864304813 } } } ``` -------------------------------- ### Example aggregation response Source: https://docs.opensearch.org/latest/aggregations/bucket/terms The aggregation response shows the 'doc_count' for each bucket, which is the sum of '_doc_count' from documents matching that bucket's key. ```json { "took" : 20, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : { "value" : 3, "relation" : "eq" }, "max_score" : null, "hits" : [ ] }, "aggregations" : { "response_codes" : { "doc_count_error_upper_bound" : 0, "sum_other_doc_count" : 0, "buckets" : [ { "key" : 200, "doc_count" : 300 }, { "key" : 404, "doc_count" : 30 } ] } } } ``` -------------------------------- ### Average Aggregation within a Filter Source: https://docs.opensearch.org/latest/aggregations/bucket/filter This example demonstrates how to use a filter aggregation with a range query to calculate the average of 'taxful_total_price' for documents where the price is less than or equal to 50. ```json GET opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, "aggs": { "low_value": { "filter": { "range": { "taxful_total_price": { "lte": 50 } } }, "aggs": { "avg_amount": { "avg": { "field": "taxful_total_price" } } } } } } ``` -------------------------------- ### Paginate Composite Aggregation with 'after' Parameter Source: https://docs.opensearch.org/latest/aggregations/bucket/composite Retrieve subsequent composite buckets by providing the 'after' parameter with the 'after_key' from the previous response. This example fetches the next 6 buckets. ```json GET opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, "aggs": { "composite_buckets": { "composite": { "sources": [ { "quantity": { "histogram": { "field": "products.quantity", "interval": 1 }}}, { "unit_price": { "histogram": { "field": "products.base_unit_price", "interval": 50 }}} ], "size": 6, "after": { "quantity": 2, "unit_price": 150 } } } } } ``` -------------------------------- ### Calculate Standard Deviation with Moving Functions Source: https://docs.opensearch.org/latest/aggregations/pipeline/moving-function This example demonstrates calculating the standard deviation of byte sums over a moving window using predefined functions. It requires a date histogram and a sum sub-aggregation. ```json POST /opensearch_dashboards_sample_data_logs/_search { "size": 0, "aggs": { "my_date_histo": { "date_histogram": { "field": "timestamp", "calendar_interval": "week" }, "aggs": { "the_sum": { "sum": { "field": "bytes" } }, "the_movavg": { "moving_fn": { "buckets_path": "the_sum", "window": 5, "script": "MovingFunctions.stdDev(values, MovingFunctions.unweightedAvg(values))" } } } } } } ``` -------------------------------- ### Nested Aggregation Example Source: https://docs.opensearch.org/latest/aggregations/bucket/nested This snippet demonstrates how to perform a nested aggregation on the 'pages' field to find the minimum 'load_time'. It filters logs for a '200' response and then applies subaggregations. ```json GET logs-nested/_search { "query": { "match": { "response": "200" } }, "aggs": { "pages": { "nested": { "path": "pages" }, "aggs": { "min_load_time": { "min": { "field": "pages.load_time" } } } } } } ``` -------------------------------- ### Example Aggregation Response Source: https://docs.opensearch.org/latest/aggregations/pipeline/bucket-script This JSON object represents the response from an OpenSearch aggregation query. It shows the calculated monthly average vendor spend, including details for each month's bucket. ```json { "took": 6, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 4675, "relation": "eq" }, "max_score": null, "hits": [] }, "aggregations": { "sales_per_month": { "buckets": [ { "key_as_string": "2025-03-01T00:00:00.000Z", "key": 1740787200000, "doc_count": 721, "vendor_count": { "value": 21 }, "total_sales": { "value": 53468.1484375 }, "avg_vendor_spend": { "value": 2546.1023065476193, "value_as_string": "$2,546.10" } }, { "key_as_string": "2025-04-01T00:00:00.000Z", "key": 1743465600000, "doc_count": 3954, "vendor_count": { "value": 21 }, "total_sales": { "value": 297415.98046875 }, "avg_vendor_spend": { "value": 14162.665736607143, "value_as_string": "$14,162.67" } } ] } } } ``` -------------------------------- ### Shift bucket start times using an offset Source: https://docs.opensearch.org/latest/aggregations/bucket/date-histogram Moves bucket boundaries forward or backward by a specified duration. Use to define custom reporting periods, e.g., 06:00-06:00. ```json GET my-logs/_search { "size": 0, "aggs": { "by_day_shifted": { "date_histogram": { "field": "timestamp", "calendar_interval": "day", "offset": "+6h" } } } } ``` -------------------------------- ### Composite Aggregation Response with Histogram Buckets Source: https://docs.opensearch.org/latest/aggregations/bucket/composite This is an example response from a composite aggregation using histogram sources. It shows the 'after_key' for pagination and the bucket keys, which represent the lower bound of each histogram interval. ```json { "took": 11, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 4675, "relation": "eq" }, "max_score": null, "hits": [] }, "aggregations": { "composite_buckets": { "after_key": { "quantity": 2, "unit_price": 150 }, "buckets": [ { "key": { "quantity": 1, "unit_price": 0 }, "doc_count": 17691 }, { "key": { "quantity": 1, "unit_price": 50 }, "doc_count": 5014 }, { "key": { "quantity": 1, "unit_price": 100 }, "doc_count": 482 }, { "key": { "quantity": 1, "unit_price": 150 }, "doc_count": 148 }, { "key": { "quantity": 1, "unit_price": 200 }, "doc_count": 32 }, { "key": { "quantity": 2, "unit_price": 150 }, "doc_count": 4 } ] } } } ``` -------------------------------- ### Ingest Sample Documents Source: https://docs.opensearch.org/latest/aggregations/bucket/significant-terms Loads sample customer order documents into the retail_orders index using the bulk API. ```json POST _bulk { "index": { "_index": "retail_orders" } } { "status":"RETURNED", "order_total": 950, "payment_method":"gift_card" } { "index": { "_index": "retail_orders" } } { "status":"RETURNED", "order_total": 720, "payment_method":"gift_card" } { "index": { "_index": "retail_orders" } } { "status":"RETURNED", "order_total": 540, "payment_method":"gift_card" } { "index": { "_index": "retail_orders" } } { "status":"RETURNED", "order_total": 820, "payment_method":"credit_card" } { "index": { "_index": "retail_orders" } } { "status":"RETURNED", "order_total": 500, "payment_method":"paypal" } { "index": { "_index": "retail_orders" } } { "status":"DELIVERED", "order_total": 130, "payment_method":"credit_card" } { "index": { "_index": "retail_orders" } } { "status":"DELIVERED", "order_total": 75, "payment_method":"paypal" } { "index": { "_index": "retail_orders" } } { "status":"DELIVERED", "order_total": 260, "payment_method":"paypal" } { "index": { "_index": "retail_orders" } } { "status":"DELIVERED", "order_total": 45, "payment_method":"credit_card" } { "index": { "_index": "retail_orders" } } { "status":"DELIVERED", "order_total": 310, "payment_method":"credit_card" } { "index": { "_index": "retail_orders" } } { "status":"DELIVERED", "order_total": 220, "payment_method":"credit_card" } { "index": { "_index": "retail_orders" } } { "status":"DELIVERED", "order_total": 410, "payment_method":"paypal" } ``` -------------------------------- ### Ingest Documents for Missing Value Example Source: https://docs.opensearch.org/latest/aggregations/metric/average Ingests sample documents into the `students` index, with one document intentionally missing the `gpa` field. This setup is used to demonstrate the `missing` parameter in aggregations. ```json POST _bulk { "create": { "_index": "students", "_id": "1" } } { "name": "John Doe", "gpa": 3.89, "grad_year": 2022} { "create": { "_index": "students", "_id": "2" } } { "name": "Jonathan Powers", "grad_year": 2025 } { "create": { "_index": "students", "_id": "3" } } { "name": "Jane Doe", "gpa": 3.52, "grad_year": 2024 } ``` -------------------------------- ### Sampler Aggregation with Terms Bucketing Source: https://docs.opensearch.org/latest/aggregations/bucket/sampler This example demonstrates limiting the documents collected per shard to 1,000 and then applying a terms aggregation to the sampled documents based on the 'agent.keyword' field. Use this when you need approximate but fast results for term-based analysis on large datasets. ```json GET opensearch_dashboards_sample_data_logs/_search { "size": 0, "aggs": { "sample": { "sampler": { "shard_size": 1000 }, "aggs": { "terms": { "terms": { "field": "agent.keyword" } } } } } } ``` -------------------------------- ### Truncate Buckets Without Sorting Source: https://docs.opensearch.org/latest/aggregations/pipeline/bucket-sort To truncate results without applying a sort order, omit the 'sort' parameter from the 'bucket_sort' aggregation. This example returns two buckets, starting from the second, based on their natural order. ```json GET opensearch_dashboards_sample_data_logs/_search { "size": 0, "aggs": { "sales_per_month": { "date_histogram": { "field": "@timestamp", "calendar_interval": "month" }, "aggs": { "total_bytes": { "sum": { "field": "bytes" } }, "bytes_bucket_sort": { "bucket_sort": { "from": 1, "size": 2 } } } } } } ``` -------------------------------- ### Create Sample Index Source: https://docs.opensearch.org/latest/aggregations/metric/percentile-ranks Creates an index named 'transaction_data' with a mapping for a 'double' type 'amount' field. ```json PUT /transaction_data { "mappings": { "properties": { "amount": { "type": "double" } } } } ``` -------------------------------- ### Cardinality Aggregation with Ordinals Hint Source: https://docs.opensearch.org/latest/aggregations/metric/cardinality This example demonstrates how to run a cardinality aggregation using the 'ordinals' execution hint to count unique values in a field. It's useful for fields with a high number of unique values where performance is critical. ```json GET opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, "aggs": { "unique_products": { "cardinality": { "field": "products.product_id", "execution_hint": "ordinals" } } } } ``` -------------------------------- ### Example Geo Distance Aggregation Source: https://docs.opensearch.org/latest/aggregations/bucket/geo-distance An example of a geo_distance aggregation that buckets documents into ranges based on their distance from a specific latitude and longitude. ```json GET opensearch_dashboards_sample_data_logs/_search { "size": 0, "aggs": { "position": { "geo_distance": { "field": "geo.coordinates", "origin": { "lat": 83.76, "lon": -81.2 }, "ranges": [ { "to": 10 }, { "from": 10, "to": 20 }, { "from": 20, "to": 50 }, { "from": 50, "to": 100 }, { "from": 100 } ] } } } } ``` -------------------------------- ### Date Range Aggregation - Three Sliding Windows Source: https://docs.opensearch.org/latest/aggregations/bucket/date-range This example demonstrates how to create three buckets representing the last 7 days, the previous 7 days, and older documents. It utilizes date math for defining the ranges and specifies a 'yyyy-MM-dd' format for the output. ```APIDOC ## GET my-index/_search ### Description Groups documents into three date ranges: the last 7 days, the previous 7 days, and all documents older than the previous 7 days. ### Method GET ### Endpoint my-index/_search ### Parameters #### Query Parameters - **size** (integer) - Optional - The number of search results to return. #### Request Body - **aggs** (object) - Required - Defines the aggregations to perform. - **by_range** (object) - Required - Configuration for the date range aggregation. - **date_range** (object) - Required - Specifies the date range aggregation. - **field** (string) - Required - The date field to aggregate on (e.g., "@timestamp"). - **format** (string) - Optional - The format for date strings in the response (e.g., "yyyy-MM-dd"). - **ranges** (array) - Required - An array of range objects defining the buckets. - **from** (string) - One of `from` or `to` is required. Lower inclusive bound. Supports ISO 8601, date math, and epoch milliseconds. - **to** (string) - One of `from` or `to` is required. Upper exclusive bound. Supports ISO 8601, date math, and epoch milliseconds. - **key** (string) - Optional - A label for the bucket. ### Request Example ```json { "size": 0, "aggs": { "by_range": { "date_range": { "field": "@timestamp", "format": "yyyy-MM-dd", "ranges": [ { "from": "now-7d/d", "to": "now+1d/d", "key": "last_7d" }, { "from": "now-14d/d", "to": "now-7d/d", "key": "prev_7d" }, { "to": "now-14d/d", "key": "older" } ] } } } } ``` ### Response #### Success Response (200) - **aggregations** (object) - Contains the aggregation results. - **by_range** (object) - Results for the date range aggregation. - **buckets** (array) - An array of buckets, each representing a date range. - **key** (string) - The label for the bucket. - **from** (long) - The inclusive start of the bucket in epoch milliseconds. - **from_as_string** (string) - The string representation of the `from` bound. - **to** (long) - The exclusive end of the bucket in epoch milliseconds. - **to_as_string** (string) - The string representation of the `to` bound. - **doc_count** (integer) - The number of documents in the bucket. #### Response Example ```json { "aggregations": { "by_range": { "buckets": [ { "key": "older", "to": 1758067200000, "to_as_string": "2025-09-17", "doc_count": 1 }, { "key": "prev_7d", "from": 1758067200000, "from_as_string": "2025-09-17", "to": 1758672000000, "to_as_string": "2025-09-24", "doc_count": 2 }, { "key": "last_7d", "from": 1758672000000, "from_as_string": "2025-09-24", "to": 1759363200000, "to_as_string": "2025-10-02", "doc_count": 2 } ] } } } ``` ``` -------------------------------- ### Create Sample Index for Logs Source: https://docs.opensearch.org/latest/aggregations/metric/scripted-metric Defines the mapping for the 'logs' index, specifying the 'response' field as a keyword type. ```json PUT logs { "mappings": { "properties": { "response": { "type": "keyword" } } } } ``` -------------------------------- ### Date Range Aggregation with Three Sliding Windows Source: https://docs.opensearch.org/latest/aggregations/bucket/date-range This example creates three buckets for the last 7 days, the previous 7 days, and older documents. It uses date math and specifies the 'yyyy-MM-dd' output format. ```json GET my-index/_search { "size": 0, "aggs": { "by_range": { "date_range": { "field": "@timestamp", "format": "yyyy-MM-dd", "ranges": [ { "from": "now-7d/d", "to": "now+1d/d", "key": "last_7d" }, { "from": "now-14d/d", "to": "now-7d/d", "key": "prev_7d" }, { "to": "now-14d/d", "key": "older" } ] } } } } ``` -------------------------------- ### Significant Terms Aggregation Result Example Source: https://docs.opensearch.org/latest/aggregations/bucket/significant-terms Example output of a significant_terms aggregation, showing document counts, background counts, and the score for overrepresented terms. ```json { "...": "...", "aggregations": { "payment_signals": { "doc_count": 5, "bg_count": 12, "buckets": [ { "key": "gift_card", "doc_count": 3, "score": 0.84, "bg_count": 3 } ] } } } ``` -------------------------------- ### Geo Bounds Aggregation Result Example Source: https://docs.opensearch.org/latest/aggregations/metric/geobounds This is an example of the output from a geo_bounds aggregation when wrap_longitude is set to false. Note the 'bounds' object with 'top_left' and 'bottom_right' coordinates. ```json { ... "aggregations": { "grouped": { "bounds": { "top_left": { "lat": 45.11999997776002, "lon": -120.23000006563962 }, "bottom_right": { "lat": 13.469999986700714, "lon": 144.71999991685152 } } } } } ``` -------------------------------- ### Example Response with Second Derivative Source: https://docs.opensearch.org/latest/aggregations/pipeline/derivative This JSON response shows the output of an aggregation that includes the calculation of the first and second derivatives. Note that the second derivative is only present in the third bucket, as it requires two preceding buckets for calculation. ```json { "took": 6, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 10000, "relation": "gte" }, "max_score": null, "hits": [] }, "aggregations": { "sales_per_month": { "buckets": [ { "key_as_string": "2025-03-01T00:00:00.000Z", "key": 1740787200000, "doc_count": 480, "number_of_bytes": { "value": 2804103 } }, { "key_as_string": "2025-04-01T00:00:00.000Z", "key": 1743465600000, "doc_count": 6849, "number_of_bytes": { "value": 39103067 }, "bytes_1st_deriv": { "value": 36298964 } }, { "key_as_string": "2025-05-01T00:00:00.000Z", "key": 1746057600000, "doc_count": 6745, "number_of_bytes": { "value": 37818519 }, "bytes_1st_deriv": { "value": -1284548 }, "bytes_2nd_deriv": { "value": -37583512 } } ] } } } ``` -------------------------------- ### Calculate Minimum Monthly Bytes Source: https://docs.opensearch.org/latest/aggregations/pipeline/min-bucket This example demonstrates how to use the `min_bucket` aggregation to find the minimum sum of bytes within monthly buckets. It first creates a date histogram to group data by month and calculates the sum of bytes for each month using a `sum` subaggregation. The `min_bucket` aggregation then finds the minimum value from these monthly sums. ```json POST opensearch_dashboards_sample_data_logs/_search { "size": 0, "aggs": { "visits_per_month": { "date_histogram": { "field": "@timestamp", "interval": "month" }, "aggs": { "sum_of_bytes": { "sum": { "field": "bytes" } } } }, "min_monthly_bytes": { "min_bucket": { "buckets_path": "visits_per_month>sum_of_bytes" } } } } ``` -------------------------------- ### Index Sample Data for Weighted Average Aggregation Source: https://docs.opensearch.org/latest/aggregations/metric/weighted-avg This snippet indexes sample product data into an 'products' index. It includes documents with and without 'rating' and 'num_reviews' fields to demonstrate handling missing values. ```json POST _bulk { "index": { "_index": "products" } } { "name": "Product A", "rating": 4.5, "num_reviews": 100 } { "index": { "_index": "products" } } { "name": "Product B", "rating": 3.8, "num_reviews": 50 } { "index": { "_index": "products" } } { "name": "Product C"} ``` -------------------------------- ### Calculate Average Monthly Bytes with Avg Bucket Aggregation Source: https://docs.opensearch.org/latest/aggregations/pipeline/avg-bucket This example demonstrates calculating the average sum of bytes per month using a date histogram and a sum subaggregation, followed by the avg_bucket aggregation. It requires the OpenSearch Dashboards sample data logs. ```json POST opensearch_dashboards_sample_data_logs/_search { "size": 0, "aggs": { "visits_per_month": { "date_histogram": { "field": "@timestamp", "interval": "month" }, "aggs": { "sum_of_bytes": { "sum": { "field": "bytes" } } } }, "avg_monthly_bytes": { "avg_bucket": { "buckets_path": "visits_per_month>sum_of_bytes" } } } } ``` -------------------------------- ### Moving Average Aggregation Example Source: https://docs.opensearch.org/latest/aggregations/pipeline/moving-avg Calculates the moving average of the sum of bytes per month using a date histogram and sum aggregation. This example demonstrates the typical use case for time-series data smoothing. ```json GET opensearch_dashboards_sample_data_logs/_search { "size": 0, "aggs": { "my_date_histogram": { "date_histogram": { "field": "@timestamp", "calendar_interval": "month" }, "aggs": { "sum_of_bytes": { "sum": { "field": "bytes" } }, "moving_avg_of_sum_of_bytes": { "moving_avg": { "buckets_path": "sum_of_bytes" } } } } } } ```