我在user_logs表中有2亿条记录。我按照策略清除了超过1个月的数据。
创建一个触发器函数来清除超过1个月的数据:
CREATE OR REPLACE FUNCTION delete_old_user_logs()
RETURNS trigger
LANGUAGE 'plpgsql'
AS $$
BEGIN
DELETE FROM user_logs WHERE timestamp < now() - interval '1 month';
RETURN NULL;
END;
$$;
最后,我设置了每次插入新记录时调用的触发器,删除任何超过1个月的记录:
CREATE TRIGGER trigger_delete_old_user_logs
AFTER INSERT ON user_logs
EXECUTE PROCEDURE delete_old_user_logs();
奇妙?
但是,这不是最好的方法。专家告诉他们使用分区。
所以我尝试按照以下语句创建分区 -
create rolling partition schema that creates a new day and removes and 31st
day on the UTC rotation
代码段:
CREATE TABLE purged_user_logs(
CONSTRAINT pk_user_logs PRIMARY KEY(user_logs_id),
CONSTRAINT ck_user_logs CHECK(timestamp > now() - interval '1 month')
) INHERITS(user_logs);
CREATE INDEX idx_user_logs ON purged_user_logs(timestamp);
这是INSERT查询:
INSERT INTO purged_user_logs(user_logs_id, timestamp)
SELECT user_logs_id, timestamp
from user_logs where timestamp > now() - interval '1 month';
这是功能:
create or replace function on_purged_user_insert() returns trigger as $$
begin
if (new.timestamp > now() - interval '1 month') then
insert into purged_user_logs values (new.*);
else
raise exception 'timestamp date out of range';
end if;
return null;
end;
$$ language plpgsql;
这是触发器:
create trigger user_logs_insert
before insert on user_logs
for each row execute procedure on_purged_user_insert();
根据声明,这是否正确? 不,删除失踪。所以我们需要另一个触发器去除?
INSERT触发器是否正确?