Scripted Metric Aggregation Usageedit

Fluent DSL exampleedit

s => s
.Aggregations(a => a
    .ScriptedMetric("sum_the_hard_way", sm => sm
        .InitScript(ss=>ss.Inline("_agg['commits'] = []").Lang("groovy"))
        .MapScript(ss=>ss.Inline("if (doc['state'].value == \"Stable\") { _agg.commits.add(doc['numberOfCommits']) }").Lang("groovy"))
        .CombineScript(ss=>ss.Inline("sum = 0; for (c in _agg.commits) { sum += c }; return sum").Lang("groovy"))
        .ReduceScript(ss=>ss.Inline("sum = 0; for (a in _aggs) { sum += a }; return sum").Lang("groovy"))
    )
)

Object Initializer syntax exampleedit

new SearchRequest<Project>
{
    Aggregations = new ScriptedMetricAggregation("sum_the_hard_way")
    {
        InitScript = new InlineScript("_agg['commits'] = []") { Lang = "groovy" },
        MapScript = new InlineScript("if (doc['state'].value == \"Stable\") { _agg.commits.add(doc['numberOfCommits']) }"){ Lang = "groovy" },
        CombineScript = new InlineScript("sum = 0; for (c in _agg.commits) { sum += c }; return sum"){ Lang = "groovy" },
        ReduceScript = new InlineScript("sum = 0; for (a in _aggs) { sum += a }; return sum"){ Lang = "groovy" }
    }
}

Example json output. 

{
  "aggs": {
    "sum_the_hard_way": {
      "scripted_metric": {
        "init_script": {
          "inline": "_agg['commits'] = []",
          "lang": "groovy"
        },
        "map_script": {
          "inline": "if (doc['state'].value == \"Stable\") { _agg.commits.add(doc['numberOfCommits']) }",
          "lang": "groovy"
        },
        "combine_script": {
          "inline": "sum = 0; for (c in _agg.commits) { sum += c }; return sum",
          "lang": "groovy"
        },
        "reduce_script": {
          "inline": "sum = 0; for (a in _aggs) { sum += a }; return sum",
          "lang": "groovy"
        }
      }
    }
  }
}

Handling Responsesedit

response.ShouldBeValid();
var sumTheHardWay = response.Aggs.ScriptedMetric("sum_the_hard_way");
sumTheHardWay.Should().NotBeNull();
sumTheHardWay.Value<int>().Should().BeGreaterThan(0);