# clustering

This module contains functions that perform clustering on geographies.

## ST\_CLUSTERKMEANS <a href="#st_clusterkmeans" id="st_clusterkmeans"></a>

```sql
ST_CLUSTERKMEANS(geog [, numberOfClusters])
```

**Description**

Takes a set of points as input and partitions them into clusters using the k-means algorithm. Returns an array of tuples with the cluster index for each of the input features and the input geometry.

**Input parameters**

* `geojsons`: `ARRAY` points to be clustered.
* `numberOfClusters` (optional): `INT` numberOfClusters that will be generated. By default `numberOfClusters` is `Math.sqrt(<NUMBER OF POINTS>/2)`. The output number of cluster cannot be greater to the number of distinct points of the `geojsons`.

**Return type**

`ARRAY`: containing objects with `cluster`, as the cluster id, and `geom`, as the geometry geojson.

**Examples**

```sql
SELECT CARTO.CARTO.ST_CLUSTERKMEANS(ARRAY_CONSTRUCT(ST_ASGEOJSON(ST_POINT(0, 0))::STRING, ST_ASGEOJSON(ST_POINT(0, 1))::STRING, ST_ASGEOJSON(ST_POINT(5, 0))::STRING, ST_ASGEOJSON(ST_POINT(1, 0))::STRING));
-- {"cluster": 0, "geom": "{\"coordinates\":[0,0],\"type\":\"Point\"}"}
-- {"cluster": 0, "geom": "{\"coordinates\":[0,1],\"type\":\"Point\"}"}
-- {"cluster": 0, "geom": "{\"coordinates\":[5,0],\"type\":\"Point\"}"}
-- {"cluster": 0, "geom": "{\"coordinates\":[1,0],\"type\":\"Point\"}"}
```

```sql
SELECT CARTO.CARTO.ST_CLUSTERKMEANS(ARRAY_CONSTRUCT(ST_ASGEOJSON(ST_POINT(0, 0))::STRING, ST_ASGEOJSON(ST_POINT(0, 1))::STRING, ST_ASGEOJSON(ST_POINT(5, 0))::STRING, ST_ASGEOJSON(ST_POINT(1, 0))::STRING), 2);
-- {"cluster": 1, "geom": "{\"coordinates\":[0,0],\"type\":\"Point\"}"}
-- {"cluster": 1, "geom": "{\"coordinates\":[0,1],\"type\":\"Point\"}"}
-- {"cluster": 0, "geom": "{\"coordinates\":[5,0],\"type\":\"Point\"}"}
-- {"cluster": 1, "geom": "{\"coordinates\":[1,0],\"type\":\"Point\"}"}
```

{% hint style="info" %}
**Additional examples**

* [New supplier offices based on store locations clusters](https://academy.carto.com/advanced-spatial-analytics/spatial-analytics-for-snowflake/step-by-step-tutorials/new-supplier-offices-based-on-store-locations-clusters)
  {% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.carto.com/data-and-analysis/analytics-toolbox-for-snowflake/sql-reference/clustering.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
