Top Metrics Aggregation Usage

edit

The top metrics aggregation selects metrics from the document with the largest or smallest "sort" value.

Top metrics is fairly similar to "top hits" in spirit but because it is more limited it is able to do its job using less memory and is often faster.

Be sure to read the Elasticsearch documentation on Top Metrics Aggregation

Fluent DSL example

edit
a => a
.TopMetrics("tm", st => st
    .Metrics(m => m.Field(p => p.NumberOfContributors))
    .Size(10)
    .Sort(sort => sort
        .Ascending("numberOfContributors")
    )
)

Object Initializer syntax example

edit
new TopMetricsAggregation("tm")
{
    Metrics = new List<ITopMetricsValue>
    {
        new TopMetricsValue(Field<Project>(p => p.NumberOfContributors))
    },
    Size = 10,
    Sort = new List<ISort> { new FieldSort { Field = "numberOfContributors", Order = SortOrder.Ascending } }
}

Example json output.

{
  "tm": {
    "top_metrics": {
      "metrics": [
        {
          "field": "numberOfContributors"
        }
      ],
      "size": 10,
      "sort": [
        {
          "numberOfContributors": {
            "order": "asc"
          }
        }
      ]
    }
  }
}

Handling Responses

edit
response.ShouldBeValid();
var topMetrics = response.Aggregations.TopMetrics("tm");
topMetrics.Should().NotBeNull();
topMetrics.Top.Should().NotBeNull();
topMetrics.Top.Count.Should().BeGreaterThan(0);

var tipTop = topMetrics.Top.First();
tipTop.Sort.Should().Should().NotBeNull();
tipTop.Sort.Count.Should().BeGreaterThan(0);
tipTop.Metrics.Should().NotBeNull();
tipTop.Metrics.Count.Should().BeGreaterThan(0);