All Products
Search
Document Center

ApsaraDB RDS:ST_ClusterKMeans

Last Updated:Mar 28, 2026

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

ParameterDescription
geomThe geometry objects to cluster.
numberOfClustersThe number of clusters to generate.

Usage notes

  • ST_ClusterKMeans is a window function. Call it with an OVER() 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)