在GeoDjango中获取最接近几何图形的最快方法 [英] Fastest way to get nearest geometry to a point in GeoDjango
问题描述
我在WGS84坐标系中有大量点(约150万个).这些点的面积很大,因此无法使用投影坐标系.我想找到最接近给定输入坐标对的点.我有一个有效的视图,但是执行时间太长(约2.5秒).
I've got a large number of points (~1.5 million) in the WGS84 coordinate system. The points span a large area, so I can't use a projected coordinate system. I want to find the closest point to a given pair of input coordinates. I have a working view, but it takes too long (~2.5 seconds) to execute.
这是我的模特
from django.contrib.gis.db import models
class Point(models.Model):
id = models.IntegerField(primary_key=True)
geom = models.PointField(srid=4326, spatial_index=True)
objects = models.GeoManager()
这是视图中的查询(这是我从另一个SO问题获得的):
This is the query in the view (which I got from another SO question):
input_point = GEOSGeometry('POINT({0} {1})'.format(lon, lat))
point = Point.objects.distance(input_point).order_by('distance')[0]
有没有办法更快地做到这一点?我在SQLAlchemy/GeoAlchemy2中有一个等效的查询,执行该查询所需的时间不到0.5秒,所以我知道这是可能的.
Is there a way to do this faster? I have an equivalent query in SQLAlchemy/GeoAlchemy2, which takes less than 0.5 seconds to execute, so I know it's possible.
from geoalchemy2.elements import WKTElement
pt = WKTElement('POINT({0} {1})'.format(lon, lat), srid=4326)
q = session.query(Point).order_by(Point.geom.distance_box(pt)).first()
是否有更好的方法通过GeoDjango进行最近点"查询?
Is there a better way to do "nearest point" queries with GeoDjango?
推荐答案
不确定,这可能会更快.您可以使用Google投影( 900913
)来获取以米为单位的数据.
Not sure, this may be faster. You can use the google projection (900913
) to get your data in meters.
from django.contrib.gis.measure import D
DISTANCE_LIMIT_METERS = 5000
input_point = Point(lon, lat, srid=4326)
input_point.transform(900913)
ModelContainingPoint.objects.filter(geom__dwithin=(input_point , D(m=DISTANCE_LIMIT_METERS)))
参考:
https://docs.djangoproject.com/en/dev/ref/contrib/gis/db-api/#distance-queries
这篇关于在GeoDjango中获取最接近几何图形的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!