PostGIS Distance Matrix – Fast Methods for Recalculating Distance Table

distancedistance matrixpostgis

I have a system that is based on PostGIS that holds a set of coordinates.
It serves a lot of user requests where users send their own current coordinates and receive a set of points that are located nearby, like 5-10 km. Each time the DB pulls all points and calculates the distance between points.

Is there is a way to use a simpler way of calculation, like counting all distances to the base point, and then using some matrix transformation?
Or maybe I am missing some PostGIS functionality?

UPD:
The point info is stored this way:

ST_GeomFromGeoJSON('{"type":"Point","coordinates":[28.119871,48.542976]}')::geometry

The resulting SQL is really big, but the distance is calculated like:

ST_Distance(ST_Transform("fuelStation"."location",9015), ST_Transform(ST_GeomFromGeoJSON([user entered coordinates]),9015))

Maybe I need to clarify the question – the current realization works +- fast, but I wonder is there a way to "cache" distances table from 1 point and then recalculate when the point changes?

Best Answer

This has a few failure modes because it's doing the KNN in cartesian space, but without re-organizing how you manage projections in your system (what your storage SRS is, what your in/out SRS is) it is a rough'n'ready answer.

CREATE INDEX fuelStation_location_x 
  ON "fuelStation" 
  USING GIST (location);

SELECT f.*, ST_Distance(f.location::geography, ST_GeomFromGeoJSON($text)::geography) AS distance
  FROM "fuelStation" f
  ORDER BY location <-> ST_GeomFromGeoJSON($text)
  LIMIT 5;
Related Question