Searching and Ranking Results by Geographic Location in Amazon CloudSearch
If you store locations in your document data using a
latlon field, you can use the
haversin function in an Amazon CloudSearch expression to compute the distance between two locations. Storing locations with your
document data also enables you to easily search within particular areas.
Searching Within an Area in Amazon CloudSearch
To associate a location with a search document, you can store the location's
latitude and longitude in a
latlon field using decimal degree notation. The values are specified
as a comma-separated list,
Associating a location with a document enables you to easily constrain search hits to a
particular area with the
To use a bounding box to constrain results to a particular area
Determine the latitude and longitude of the upper-left and lower-right corners of the area you are interested in.
fqparameter to filter the matching documents using those bounding box coordinates. For example, if you include a
locationfield in each document, you could specify your bounding box filter as
fq=location:['nn.n,nn.n','nn.n,nn.n']. In the following example, the matches for restaurant are filtered so that only matches within the downtown area of Paso Robles, CA are included in the results.Copy
Sorting Results by Distance in Amazon CloudSearch
You can define an expression as part of your search request to sort results by
distance. Amazon CloudSearch expressions support the
haversin function, which computes
the great-circle distance between two points on a sphere using the latitude and
longitude of each point. (For more information, see Haversine formula.) The resulting distance is returned in kilometers.
To calculate the distance between each matching document and the user, you pass the user's location into the
haversin function and reference the document locations stored in a
latlon field. You specify the user latitude and longitude in decimal degree notation and access the latitude and longitude stored
FIELD.longitude. For example,
To use the expression to sort the search results, you specify the
For example, the following query searches for restaurants and sorts the results by distance from the user.
Note that you must explicitly specify the sort
You can include the distance calculated for each document in the search
results by specifying the name of the expression with the
You can also use the distance value in more complex expressions to take other characteristics into account, such as a document's
_score. In the following example, a second rank expression uses both the document's calculated
distance and its relevance
For more information about using expressions to sort search results, see Controlling Search Results.