[GIS] Ogr2Ogr – PostGIS and using existing column for Feature ID

geojsonogr2ogrpostgis

I am importing existing GeoJSON files into a PostgreSQL database using Ogr2Ogr. Some of these files have existing columns we want to use as unique identifiers, and some do not.

I've been unable to find a way to set a given column as a primary key or use an existing column to seed the primary key using variations of this:

.\ogr2ogr.exe -f "PostgreSQL" PG:"{connectionString}" "test.geojson" -nln test -preserve_fid

Is this something Ogr2Ogr supports? Or do I just need to hack it through SQL?

Best Answer

Option -preserve_fid does what it says: GDAL preserves the fid of the source data instead of assigning a new one. For having any effect GDAL must recognize what the fid is in the source data.

In case of GeoJSON there are three possibilities for fid:

  1. By the standard it should be at feature level as a member named "id" http://geojson.org/geojson-spec.html#feature-objects Example:

    { "type": "Feature", "id" : 1, "properties": { "foo": "bar" }...

  2. If feature level "id" does not exist, GDAL checks if feature has an attribute named "id" or "ID". Example:

    { "type": "Feature", "properties": { "id": "1" }...

  3. If GDAL does not find id from GeoJSON at feature level or from the attributes it lets the output driver to assigns a new id.

If your plan is to use some existing attribute that is not "id" as feature id then it is not supported. One option is to rename you unique field into "id". It might be safer to let GDAL to create a new fid field and really hack the changes in with SQL later.

Source: https://trac.osgeo.org/gdal/ticket/6538