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?
WAREHOUSE.property_fileandproperty_filethe same table? It would be helpful if you shared the polygon geojson.