從PostGIS 2.0開始踢涌,geometry 類型的數(shù)據(jù)支持KNN算法。下面的例子示范查找最近點
關(guān)于<->,詳見PostgreSQL manual
SELECT *
FROM your_table
ORDER BY your_table.geom <-> "your location..."
LIMIT 1;
例:
//創(chuàng)建表
CREATE TABLE "nts_io_postgis_2d" (id serial primary key, wkt text,name text);
SELECT AddGeometryColumn('nts_io_postgis_2d', 'the_geom', 4326 ,'GEOMETRY', 2)
插入數(shù)據(jù)如下:
| id | wkt | name | the_geom |
| 1 | POINT (4 4) | | 010100002... |
| 2 | POINT (6 6) | | 010100002... |
| 3 | LINESTRING (5 0, 5 10, 5 20) | | 010200002... |
| 4 | LINESTRING (5 0, 5 10, 5 20) | | 010200002... |
| 5 | LINESTRING (5 0, 5 10, 5 20) | | 010300000... |
select ST_AsText(the_geom)
from public.nts_io_postgis_2d
order by the_geom <-> ST_PointFromText('POINT(2 2)',4326)
limit 1
--returns
LINESTRING(5 0,5 10,5 20)
再比如,加入Geometry類型過濾條件,比如只查找距離目標(biāo)地物最近的點癞尚,使用ST_GeometryType
命令,返回ST_Point榜配、ST_LineString否纬、ST_Polygon
等。
select ST_AsText(the_geom)
from public.nts_io_postgis_2d
where ST_GeometryType(the_geom) = 'ST_Point'
order by the_geom <-> ST_PointFromText('POINT(0 0)',4326)
limit 1
--returns
POINT(4 4)