3

I have point in my db (Postgres postgis):

CREATE TABLE geometries (name varchar, geom geometry);

With example data:

INSERT INTO geometries VALUES ('Point', 'POINT(0 0)');

INSERT INTO geometries VALUES ('Point', 'POINT(10 0)');

I would like to select one point closest to input - for example (1, 1)

It must be geographics distance using haversine formula (https://www.movable-type.co.uk/scripts/latlong.html).

What is the best way (fastest by performance) how can I do it?

1
  • 4
    Use a geography column rather than a geometry column
    – Ian Turton
    Commented Oct 26, 2019 at 15:44

1 Answer 1

4

Use the nearest neighbour operator

SELECT * FROM geometries
ORDER BY geom <-> ST_GeogFromText('POINT(1, 1)')
LIMIT 1
4
  • 1
    note that the <-> operator measures distances based on a sphere for GEOGRAPHY; if 'using haversine' (i.e. spheroidal geometric algebra) is mandatory, one will need to ORDER BY ST_Distance(<geography_a>, <geography_b>)
    – geozelot
    Commented Oct 27, 2019 at 8:13
  • @ThingumaBob I was under the impression that ordering by ST_DISTANCE was horribly slow and inefficient. Wouldn't it be enough to cast geometry to geography? Ie, ORDER BY geom::geography <-> ST_GeomFromText('POINT(1, 1)')::geography ?
    – hunter
    Commented Oct 27, 2019 at 11:53
  • @hunter it's as efficient as ordering in general. the advantage of the <-> operator is the implicit check of the index to consider only geometries in the actual neighborhood; adding sth. like WHERE geom && ST_Expand('POINT(1 1)'::GEOMETRY, <threshold_in_degree_eg_0.001>) would help to limit actual calculations to nearby points (but obviously doesn't guarantee to find a neighbor). casting to GEOGRAPHY is definitely what you want, but the <-> operator is hardcoded to 'only' measure on a sphere, wheras ST_Distance uses a spheroid for GEOGRAPHY by default.
    – geozelot
    Commented Oct 27, 2019 at 12:31
  • 1
    @hunter your answer is still +1! ...actually, there is almost no need at all to use GEOGRAPHY precision for nearest neighbor searches; for 99.5% of cases, topology is completely independent from the impact of longitudinal measurement discrepancy or great circle distance differences when using 2D LatLon 'projections'!
    – geozelot
    Commented Oct 27, 2019 at 12:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.