I am working with the GeoNames database which has around 10 million rows of locations including longitude and latitude.
I have tested around 6 various nearby location queries including spatial indexes. I found the following query to be the fastest as well as accurate (using indexes on longitude/latitude)
SELECT
*,
ROUND(SQRT(POW(((69.1/1.61) * (? - latitude)), 2) +
POW(((53/1.61) * (? - longitude)), 2)), 1) AS distance
FROM
geoName FORCE INDEX (longitude)
WHERE
latitude > ? - 100 / (69.1/1.61)
AND latitude < ? + 100 / (69.1/1.61)
AND longitude > ? - 100 / (53/1.61)
AND longitude < ? + 100 / (53/1.61)
HAVING
distance < 1500
ORDER BY
distance ASC
LIMIT 1
However there is still an issue with speed. This query takes an average of 3.14 seconds to run on my DigitalOcean Managed DB (2 dedicated CPU's 8gb ram). This is far too long and I would hopefully like to get it to around 500ms.
I can only think of 4 ways to do this
- Find a more efficient query than the one that I posted above
- Migrate from MySQL to PostgreSQL (do you think this will make much of a difference?)
- Upgrade the server specs
- Split the data into multiple tables by country and keep a database of neighboring countries so that we query multiple countries where the longitude/latitude point of interest is on the border
I suspect #4 will have the biggest impact (with quite a bit of work involved). A query from USA including neighboring countries would result in a total of 1584153 rows (which could be further reduced if we take into account state).
What do you think would be best?
latitude, longitude
may actually serve you quite well.