Bucket Sort Aggregation Usage

edit

Fluent DSL example

edit
a => a
.DateHistogram("projects_started_per_month", dh => dh
    .Field(p => p.StartedOn)
    .Interval(DateInterval.Month)
    .Aggregations(aa => aa
        .Sum("commits", sm => sm
            .Field(p => p.NumberOfCommits)
        )
        .BucketSort("commits_bucket_sort", bs => bs
            .Sort(s => s
                .Descending("commits")
            )
            .From(0)
            .Size(3)
            .GapPolicy(GapPolicy.InsertZeros)
        )
    )
)

Object Initializer syntax example

edit
new DateHistogramAggregation("projects_started_per_month")
{
    Field = "startedOn",
    Interval = DateInterval.Month,
    Aggregations =
        new SumAggregation("commits", "numberOfCommits") &&
        new BucketSortAggregation("commits_bucket_sort")
        {
            Sort = new List<ISort>
            {
                new FieldSort { Field = "commits", Order = SortOrder.Descending }
            },
            From = 0,
            Size = 3,
            GapPolicy = GapPolicy.InsertZeros
        }
}

Example json output.

{
  "projects_started_per_month": {
    "date_histogram": {
      "field": "startedOn",
      "interval": "month"
    },
    "aggs": {
      "commits": {
        "sum": {
          "field": "numberOfCommits"
        }
      },
      "commits_bucket_sort": {
        "bucket_sort": {
          "sort": [
            {
              "commits": {
                "order": "desc"
              }
            }
          ],
          "from": 0,
          "size": 3,
          "gap_policy": "insert_zeros"
        }
      }
    }
  }
}

Handling Responses

edit
response.ShouldBeValid();

var projectsPerMonth = response.Aggregations.DateHistogram("projects_started_per_month");
projectsPerMonth.Should().NotBeNull();
projectsPerMonth.Buckets.Should().NotBeNull();
projectsPerMonth.Buckets.Count.Should().Be(3);

double previousCommits = -1;

// sum of commits should descend over buckets
foreach (var item in projectsPerMonth.Buckets)
{
    var value = item.Sum("commits").Value;
    if (value == null) continue;

    var numberOfCommits = value.Value;
    if (Math.Abs(previousCommits - (-1)) > double.Epsilon)
        numberOfCommits.Should().BeLessOrEqualTo(previousCommits);

    previousCommits = numberOfCommits;
}