Assigns a cluster ID to each geometry object using the 2D K-means algorithm.
Syntax
integer ST_ClusterKMeans(geometry winset geom, integer numberOfClusters);Return value: An integer representing the cluster ID assigned to each geometry object.
Parameters
| Parameter | Description |
|---|---|
geom | The geometry objects to cluster. |
numberOfClusters | The number of clusters to generate. |
Usage notes
ST_ClusterKMeansis a window function. Call it with anOVER()clause.Clustering distance is calculated as the distance between the centroids of the input geometry objects.
Examples
Basic clustering
The following example clusters four 2D points into two groups.
SELECT ST_ClusterKMeans(geom, 2) OVER(), ST_AsText(geom)
FROM (
SELECT unnest(ARRAY[
'POINT (0 0)'::geometry,
'POINT(1 1)'::geometry,
'POINT (-1 -1)'::geometry,
'POINT (-2 -2)'::geometry
]) AS geom
) AS test;Output:
st_clusterkmeans | st_astext
------------------+--------------
0 | POINT(0 0)
0 | POINT(1 1)
1 | POINT(-1 -1)
1 | POINT(-2 -2)
(4 rows)