Skip to content

ST_KNN

Returns true if geomA finds k nearest neighbors from geomB.

Usage

boolean ST_KNN(geomA: geometry, geomB: geometry, k: integer, use_spheroid: boolean)
boolean ST_KNN(geomA: geometry, geomB: geometry, k: integer)
boolean ST_KNN(geomA: geometry, geomB: geometry)

Arguments

  • geomA (geometry): The geometry around which to search.
  • geomB (geometry): Column containing candidate geometries.
  • k (integer): The number of nearest neighbours to return. Defaults to 1.
  • use_spheroid (boolean): true to use spherical distance, false for Euclidean. Defaults to false.

Description

ST_KNN is used in a join condition to find the k nearest neighbors of one geometry from another set of geometries. The actual k-nearest neighbors logic is handled by the spatial join execution engine: the function itself is a stub that simply defines the expected signature.

Examples

WITH table2 AS (
    SELECT geom1 FROM (VALUES
        (ST_Point(0, 1)),
        (ST_Point(2, 3)),
        (ST_Point(4, 5)),
        (ST_Point(6, 7)),
        (ST_Point(8, 9))
    ) AS t(geom1)
),
table1 AS (
    SELECT ST_Point(0, 0) AS geom2
)
SELECT * FROM table1 JOIN table2 ON ST_KNN(geom1, geom2, 3);
┌────────────┬────────────┐
│    geom2   ┆    geom1   │
│  geometry  ┆  geometry  │
╞════════════╪════════════╡
│ POINT(0 0) ┆ POINT(0 1) │
├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ POINT(0 0) ┆ POINT(2 3) │
├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ POINT(0 0) ┆ POINT(4 5) │
├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ POINT(0 0) ┆ POINT(6 7) │
├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ POINT(0 0) ┆ POINT(8 9) │
└────────────┴────────────┘