Geo Centroid Aggregation Usage

edit

A metric aggregation that computes the weighted centroid from all coordinate values for a Geo-point datatype field.

Be sure to read the Elasticsearch documentation on Geo Centroid Aggregation

Fluent DSL example

edit
s => s
.Aggregations(a => a
    .GeoCentroid("centroid", gb => gb
        .Field(p => p.Location)
    )
)

Object Initializer syntax example

edit
new SearchRequest<Project>
{
    Aggregations = new GeoCentroidAggregation("centroid", Infer.Field<Project>(p => p.Location))
}

Example json output.

{
  "aggs": {
    "centroid": {
      "geo_centroid": {
        "field": "location"
      }
    }
  }
}

Handling Responses

edit
response.ShouldBeValid();
var centroid = response.Aggs.GeoCentroid("centroid");
centroid.Should().NotBeNull();
centroid.Location.Should().NotBeNull();

centroid.Location.Latitude.Should().NotBe(0);
centroid.Location.Longitude.Should().NotBe(0);

Geo Centroid Sub Aggregation

edit

The geo_centroid aggregation is more interesting when combined as a sub-aggregation to other bucket aggregations

Fluent DSL example

edit
s => s
.Aggregations(a => a
    .Terms("projects", t => t
        .Field(p => p.Name)
        .Aggregations(sa => sa
            .GeoCentroid("centroid", gb => gb
                .Field(p => p.Location)
            )
        )
    )
)

Object Initializer syntax example

edit
new SearchRequest<Project>
{
    Aggregations = new TermsAggregation("projects")
    {
        Field = Infer.Field<Project>(p => p.Name),
        Aggregations = new GeoCentroidAggregation("centroid", Infer.Field<Project>(p => p.Location))
    }
}

Example json output.

{
  "aggs": {
    "projects": {
      "terms": {
        "field": "name"
      },
      "aggs": {
        "centroid": {
          "geo_centroid": {
            "field": "location"
          }
        }
      }
    }
  }
}

Handling Responses

edit
response.IsValid.Should().BeTrue();

var projects = response.Aggs.Terms("projects");

foreach (var bucket in projects.Buckets)
{
    var centroid = bucket.GeoCentroid("centroid");
    centroid.Should().NotBeNull();
    centroid.Location.Should().NotBeNull();

    centroid.Location.Latitude.Should().NotBe(0);
    centroid.Location.Longitude.Should().NotBe(0);
}