Question

I currently have a postgres database in which I store a data about a photo, along with the location as a JSON (using Django). The location is obtained through GooglePlacesAPI- https://developers.google.com/places/documentation/search (search for Search Responses for example responses)

So currently, every photo has a location column which contains the JSON information for the place as obtained from the GooglePlacesAPI

Now I would like to use Postgres' spatial capabilities to query based on the location, however I am not sure how to do that and what schema changes are required. The Postgres documentation seems to indicate that there would be a new table required with the location's name, lat, lng and other information. So does that mean that every location will be saved in a different table and will have a foreign key referenced to that? And so the JSON will need to be essentially flattened to be stored in the table?

If so, is there a recommended table format that would be good to store the location in so that I can get any other location data (say from Foursquare, FB, etc) and convert it to the format of the table before storing.

Was it helpful?

Solution

Geometry is not special: it's just another data type. So add a geometry column to your existing table. Assuming you have installed and enabled PostGIS 2.x:

ALTER TABLE mytable ADD COLUMN geom geometry(Point,4326);

Then populate the geometry data by extracting the data out of the location JSON column (which really depends on how the data are structured within this amorphous column):

UPDATE mytable SET
  geom = ST_SetSRID(ST_MakePoint((location->>'lng')::numeric,
                                 (location->>'lat')::numeric), 4326)

And that should be a start. Later steps would be to build GiST indices and do spatial queries with other tables or points of interests. You may also want to consider the geography data type, instead of the geometry data type, depending on your needs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top