PostgreSQL Partitioning
- เริ่มต้นด้วยมีตารางข้อมูลที่เราต้องการ
create table main_table (
id serial not null,
name varchar(50) ,
provcode char(2) ,
primary key (id));
create index idx_main_table_provcode on main_table (provcode);
ซึ่งจะเป็นตารางที่กำหนด provcode เป็นรหัสจังหวัดซึ่งจะจัดทำ partition โดยแยกตามจังหวัด (ถ้าใครต้องการเปลี่ยนเป็นอย่างอื่นๆก็ได้เช่นวันที่ เป็นต้น
- เมื่อได้ตารางข้อมูลแล้วก็จัดทำตาราง partion ตามที่ต้องการ โดยในตัวอย่างจะใช้ provcode เป็นตัวแยกข้อมูล
create table main_table_part_10 (
check (provcode='10')
) INHERITS (main_table);
create index main_table_part_10_provcode on main_table_part_10 (provcode);
create table main_table_part_11 (
check(provocde='11')
) INHERITS (main_table);
create index main_table_part_11_provcode on main_table_part_11(provcode);
- ให้สร้างฟังก์ชั่นเพื่อใช้ในการกำหนดในการนำเข้าข้อมูลไปยังตารางที่กำหนดเป็น partition
create or repace function main_table_insert()
returns trigger as $$
begin
if (new.provcode='10') then
insert into main_table_part_10 values (new.*);
elseif (new.provcode='11') then
insert into main_table_part_11 values (new.*);
else
raise exception 'Province Code out of range . Fix provcode ';
end if;
end;
$$
language plpgsql;
- เมื่อได้ตารางข้อมูลหลัก และตารางข้อมูลที่จัดเป็นแต่ละ partition แล้ว ให้นำฟังก์ชั่นที่ได้ไปทำการเพิ่มเข้าไปใน definition ของตารางหลักดังนี้
create trigger main_table_insert
before insert on main_table
for each row execute procedure main_table_insert();
- เมื่อได้องค์ประกอบครบถ้วนแล้ว ให้ลองทำการเพิ่มข้อมูลเข้าไปยังตารางข้อมูล โดยให้ทำการเพิ่มเข้าไปยังตารางหลักเท่านั้นส่วนข้อมูลจะวิ่งไปยังตารางที่ถูกต้องเอง เช่น
insert into main_table (name,provcode) values ('test1','10');
insert into main_table (name,provcode) values ('test1','10');
insert into main_table (name,provcode) values ('test3','11');
insert into main_table (name,provcode) values ('test4','11');
- เมื่อต้องการดึงข้อมูลก็ดึงจากตารางหลักเช่นเดียวกัน
select * from main_table where provcode = '10';
ความคิดเห็น
แสดงความคิดเห็น