← 中文资源

简体中文版本

SP-GiST 索引支撑前缀搜索

USING spgist (url text_ops) 建空间分区树索引:常量前缀 LIKE 直接命中分支;中缀 %…% 与 btree 一样不支持,子串搜索要另配 pg_trgm 加 GIN 索引。

阅读英文原文

实现说明

一个文件里不止一条语句:SELECT / INSERT / CREATE / EXPLAIN,endpoints 都在涉及之列。 endpoints 是这个文件自己建的会话级临时表——建表动作就在文件里,会话一结束它们就消失。 逐子句看,这些语句使用了:WHERE 把语句的作用范围收窄到满足条件的行;必填列上的 NOT NULL 限定。

常见问题

说出这个文件涉及的表。

endpoints——名字即引用,连接不在流程里。

核心语句

EXPLAIN (COSTS OFF)
SELECT url FROM endpoints WHERE url LIKE '/api/v2/%';
EXPLAIN (COSTS OFF)
SELECT url FROM endpoints WHERE url LIKE '%orders%';
INSERT INTO endpoints (url) VALUES
    ('/api/v2/orders'), ('/api/v2/orders/42'), ('/api/v2/users'),
    ('/api/v1/health'), ('/static/logo.svg');

代码示例

-- SP-GiST: a space-partitioned tree index. text_ops supports prefix matching,
-- more space-efficient than btree when values share long prefixes (paths, serial numbers, domains)
CREATE TEMP TABLE endpoints (
    url text NOT NULL
);

INSERT INTO endpoints (url) VALUES
    ('/api/v2/orders'), ('/api/v2/orders/42'), ('/api/v2/users'),
    ('/api/v1/health'), ('/static/logo.svg');

CREATE INDEX idx_endpoints_url_spgist
    ON endpoints USING spgist (url text_ops);

-- LIKE with a constant prefix can use SP-GiST: the tree branches by prefix and lands directly on the right subtree
EXPLAIN (COSTS OFF)
SELECT url FROM endpoints WHERE url LIKE '/api/v2/%';

-- infix '%...%' does not qualify: like btree, SP-GiST only serves patterns anchored at the front
-- for substring search, add a pg_trgm + GIN index separately
EXPLAIN (COSTS OFF)
SELECT url FROM endpoints WHERE url LIKE '%orders%';