How to speed up query that use postgis extension?

Viewed 1185

I have the following query that checks whether is point (T.latitude, T.longitude) is inside a POLYGON

query = """
  SELECT id
  FROM T
  WHERE ST_Intersects(ST_Point(T.latitude, T.longitude), 'POLYGON(({points}))')
"""

But it works slow, how can I speed up it if I have the following index: (latitude, longitude)?

The query is slow because it must compute the formula for every possible pair of points. So it makes the postgress server do a lot of math, and it forces it to scan through your whole location table. How can we optimize this? Maybe we can eliminate the points that are too far north or too far south or too far east or west?

2 Answers
Related