Weighted Average Aggregation Usage

edit

A single-value metrics aggregation that computes the weighted average of numeric values that are extracted from the aggregated documents. These values can be extracted either from specific numeric fields in the documents. When calculating a regular average, each datapoint has an equal "weight" i.e. it contributes equally to the final value. Weighted averages, on the other hand, weight each datapoint differently. The amount that each datapoint contributes to the final value is extracted from the document, or provided by a script.

Only available in Elasticsearch 6.4.0+

Be sure to read the Elasticsearch documentation on Weighted Avg Aggregation

Fluent DSL example

edit
a => a
.WeightedAverage("weighted_avg_commits", avg => avg
    .Value(v => v.Field(p => p.NumberOfCommits).Missing(0))
    .Weight(w => w.Script("(doc['numberOfContributors']?.value ?: 0) + 1"))
    .ValueType(ValueType.Long)
)

Object Initializer syntax example

edit
new WeightedAverageAggregation("weighted_avg_commits")
{
    Value = new WeightedAverageValue(Field<Project>(p => p.NumberOfCommits))
    {
        Missing = 0
    },
    Weight = new WeightedAverageValue(new InlineScript("(doc['numberOfContributors']?.value ?: 0) + 1")),
    ValueType = ValueType.Long
}

Example json output.

{
  "weighted_avg_commits": {
    "weighted_avg": {
      "value": {
        "field": "numberOfCommits",
        "missing": 0.0
      },
      "weight": {
        "script": {
          "source": "(doc['numberOfContributors']?.value ?: 0) + 1"
        }
      },
      "value_type": "long"
    }
  }
}

Handling Responses

edit
response.ShouldBeValid();
var commitsAvg = response.Aggregations.WeightedAverage("weighted_avg_commits");
commitsAvg.Should().NotBeNull();
commitsAvg.Value.Should().BeGreaterThan(0);