5

如何在 PostgreSQL 11.2 中的分区表上创建索引?

我的桌子是:

CREATE TABLE sometablename
(
    column1 character varying(255) COLLATE pg_catalog."default" NOT NULL,
    column2 integer NOT NULL,
    column3 character varying(255) COLLATE pg_catalog."default" NOT NULL,
    "timestamp" timestamp without time zone NOT NULL,
    avg_val double precision,
    max_val double precision,
    min_val double precision,
    p95_val double precision,
    sample_count double precision,
    sum_val double precision,
    unit character varying(255) COLLATE pg_catalog."default",
    user_id bigint NOT NULL,
    CONSTRAINT testtable_pkey PRIMARY KEY (column1, column2, column3, "timestamp", user_id)
)
PARTITION BY HASH (user_id) 
    WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;


CREATE UNIQUE INDEX testtable_unique_pkey
ON sometablename USING btree (column1 COLLATE pg_catalog."default", column2
COLLATE pg_catalog."default", "timestamp", user_id)
TABLESPACE pg_default;

如您所见testtable_unique_pkey,是我的索引。

但是当我运行时:

SELECT tablename, indexname, indexdef 
FROM pg_indexes 
WHERE tablename = 'sometablename'

我看不到我的索引。

我检查了对我的查询的解释分析,该查询也没有使用索引。

4

1 回答 1

14

基表的索引从未真正创建,因此它不会显示在pg_indexes

CREATE TABLE base_table
(
    column1 varchar(255) NOT NULL,
    column2 integer NOT NULL,
    user_id bigint NOT NULL
)
PARTITION BY HASH (user_id);
CREATE UNIQUE INDEX idx_one ON base_table (column1, column2, user_id);

因此,以下内容不返回任何内容:

select *
from pg_indexes
where tablename = 'base_table';

然而,它存储在 pg_class 中:

select i.relname as indexname, t.relname as tablename
from pg_class i
  join pg_index idx on idx.indexrelid = i.oid
  join pg_class t on t.oid = idx.indrelid
where i.relkind = 'I'
  and t.relname = 'base_table';

返回:

indexname | tablename 
----------+-----------
idx_one   | base_table

但是对于每个分区,索引将显示在pg_indexes

create table st_p1 partition of base_table for values with (modulus 4, remainder 0);
create table st_p2 partition of base_table for values with (modulus 4, remainder 1);
create table st_p3 partition of base_table for values with (modulus 4, remainder 2);
create table st_p4 partition of base_table for values with (modulus 4, remainder 3);

接着:

select tablename, indexname
from pg_indexes
where tablename  in ('st_p1', 'st_p2', 'st_p3', 'st_p4');

返回:

tablename | indexname                        
----------+----------------------------------
st_p1     | st_p1_column1_column2_user_id_idx
st_p2     | st_p2_column1_column2_user_id_idx
st_p3     | st_p3_column1_column2_user_id_idx
st_p4     | st_p4_column1_column2_user_id_idx

2020 年 6 月 26 日更新:

pg_indexesPostgres 团队承认索引没有出现的事实是一个错误,并在 Postgres 12中修复。

所以上面的解释只对 Postgres 10 和 11 有效。从 Postgres 12 开始,上的索引base_table显示在 `pg_indexes.

于 2019-04-10T12:15:31.687 回答