Scripted metric aggregations

The scripted_metric metric is a multi-value metric aggregation that returns metrics calculated from a specified script.

A script has four stages: the initial stage, the map stage, the combine stage, and the reduce stage.

  • init_script: (OPTIONAL) Sets the initial state and executes before any collection of documents.
  • map_script: Checks the value of the type field and executes the aggregation on the collected documents.
  • combine_script: Aggregates the state returned from every shard. The aggregated value is returned to the coordinating node.
  • reduce_script: Provides access to the variable states; this variable combines the results from the combine_script on each shard into an array.

The following example aggregates the different HTTP response types in web log data:

  1. GET opensearch_dashboards_sample_data_logs/_search
  2. {
  3. "size": 0,
  4. "aggregations": {
  5. "responses.counts": {
  6. "scripted_metric": {
  7. "init_script": "state.responses = ['error':0L,'success':0L,'other':0L]",
  8. "map_script": """
  9. def code = doc['response.keyword'].value;
  10. if (code.startsWith('5') || code.startsWith('4')) {
  11. state.responses.error += 1 ;
  12. } else if(code.startsWith('2')) {
  13. state.responses.success += 1;
  14. } else {
  15. state.responses.other += 1;
  16. }
  17. """,
  18. "combine_script": "state.responses",
  19. "reduce_script": """
  20. def counts = ['error': 0L, 'success': 0L, 'other': 0L];
  21. for (responses in states) {
  22. counts.error += responses['error'];
  23. counts.success += responses['success'];
  24. counts.other += responses['other'];
  25. }
  26. return counts;
  27. """
  28. }
  29. }
  30. }
  31. }

copy

Example response

  1. ...
  2. "aggregations" : {
  3. "responses.counts" : {
  4. "value" : {
  5. "other" : 0,
  6. "success" : 12832,
  7. "error" : 1242
  8. }
  9. }
  10. }
  11. }