All Products
Search
Document Center

PolarDB:ST_ClusterKMeans

Last Updated:Mar 28, 2026

Assigns a cluster ID to each input geometry using the 2D K-means algorithm.

Syntax

integer ST_ClusterKMeans(geometry winset geom, integer numberOfClusters);

Parameters

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

Usage notes

  • Clustering distance is calculated between the centroids of the input geometries.

  • ST_ClusterKMeans is a window function. Use it with an OVER clause.

Example

The following query assigns cluster IDs to four points.

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)