I am using gem geokit rails in my app. I have a table that contains various addresses. I am trying to use the geokit feature by_distance which finds records ordered by distance from the origin point.
So I am doing this at the moment.
@close = Mytable.by_distance(:origin => "12 wall street, NY")
So what happens here is that all the ids in MyTable are stored in @close by order meaning that the closest one is the first element of the array.
I actually only need the closest two addresses from Mytable. So i was wondering how to do that? Because my current code is giving me a list of all the closest addresses in the table in order. I don't want to have bad performance as I only need the 2 closest stops.
Please suggest how to achieve this.
You should try this:
@close = Mytable.by_distance(:origin => "12 wall street, NY").limit(2)
Note that the by_distance
query is already as well optimized it can be, and adding a limit
to the query won't make anything radical for you in terms of performance, but it should also not slow your application down.
As always, test it out in your console to see what the resulting SQL statement looks like, and that nothing strange is going on. You might also wish to profile the two against each other just to be sure.