0

I am trying to retrieve all of the points from a table which are within a GEOJSON polygon. I am running everything below through a Python function.

So, I created a table from a CSV file of open data which shows all of the house sales in a region. Each record has a latitude and longitude and I create a Point column on the table using these, so this is the syntax I use:

ST_GeomFromText(CONCAT('POINT(', %(longitude)s, ' ', %(latitude)s, ')'), 4326))

Then I want to do two queries later, the first one if to find the 10 closest records to a location which I pass and this works, this query looks like this:

closest_properties_query = f"""
    SELECT *
    FROM property_file
    WHERE date_of_sale BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 YEAR) AND CURDATE()
    AND ST_SRID(GEOMETRY) = 4326
    ORDER BY 
    ST_Distance_Sphere(ST_GeomFromText(CONCAT('POINT(', {longitude}, ' ', {latitude}, ')'), 4326), GEOMETRY) ASC
    LIMIT 10
"""

But I also want to construct a ‘dictionary’ of the last 5 years sales which happened with a polygon. The polygon represents a drivetime and is in GEOJSON form. I have checked the GEOJSON on a Jupyter folium map and it looks fine. I have tried ST_Within, ST_Contains and ST_Intersects and I have even swapped the parameters around. This is the latest version I have tried:

SELECT
YEAR(date_of_sale) as sale_year,
COUNT(*) as year_count
FROM WAREHOUSE.property_file
WHERE 
ST_Within(GEOMETRY, ST_GeomFromGeoJSON('{geojson_str}'))
AND YEAR(date_of_sale) BETWEEN {five_years_ago} AND {current_year}
GROUP BY YEAR(date_of_sale)
ORDER BY sale_year;

If I remove the geography parameter I get results for the last 5 years but if I include the geography parameter I always get {} returned. I know there is data in there because when I use Shapely on a memory object which contains the same data as the table it works. I suspect the GEOMETRY column is not being built correctly but if that is the case I do not understand how the first query works (again I have verified the results of that against the Shapely/Memory object query).

Could anyone shed any light on where I may be going wrong?

2
  • are WAREHOUSE.property_fileand property_file the same table? It would be helpful if you shared the polygon geojson. Commented Aug 14, 2023 at 18:20
  • Make sure the polygon has the same SRID as your point geometry Commented Aug 14, 2023 at 18:28

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.