假设我有以下模型:
from django.db import models
from django.contrib.gis.db import models as gis_models
class Place(models.Model):
location = gis_models.PointField(geography=True, srid=4326)
稍后我将在这些地方进行搜索;我的问题是";在离我不远N米的地方获取所有位置":
from django.contrib.gis.db.models.functions import Distance
from django.contrib.gis.geos import Point
location = Point(1.0, 2.0)
distance = 20.0
queryset = queryset.annotate(distance=Distance("location", location)).filter(
distance__lte=distance
)
有没有办法使用PostGIS来优化这些查询?例如,使用索引或相关的东西。
您的代码看起来不像SQL,而且您没有标记编程语言、框架或ORM,所以我会给您一个SQL答案。
要搜索从某一点起小于30的所有geometry
,您可以使用
... WHERE ST_DWithin(geom, 'POINT(1 2)', 30)
要支持的索引是
CREATE INDEX ON tab USING gist (geom);
要创建这样的空间索引,例如可以执行以下操作:
CREATE INDEX unique_index_name ON table_name USING gist (geometry_column);
正如@fresser和@laurenz的建议,正确的索引是GIST索引:
from django.contrib.postgres.indexes import GistIndex
class Place:
...
class Meta:
indexes = [
GistIndex(fields=["location"]),
]
你的问题是你的数据是以度为单位的(EPSG:4326(,你要求的是20分以内的所有数据。这30是以度为单位的,可能包括你的一大块(如果不是全部的话(数据,所以PostGIS太聪明了,不能使用你的索引。