Skip to content

KDTree Quickstart

KDTree indexes a 2D NumPy array of points and answers exact k-nearest-neighbor queries.

Build A Tree

import numpy as np
from fastspatial import KDTree

points = np.array(
    [
        [0.0, 0.0],
        [1.0, 1.0],
        [2.0, 2.0],
        [10.0, 10.0],
    ],
    dtype=np.float64,
)

tree = KDTree(points, leafsize=16)

Query One Point

indices, distances = tree.knn(np.array([1.2, 1.1], dtype=np.float64), k=2)

print(indices)
print(distances)

indices are row indices into the original input array. distances are Euclidean distances sorted nearest-first.

Query Many Points

Use knn_many() for throughput-oriented workloads.

queries = np.array(
    [
        [1.2, 1.1],
        [9.0, 9.5],
    ],
    dtype=np.float64,
)

indices, distances = tree.knn_many(queries, k=2)

print(indices.shape)    # (2, 2)
print(distances.shape)  # (2, 2)

Practical Notes

  • Input data must be a finite float64 array shaped (n_points, n_dims).
  • Query arrays must have the same dimensionality as the indexed points.
  • k is capped to the number of indexed points.
  • knn() is best for ergonomic single-query calls.
  • knn_many() is best when querying many points because it uses the native batch path and avoids repeated Python call overhead.