☰
supabase-postgres-best-practices - query-index-types
2026/10/15 3:38:05 网站建设 项目流程

title: Choose the Right Index Type for Your Data
impact: HIGH
impactDescription: 10-100x improvement with correct index type
tags: indexes, btree, gin, gist, brin, hash, index-types

为你的数据选择正确的索引类型

不同的索引类型擅长不同的查询模式。默认的 B-tree 并不总是最优选择。

错误做法(对 JSONB 包含查询使用 B-tree):

-- B-tree 无法优化包含运算符createindexproducts_attrs_idxonproducts(attributes);select*fromproductswhereattributes @>'{"color": "red"}';-- 全表扫描——B-tree 不支持 @> 运算符

正确做法(JSONB 使用 GIN):

-- GIN 支持 @>, ?, ?&, ?| 运算符createindexproducts_attrs_idxonproductsusinggin(attributes);select*fromproductswhereattributes @>'{"color": "red"}';

索引类型指南:

-- B-tree(默认):=, <, >, BETWEEN, IN, IS NULLcreateindexusers_created_idxonusers(created_at);-- GIN:数组、JSONB、全文搜索createindexposts_tags_idxonpostsusinggin(tags);-- GiST:几何数据、范围类型、最近邻(KNN)查询createindexlocations_idxonplacesusinggist(location);-- BRIN:大型时序表(体积小 10-100 倍)createindexevents_time_idxoneventsusingbrin(created_at);-- Hash:仅等值比较(对 = 比 B-tree 略快)createindexsessions_token_idxonsessionsusinghash(token);

参考:索引类型

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询