Dissolve Shapefiles using OGR
Quite often, I’ll run across a large or complex shapefile that causes issues (crashing, very poor performance, etc) in QGIS or other desktop GIS.
However, sometimes you have to find a way to deal with these files, and not spend a lot of time worrying about them. Often, the best way is to head back to the mysterious black box that is the command line, and use the ultra-stable suite of tools available there. My favourite for spatial work is GDAL/OGR
I was recently struggling to do a simple dissolve on a large and complex shapefile. I didn’t want to bring it into a database, but QGIS would crash trying to dissolve the shapefile. Of course, OGR had no problem with the file!
Here’s how to turn this (nine features with three different attributes):
Into this (three attributes, three multi-part features!):
Simply use this command (substituting your file names and field names as appropriate) into ogr, and you’re all set!
ogr2ogr outputfile.shp inputfile.shp -dialect sqlite -sql “SELECT dissolvefield,ST_Union(geometry) as geometry FROM inputfile GROUP BY dissolvefield”
Posted: January 23rd, 2015 under GIS.
Comments
Comment from Marcelo
Time March 17, 2015 at 12:46 am
Hi,
Thanks for the easy way. You need to add single quotes to the input file source inside the sql statement … FROM ‘input file’ …
Best,
Marcelo
Comment from Ivan Gonzalez
Time April 21, 2016 at 9:15 pm
Works perfect. Thanks a lot!!
Comment from maggie
Time May 5, 2017 at 6:29 pm
Hi Darren,
Thank you for this post. As I am not familiar with SQL, how can I edit this command to dissolve a shapefile NOT based on fields, but only based on geography (i.e. dissolve polygons that are touching together no matter the attribute value)? I’ve tried many things and can’t get it to work. Thank you!
Comment from darrencope
Time May 7, 2017 at 7:25 am
Hi maggie,
Excellent question! It’s as simple as leaving out the dissolvefield value altogether, and just running the ST_Union command. For example:
ogr2ogr outputfile.shp inputfile.shp -dialect sqlite -sql “SELECT ST_Union(geometry) as geometry FROM inputfile”
Hope this helps!
Comment from Adam
Time January 21, 2018 at 12:14 pm
This helped me out – thanks for taking the time to make this blog post!
Pingback from Dissolve Shapefiles using OGR | Geo-How-To News
Time January 24, 2015 at 8:31 pm
[…] http://darrencope.com/2015/01/23/dissolve-shapefiles-using-ogr/ […]