An aggregate function that clusters input geometries by separation distance and returns an array of GeometryCollection objects.
Syntax
geometry[] ST_ClusterWithin(geometry set g, float8 distance)Parameters
| Parameter | Type | Description |
|---|---|---|
g | geometry set | The set of geometry objects to cluster. As an aggregate function, ST_ClusterWithin accepts a set of rows, not a single value. |
distance | float8 | The maximum separation distance between geometries in the same cluster. Expressed as a Cartesian distance in the units of the spatial reference identifier (SRID). |
Description
ST_ClusterWithin groups geometries that are within distance of each other into a single GeometryCollection. Geometries separated by more than distance are placed in separate collections. The function returns one GeometryCollection per cluster.
Because this is an aggregate function, use unnest() to expand the returned array into individual rows.
Examples
The following examples use four geometry objects — three connected line strings and one isolated point — to demonstrate how the distance threshold controls cluster formation.
Spatial layout: LINESTRING (0 1,2 3) bridges LINESTRING (0 0,0 1) and LINESTRING (2 3,3 3), keeping the three line strings within distance 1 of each other. POINT (-1 -1) is more than distance 1 away from all line strings, so it forms its own cluster.
Example 1: Distance threshold = 1
With distance = 1, the three connected line strings form one cluster and the isolated point forms another.
SELECT ST_AsText(unnest(ST_ClusterWithin(geom, 1)))
FROM (
SELECT ARRAY[
'LINESTRING (0 0,0 1)'::geometry,
'LINESTRING (2 3,3 3)'::geometry,
'LINESTRING (0 1,2 3)'::geometry,
'POINT (-1 -1)'::geometry
] AS geom
) AS test;Output:
st_astext
---------------------------------------------------------------
GEOMETRYCOLLECTION(LINESTRING(0 0,0 1),LINESTRING(2 3,3 3),LINESTRING(0 1,2 3))
GEOMETRYCOLLECTION(POINT(-1 -1))
(2 rows)Example 2: Distance threshold = 2
With distance = 2, the point falls within distance 2 of the nearest line string, so all four geometries merge into a single cluster.
SELECT ST_AsText(unnest(ST_ClusterWithin(geom, 2)))
FROM (
SELECT ARRAY[
'LINESTRING (0 0,0 1)'::geometry,
'LINESTRING (2 3,3 3)'::geometry,
'LINESTRING (0 1,2 3)'::geometry,
'POINT (-1 -1)'::geometry
] AS geom
) AS test;Output:
st_astext
---------------------------------------------------------------
GEOMETRYCOLLECTION(LINESTRING(0 0,0 1),LINESTRING(2 3,3 3),LINESTRING(0 1,2 3),POINT(-1 -1))
(1 row)What's next
ST_ClusterDBSCAN — DBSCAN-based clustering with configurable minimum point density
ST_ClusterIntersecting — groups geometries that spatially intersect
ST_ClusterKMeans — k-means clustering that partitions geometries into a fixed number of clusters