Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Geo Aggregations in Elasticsearch

Introduction

Geo aggregations in Elasticsearch allow you to analyze your geospatial data. This tutorial will guide you through the various types of geo aggregations available and show you how to use them effectively.

Geo Boundaries

Geo boundaries aggregation computes the bounding box enclosing all geo points in a set of documents.

Example Query:

{
  "aggs": {
    "viewport": {
      "geo_bounds": {
        "field": "location"
      }
    }
  }
}

Sample Output:

{
  "aggregations": {
    "viewport": {
      "bounds": {
        "top_left": {
          "lat": 40.73,
          "lon": -74.1
        },
        "bottom_right": {
          "lat": 40.01,
          "lon": -71.12
        }
      }
    }
  }
}

Geo Centroid

The geo centroid aggregation finds the geometric center (centroid) of a set of geo points.

Example Query:

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

Sample Output:

{
  "aggregations": {
    "centroid": {
      "location": {
        "lat": 40.52,
        "lon": -73.61
      },
      "count": 10
    }
  }
}

Geo Distance

The geo distance aggregation groups documents into buckets based on their distance from a central point.

Example Query:

{
  "aggs": {
    "rings_around_amsterdam": {
      "geo_distance": {
        "field": "location",
        "origin": "52.3760, 4.894",
        "ranges": [
          { "to": 100 },
          { "from": 100, "to": 300 },
          { "from": 300 }
        ]
      }
    }
  }
}

Sample Output:

{
  "aggregations": {
    "rings_around_amsterdam": {
      "buckets": [
        {
          "key": "*-100.0",
          "to": 100,
          "doc_count": 3
        },
        {
          "key": "100.0-300.0",
          "from": 100,
          "to": 300,
          "doc_count": 5
        },
        {
          "key": "300.0-*",
          "from": 300,
          "doc_count": 8
        }
      ]
    }
  }
}

Geo Hash Grid

The geo hash grid aggregation groups documents into cells defined by a GeoHash grid.

Example Query:

{
  "aggs": {
    "locations": {
      "geohash_grid": {
        "field": "location",
        "precision": 3
      }
    }
  }
}

Sample Output:

{
  "aggregations": {
    "locations": {
      "buckets": [
        {
          "key": "u4pruydqqvj",
          "doc_count": 5
        },
        {
          "key": "u4pruydqqvm",
          "doc_count": 3
        }
      ]
    }
  }
}

Conclusion

Geo aggregations in Elasticsearch provide powerful tools for analyzing geospatial data. By understanding and using these aggregations effectively, you can gain valuable insights from your data.