Monday 22 April 2019

How to rename PostgreSQL/PostGIS columns while importing Shapefiles?


I discovered shp2psql to successfully import geospatial data from ESRI Shapefiles into PostgreSQL/PostGIS.
Now I would like to automatically rename the target column names. Is there any mechanism where I can define the original column names and their corresponding target column names in something such as a look-up table? Or would you do the renaming within the database using triggers or rules? Or do you recommend another import tool?



Answer



To expand on David Bitner's answer, here's an example ogr2ogr instruction demonstrating an optional OGR SQL clause to rename fields from a source dataset (shapefile in this case) before they are brought into a target dataset (a PostGREsql table):


ogr2ogr -f "PostGreSQL" PG:"host=127.0.0.1 user=YourUser dbname=YourDB password=YourPass"
"E:\path\to\YourShapefile.shp" -nln NewTableName -nlt geometry

-sql "SELECT col_1 AS BetterName, col_2 AS ImprovedName FROM YourShapefile"
-lco GEOMETRY_NAME=the_geom


  • -nln Allows you to provide a name for the new PostGREsql table

  • -nlt Will allow multipart and singlepart features to exist in the same table

  • -sql The OGR SQL clause renaming the source fields

  • -lco GEOMETRY_NAME=the_geom By default ogr2ogr names the geometry field wkb_geometry, but we can use a Layer Creation Option (-lco) to name it something else, like the_geom so it will share this convention with shp2pgsql..


Gotchas: A valid ogr2ogr instruction should not have any line breaks. Also, I've had trouble copying single quotes (') and double quotes (") from web examples and pasting them into the terminal. Perhaps it's a weird unicode issue? So it's recommended to type your command in a simple text editor like notepad before pasting it into the terminal. Or just type it directly into the terminal. Either way the point is beware copy-and-pasted quotes and double quotes.



No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...