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

问题描述 投票:1回答:1

如何在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'

我看不到我的索引。

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

postgresql indexing database-partitioning postgresql-11
1个回答
1
投票

永远不会真正创建基表的索引,因此它不会显示在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
© www.soinside.com 2019 - 2024. All rights reserved.