Getting Distance with Azure Search Service

Viewed 675

I have an object such as this:

[SerializePropertyNamesAsCamelCase]
public class Location
{
    [Key]
    public string Id { get; set; }

    [IsFilterable, IsSortable]
    public GeographyPoint GeographyPoint { get; set; }
}

What I would like to do is retrieve all locations that are within 10 KM and order them by distance, so closest show first. Lastly, I want to know what that distance is.

Here is what I tried:

var index = GetIndex();

var parameters = new SearchParameters
{
    Skip = 0,
    Top = 20,
    Filter = "geo.distance(geographyPoint, geography'POINT(-122.131577 47.678581)') le 10  "
};

var results = index.Documents.Search<Location>("*", parameters);

The problem with above is that it doesn't tell me the distance, nor does it sort by it.

I'm wondering how to accomplish the above? Do I have to create a double Distance property inside Location object and if so, then how do I populate it so I can search by it, order by it and then retrieve it?

1 Answers
var orderBy = new List<string>();
orderBy.Add("geo.distance(LatLong, geography'POINT(" + request.LatLong + ")')");

var parameters = new SearchParameters {
Skip = 0,
Top = 20,
Filter = "geo.distance(geographyPoint, geography'POINT(-122.131577 47.678581)') le 10",
OrderBy = orderBy };

You can also add asc/desc to the end of your order by variable to return results ascending or descending.

Unfortunately azure search doesn't return the distance, you will have to calculate that yourself.

Related