你有什么几何之王?你用的是什么投影?
我将假设您的观点在 wgs84 (epsg:4326) 中
如果您希望距离准确,最好在计算中使用地理:
alter points_table add column geog geography
update points_table set geog = geom::geography
创建索引,并运行 cluster 和 analyze 以加快查询速度
create index my_index_geog on points_table using gist(geog) /* change geog for geom if using geometry */
cluster points_table using my_index_geog
analyze points_table
获取最近的点:
SELECT point_id
FROM points_table
ORDER BY geog <-> ST_SetSrid(ST_MakePoint($get_lon, $get_lat),4326)::geography limit 1;
一起获取值:
select value
from table
where point_id = (SELECT point_id
FROM points_table
ORDER BY geog <-> ST_SetSrid(ST_MakePoint($get_lon, $get_lat),4326)::geography limit 1)
order by thedate
limit 1000;
另外,我建议保留一个仅包含点 id 和几何/地理的表,以便最近点查询运行得更快。如果您创建这样的表,称为only_points,则查询变为:
select value
from table
where point_id = (SELECT point_id
FROM only_points
ORDER BY geog <-> ST_SetSrid(ST_MakePoint($get_lon, $get_lat),4326)::geography limit 1)
order by thedate
limit 1000;
如果您需要继续使用geometry,那么您需要在几何上创建索引,基于geom 进行集群并运行查询:
select value
from table
where point_id = (SELECT point_id
FROM points_table
ORDER BY geom::geography <-> ST_SetSrid(ST_MakePoint($get_lon, $get_lat),4326)::geography limit 1)
order by thedate
limit 1000;
但是,它会更慢,因为您将在每一步都转换为地理
见KNN in Postgis和PostGIS geography type and indexes