← 中文资源

简体中文版本

GiST KNN 按距离排序取最近

GiST 索引支持 KNN 排序:ORDER BY location <-> point 直接按由近到远返回行,无需额外排序,适合找最近网点这类查询。

阅读英文原文

实现说明

一个文件里不止一条语句:SELECT / INSERT / CREATE,depots 都在涉及之列。 depots 是这个文件自己建的会话级临时表——建表动作就在文件里,会话一结束它们就消失。 具体组合了这些手段:ORDER BY 固定了输出顺序;LIMIT 限制返回行数;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。

常见问题

说出这个文件涉及的表。

引用的是 depots。

核心语句

INSERT INTO depots VALUES
    ('alpha', point '(1, 1)'),
    ('beta',  point '(5, 5)'),
    ('gamma', point '(2, 9)'),
    ('delta', point '(8, 2)');
SELECT name, location, round(location <-> point '(2, 2)', 2) AS distance
FROM depots
ORDER BY location <-> point '(2, 2)'
LIMIT 3;
CREATE TEMP TABLE depots (
    name     text PRIMARY KEY,
    location point NOT NULL
);

代码示例

-- 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;