GiST KNN Orders By Distance
GiST indexes answer nearest-neighbor queries directly: ORDER BY location <-> point returns rows from nearest to farthest without a sort step.
Code
-- ORDER BY the <-> distance operator: KNN orders rows nearest-first
CREATE TEMP TABLE depots (
name text PRIMARY KEY,
location point NOT NULL
);
INSERT INTO depots VALUES
('alpha', point '(1, 1)'),
('beta', point '(5, 5)'),
('gamma', point '(2, 9)'),
('delta', point '(8, 2)');
CREATE INDEX depots_location_gist ON depots USING gist (location);
-- 离 (2, 2) 最近的补给点:alpha 最近,其次 beta、delta、gamma
SELECT name, location, round(location <-> point '(2, 2)', 2) AS distance
FROM depots
ORDER BY location <-> point '(2, 2)'
LIMIT 3;Distance as the sort key
CREATE INDEX depots_location_gist ON depots USING gist (location) gives the point column a GiST index, which supports the KNN <-> distance operator directly in ORDER BY — rows come back nearest-first without an explicit sort step over all depots. The query asks for the three depots closest to point '(2, 2)' and prints the same operator’s value rounded to two decimals.
The nearest three
name | location | distance
-------+----------+----------
alpha | (1,1) | 1.41
beta | (5,5) | 4.24
delta | (8,2) | 6
Distances from (2, 2) are √2 ≈ 1.41 for alpha, √18 ≈ 4.24 for beta, 7 for gamma, and 6 for delta — gamma is farther than delta despite its x-coordinate matching, so LIMIT 3 cuts exactly there. The ordering and the reported distance come from the same operator, so the numbers and the row order cannot disagree.
The line that turns the index into ordering
ORDER BY location <-> point '(2, 2)'
LIMIT 3;
With the GiST index present, the planner can walk the index in distance order and stop after three rows instead of computing, sorting, and discarding — that is the KNN support the comment names.
Interactive Tools for This Topic
FAQ
- Name the tables involved in this file.
- The references are `depots`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.