Geo Distance Aggregationedit

The geo_distance agg is useful for searches such as to "find all pizza restaurants within 1km of me." The search results should, indeed, be limited to the 1km radius specified by the user, but we can add “another result found within 2km”:

GET /attractions/restaurant/_search
{
  "query": {
    "bool": {
      "must": {
        "match": { 
          "name": "pizza"
        }
      },
      "filter": {
        "geo_bounding_box": {
          "location": { 
            "top_left": {
              "lat":  40.8,
              "lon": -74.1
            },
            "bottom_right": {
              "lat":  40.4,
              "lon": -73.7
            }
          }
        }
      }
    }
  },
  "aggs": {
    "per_ring": {
      "geo_distance": { 
        "field":    "location",
        "unit":     "km",
        "origin": {
          "lat":    40.712,
          "lon":   -73.988
        },
        "ranges": [
          { "from": 0, "to": 1 },
          { "from": 1, "to": 2 }
        ]
      }
    }
  },
  "post_filter": { 
    "geo_distance": {
      "distance":   "1km",
      "location": {
        "lat":      40.712,
        "lon":     -73.988
      }
    }
  }
}

The main query looks for restaurants with pizza in the name.

The bounding box filters these results down to just those in the greater New York area.

The geo_distance agg counts the number of results within 1km of the user, and between 1km and 2km from the user.

Finally, the post_filter reduces the search results to just those restaurants within 1km of the user.

The response from the preceding request is as follows:

"hits": {
  "total":     1,
  "max_score": 0.15342641,
  "hits": [ 
     {
        "_index": "attractions",
        "_type":  "restaurant",
        "_id":    "3",
        "_score": 0.15342641,
        "_source": {
           "name": "Mini Munchies Pizza",
           "location": [
              -73.983,
              40.719
           ]
        }
     }
  ]
},
"aggregations": {
  "per_ring": { 
     "buckets": [
        {
           "key":       "*-1.0",
           "from":      0,
           "to":        1,
           "doc_count": 1
        },
        {
           "key":       "1.0-2.0",
           "from":      1,
           "to":        2,
           "doc_count": 1
        }
     ]
  }
}

The post_filter has reduced the search hits to just the single pizza restaurant within 1km of the user.

The aggregation includes the search result plus the other pizza restaurant within 2km of the user.

In this example, we have counted the number of restaurants that fall into each concentric ring. Of course, we could nest sub-aggregations under the per_rings aggregation to calculate the average price per ring, the maximum popularity, and more.