In PostGIS version 2.3, some cluster functionalities were introduced. In this recipe, we will explore ST_ClusterKMeans, a function that aggregates geometries into k clusters and retrieves the id of the assigned cluster for each geometry in the input. The general syntax for the function is as follows:
ST_ClusterKMeans(geometry winset geom, integer number_of_clusters);