2

I have a global dataset of ecoregion boundaires. There are ~809 unique polygons in this dataset. I've imported it into PostGIS with SRS of 4326 and built a spatial index using the function below

CREATE INDEX ecoregionsindex ON ecoregions USING gist(geom);

Querying with a point takes ~150ms to run

SELECT id FROM "ecoregions"
WHERE ST_Within (ST_PointFromText('POINT(-111 45)', 4326), geom);

Buffering ~20,000m around this point using the ST_DWithin() method takes about 15,000ms to run.

SELECT id
FROM "ecoregions"
WHERE ST_DWithin(ecoregions.geom, ST_MakePoint(-111,45)::geography, 
20000);

Is there a way to optimize my data or the query above to run more quickly?

jotamon
  • 1,737
  • 2
  • 28
  • 46

1 Answers1

5

You need to construct your index the way you are gonna use it. If you cast on your call, you need to cast the same way on your index (here you need to create your index on the geography version of your point):

CREATE INDEX ecoregionsindex_geog ON ecoregions USING gist(CAST(geom AS geography));

Note that the :: shortcut don't work for indexes. Don't forget to analyze after:

ANALYZE ecoregions;
robin loche
  • 2,465
  • 5
  • 9