postgresql 中的分区非常适合大型日志。首先创建父表:
create table game_history_log (
gameid integer,
views integer,
plays integer,
likes integer,
log_date date
);
现在创建分区。在这种情况下,每个月一个,900 k 行,会很好:
create table game_history_log_201210 (
check (log_date between '2012-10-01' and '2012-10-31')
) inherits (game_history_log);
create table game_history_log_201211 (
check (log_date between '2012-11-01' and '2012-11-30')
) inherits (game_history_log);
注意每个分区中的检查约束。如果您尝试插入错误的分区:
insert into game_history_log_201210 (
gameid, views, plays, likes, log_date
) values (1, 2, 3, 4, '2012-09-30');
ERROR: new row for relation "game_history_log_201210" violates check constraint "game_history_log_201210_log_date_check"
DETAIL: Failing row contains (1, 2, 3, 4, 2012-09-30).
分区的优点之一是它只会在正确的分区中搜索,无论有多少年的数据,它都会显着且一致地减少搜索大小。这里解释了搜索某个日期:
explain
select *
from game_history_log
where log_date = date '2012-10-02';
QUERY PLAN
------------------------------------------------------------------------------------------------------
Result (cost=0.00..30.38 rows=9 width=20)
-> Append (cost=0.00..30.38 rows=9 width=20)
-> Seq Scan on game_history_log (cost=0.00..0.00 rows=1 width=20)
Filter: (log_date = '2012-10-02'::date)
-> Seq Scan on game_history_log_201210 game_history_log (cost=0.00..30.38 rows=8 width=20)
Filter: (log_date = '2012-10-02'::date)
请注意,除了父表之外,它只扫描了正确的分区。显然,您可以在分区上建立索引以避免顺序扫描。
继承 分区