在 postgresql 中使用 POSTGIS 查找具有几何数据类型的 KNN
Find KNN with a geometry data type using POSTGIS in postgresql
我想使用 PostGIS 在 postgresql 中为一个点找到 k 个最近的点。
我的 table 的结构是:
CREATE TABLE mylocations
(id integer,
name varchar,
geom geometry);
样本插入行是:
INSERT INTO mylocations VALUES
(5, 'Alaska', 'POINT(-172.7078 52.373)');
我可以使用以下查询通过 ST_Distance() 找到最近的点:
SELECT ST_Distance(geography(geom), 'POINT(178.1375 51.6186)'::geometry) as distance,ST_AsText(geom),name, id
FROM mylocations
ORDER BY distance limit 10;
但实际上我想在不计算我的点与 table 的所有点之间的距离的情况下找到它们。
事实上,我想找到具有最佳性能的最佳查询,因为我的 table 会有大量数据。
我感谢你的想法
您缺少 <->
运算符 Returns the 2D distance between A and B
。确保您的 geom
类型和 SRID
相同。
SELECT ST_Distance(geom,
'POINT(178.1375 51.6186)'::geometry) as distance,
ST_AsText(geom),
name, id
FROM mylocations
ORDER BY geom <-> 'POINT(178.1375 51.6186)'::geometry limit 10
我终于可以用这个查询来回答我的问题了:
SELECT id, name
FROM mylocations
WHERE ST_DWithin(geom::geography,
ST_GeogFromText('POINT(-73.856077 40.848447)'),
1609, false);
实际上我想给一个点作为半径为 1609(以米为单位)的圆心,并让所有邻居到圆心的距离小于 1609 米。
我想使用 PostGIS 在 postgresql 中为一个点找到 k 个最近的点。
我的 table 的结构是:
CREATE TABLE mylocations
(id integer,
name varchar,
geom geometry);
样本插入行是:
INSERT INTO mylocations VALUES
(5, 'Alaska', 'POINT(-172.7078 52.373)');
我可以使用以下查询通过 ST_Distance() 找到最近的点:
SELECT ST_Distance(geography(geom), 'POINT(178.1375 51.6186)'::geometry) as distance,ST_AsText(geom),name, id
FROM mylocations
ORDER BY distance limit 10;
但实际上我想在不计算我的点与 table 的所有点之间的距离的情况下找到它们。 事实上,我想找到具有最佳性能的最佳查询,因为我的 table 会有大量数据。 我感谢你的想法
您缺少 <->
运算符 Returns the 2D distance between A and B
。确保您的 geom
类型和 SRID
相同。
SELECT ST_Distance(geom,
'POINT(178.1375 51.6186)'::geometry) as distance,
ST_AsText(geom),
name, id
FROM mylocations
ORDER BY geom <-> 'POINT(178.1375 51.6186)'::geometry limit 10
我终于可以用这个查询来回答我的问题了:
SELECT id, name
FROM mylocations
WHERE ST_DWithin(geom::geography,
ST_GeogFromText('POINT(-73.856077 40.848447)'),
1609, false);
实际上我想给一个点作为半径为 1609(以米为单位)的圆心,并让所有邻居到圆心的距离小于 1609 米。