Search code examples
postgresqlgispostgis

How to use database index correctly when searching on geo field?


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.


Solution

  • As @fresser and @laurenz-albe helpfully suggested, the correct index is GIST index:

    from django.contrib.postgres.indexes import GistIndex
    
    class Place:
        ...
    
        class Meta:
            indexes = [
                GistIndex(fields=["location"]),
            ]