Suppose i have the following model:
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)
Later i am performing the search on those Places; my query is "fetch all places no further N meters from me":
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
)
Is there any way using PostGIS to optimize those queries? For example, using indexes or something related.
4
Answers
As @fresser and @laurenz-albe helpfully suggested, the correct index is GIST index:
Your code does not look like SQL, and you did not tag a programming language, framework or ORM, so I’ll give you an SQL answer.
To search for all
geometry
s that are less than 30 from a certain point, you would useThe index to support that is
The Postgis funciton ST_DWithin should use relevant bounding box indexes if existing.
To create such a spatial index, you can for example do the following:
Your problem is that your data is in degrees (EPSG:4326) and you ask for everything with in 20 of a point. That 30 is in degrees and probably includes a large chunk (if not all) of your data so PostGIS is too smart to use your index.