PostGIS recursive query in order to find the longest connected subnetwork in my line network
The key here is to collect the visited edges into a path array and check against that in each iteration. Try
WITH RECURSIVE
connected_line AS (
SELECT 0 AS it,
ARRAY[a.id] AS path,
a.geom AS geom
FROM network a
WHERE id = 1
UNION ALL
SELECT c.it + 1 AS it
array_append(c.path, b.id) AS path,
b.geom AS geom
FROM network b
JOIN connected_line c
ON ST_Intersects(b.geom, c.geom)
AND b.id <> ALL(c.path)
)
SELECT it,
path,
geom
FROM connected_line;
Note:
This approach works if there is always exactly one connected edge that has not yet been found. However, it produces one path for each branch when the network forks and will find already visited edges when they were found in different paths.
If your question is answered by simply finding all connected sub-networks and get the longest, try ST_ClusterDBSCAN
with eps := 0
and search for the max ST_Length
of the clusters collected components. This way, you could also specify attributes to cluster (i.e. specify the sub-network type) for if you need to (in the mandatory OVER()
clause, e.g. OVER(PARTITION BY <attribute>
).