Postgis SQL for nearest neighbors

前端 未结 2 1455
野性不改
野性不改 2021-02-09 15:35

I\'m trying to calculate the nearest neighbors. For that, I need to pass a parameter to limit the maximum distance from the neighbors. For example, which are the nearest neighbo

2条回答
  •  孤城傲影
    2021-02-09 15:56

    First, If you are using latitude, longitude, you need to use 4326.

    UPDATE season SET geom = ST_PointFromText ('POINT(' || longitude || ' ' || latitude || ')' , 4326 ) ;
    

    Then you create an index on the geom field

    CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometryfield] ); 
    

    Then you get the kNN neightbors:

    SELECT *,ST_Distance(geom,'SRID=4326;POINT(newLon newLat)'::geometry) 
    FROM yourDbTable
    ORDER BY
    yourDbTable.geom <->'SRID=4326;POINT(newLon newLat)'::geometry
    LIMIT 10;
    

    This query will take advantage of kNN functionality of the gist index (http://workshops.boundlessgeo.com/postgis-intro/knn.html).

    Still the distance returned will be in degrees, not meters (projection 4326 uses degrees).

    To fix this:

    SELECT *,ST_Distance(geography(geom),ST_GeographyFromText('POINT(newLon newLat)') 
    FROM yourDbTable
    ORDER BY
    yourDbTable.geom <->'SRID=4326;POINT(newLon newLat)'::geometry
    LIMIT 10;
    

    When you calculate the ST_distance use the geography type. There distance is always in meters:

    http://workshops.boundlessgeo.com/postgis-intro/geography.html

    All this functionality will probably need a recent Postgis version (2.0+). I am not sure though.

    Check this for reference https://gis.stackexchange.com/questions/91765/improve-speed-of-postgis-nearest-neighbor-query/

提交回复
热议问题