Skip to main content

索引

下面是使用 PostgreSQL 数据库的每种索引类型的示例:

  1. 创建索引 (Create Index)
CREATE INDEX idx_customer_name ON customers (name);

这个命令在 customers 表的 name 列上创建一个标准的索引。

  1. 唯一索引 (Unique Index)
CREATE UNIQUE INDEX idx_unique_email ON customers (email);

这个命令在 customers 表的 email 列上创建一个唯一索引,确保 email 列中的值不会重复。

  1. 表达式索引 (Index on Expression)
CREATE INDEX idx_lower_name ON customers (LOWER(name));

这个命令在 customers 表的 name 列上创建一个基于表达式的索引,索引的表达式是列值转换为小写。

  1. 部分索引 (Partial Index)
CREATE INDEX idx_active_customers ON customers (name) WHERE active = TRUE;

这个命令在 customers 表的 name 列上创建一个部分索引,只包括 active 列为 TRUE 的行。

  1. 多列索引 (Multicolumn Indexes)
CREATE INDEX idx_customer_name_dob ON customers (name, date_of_birth);

这个命令在 customers 表的 namedate_of_birth 列上创建一个多列索引。

  1. 重建索引 (Reindex)
REINDEX INDEX idx_customer_name;

这个命令用于重建 idx_customer_name 索引。

  1. 列出索引 (List indexes)
SELECT indexname, indexdef FROM pg_indexes WHERE tablename = 'customers';

这个命令列出 customers 表的所有索引及其定义。

  1. 删除索引 (Drop Index)
DROP INDEX idx_customer_name;

这个命令用于删除 idx_customer_name 索引。

  1. 索引类型 (Index Types)

    • B-Tree Index
      CREATE INDEX idx_btree ON customers USING btree (name);
    • Hash Index
      CREATE INDEX idx_hash ON customers USING hash (name);
    • GIN Index
      CREATE INDEX idx_gin ON documents USING gin (content);
    • GiST Index
      CREATE INDEX idx_gist ON geography_data USING gist (geo_column);
  2. 全文搜索 (Full Text Search)

CREATE INDEX idx_fts_gin ON articles USING gin (to_tsvector('english', content));

这个命令在 articles 表的 content 列上创建一个 GIN 索引,以支持全文搜索。

  1. JSON 索引 (JSON Index)
CREATE INDEX idx_jsonb_data ON orders USING gin (data jsonb_path_ops);

这个命令在 orders 表的 data 列(JSONB 类型)上创建一个 GIN 索引,优化基于 JSONB 路径的查询性能。