This topic describes the ST_ClusterWithin function. This function returns an array of GeometryCollection objects, each of which represents a set of geometry objects that are separated by no more than the specified distance.

Syntax

geometry[]  ST_ClusterWithin(geometry set  g , float8  distance);

Parameters

ParameterDescription
Parameter Description
g The geometry objects that you want to specify.
distance The distance that you want to use for clustering.

Description

The distance that you specify is a cartesian distance that is expressed by using spatial reference identifiers (SRIDs).

Examples

  • Obtain an array of GeometryCollection objects with the default parameter settings retained.
    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;
                               st_astext
    ---------------------------------------------------------------
     GEOMETRYCOLLECTION(LINESTRING(0 0,0 1),LINESTRING(2 3,3 3),LINESTRING(0 1,2 3))
     GEOMETRYCOLLECTION(POINT(-1 -1))
    (2 rows)
    
  • Obtain an array of GeometryCollection objects with the distance for clustering set to 2.
    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;
                               st_astext
    ---------------------------------------------------------------
     GEOMETRYCOLLECTION(LINESTRING(0 0,0 1),LINESTRING(2 3,3 3),LINESTRING(0 1,2 3),POINT(-1 -1))
    (1 row)