dezso
来自和的评论中的建议Jack
很好。如果你想要最简单的,那么这就是你实现部分索引的方式:
create table t ("date" bigint, archive boolean default false);
insert into t ("date")
select generate_series(
extract(epoch from current_timestamp - interval '5 year')::bigint,
extract(epoch from current_timestamp)::bigint,
5)
;
create index the_date_partial_index on t ("date")
where not archive
;
为避免更改所有添加索引条件的查询重命名表:
alter table t rename to t_table;
并使用包含索引条件的旧名称创建视图:
create view t as
select *
from t_table
where not archive
;
explain
select *
from t
;
QUERY PLAN
-----------------------------------------------------------------------------------------------
Index Scan using the_date_partial_index on t_table (cost=0.00..385514.41 rows=86559 width=9)
然后每天存档旧行:
update t_table
set archive = true
where
"date" < extract(epoch from current_timestamp - interval '1 week')
and
not archive
;
not archive
条件是避免更新数百万已归档的行。