I have a table of streets I've selected based on a set of attributes (let's say it's speed_limit < 25
). There are groups of streets that are locally contiguous; I'd like to group these sets of connected linestrings into GeometryCollections. In the image below, there would be two GeometryCollections: one with the red lines and one with the blue lines.
I tried running a couple of "dissolve, deaggregate" queries along the lines of:
SELECT (ST_Dump(st_union)).geom
FROM
(SELECT ST_Union(geom) FROM roads) sq
With everything I've tried, I either end up with a single feature (ST_Union
) or my original geometry (ST_Dump
of ST_Union
).
Maybe it's possible to do this with some kind of WITH RECURSIVE
magic?
Best Answer
So, by example. Here's a simple table with two connected groups of edges:
Now, here's a recursive function that, given the id of an edge, accumulates all the edges that touch:
That just leaves us needing to find, after each group is accumulated, the id of an edge that is not already part of a group. Which, tragically, requires a second recursive query.
Which taken together return a nice set with the seed id and each group it accumulated. I leave it as an exercise to the reader to turn the arrays of id back into a query to create geometry for mapping.