在 pg_restore 过程中排除表

41

更新: 在 pg_dump 命令中,成功排除表格中的数据。这种方法比尝试不加载数据更加快速,因为您无需等待那些数据被转储。

--exclude-table-data=event_logs

(PostgreSQL) 9.4.4

有人知道如何在进行 pg_restore 时排除某个表格吗?我可以找到如何在进行 pg_dump 时排除它们,但是我没有进行转储并且不能排除它们。

备份文件中有两个非常大的表格,进行恢复所需的时间非常长,因此我想跳过它们。

4个回答

76

我有同样的问题。一个很长的表格列表,我想从其中一些表格中排除数据。

我的解决方法是:

运行

pg_restore -l $pgdump_file > restore.pgdump.list

在编辑器中打开 restore.pgdump.list 文件,在说

的行前面插入一个 ;
;2429; 0 27550 TABLE DATA public <table_to_explore> <database>

保存该文件后,现在可以用于导入。所有以";"开头的行都会被忽略。
pg_restore -L restore.pgdump.list | psql

如果您完全想要忽略特定的一个表格,那么您可以编写一行代码,在指定表格名字前面添加 ;

在文档的末尾,man pg_restore也有关于此的示例说明。


7
谢谢,真是救星!正如在“man pg_restore”中所述,一旦编辑了“restore.pgdump.list”文件(根据您的示例),您可以调用“pg_restore -L db.list db.dump”(在您的示例中,您调用了“pg_restore”并将其管道连接到“psql”-- 不过,您没有指定转储文件的路径..?) - Greg Sadetsky
1
请注意,这个方法救了我一命,因为我试图从导入的 99 张表中排除其中的两张。pg_restore 在导入时不允许指定要排除的表,所以我只能这样调用它:pg_restore -t a_table -t another_table -t yet_another_table 等等。试图使用 97 个 -t 参数来调用它会出现“参数过多”的错误信息... :-) 您提供的 restore.pgdump.list 解决方案非常有效! - Greg Sadetsky
1
这非常有帮助!我只需要从单个表reports中排除数据:reports。在创建列表文件时,我能够进行内联的grep -v操作。pg_restore -l $pgdump_file | grep -v "TABLE DATA public reports" > restore.pgdump.list - Jackson Miller
1
非常好,现在我想告诉我的老同事们实施这个来帮助节省他们的时间。这太棒了,谢谢你发布这个。 - covard

28

TL;DR 一句话概括

pg_restore -L <(pg_restore -l /path/to/db/dump | grep -v 'TABLE DATA public table_to_ignore ') -d db_name_where_to_restore /path/to/db/dump
以下返回恢复“待办事项清单”:
pg_restore -l /path/to/db/dump 
以下代码将返回除 table_to_ignore 之外的所有内容(grep 的选项 -v 使匹配反转):

grep -v "table_to_ignore" file.txt

pg_restore -l /path/to/db/dump | grep -v 'TABLE DATA public table_to_ignore '

这可以与pg_restore选项-L结合使用,该选项需要输入待办事项列表:

pg_restore -L <(pg_restore -l /path/to/db/dump | grep -v 'TABLE DATA public table_to_ignore ') -d db_name_where_to_restore /path/to/db/dump
如果你有多个表需要忽略,你可以使用grep来:
pg_restore -l /path/to/db/dump | grep -vE 'TABLE DATA public (table_1 |table_2 |table_3 )'

请注意在使用grep命令时,存在-E选项可用于使用扩展正则表达式。


2
你需要在表名后面添加一个空格,例如 'TABLE DATA public (table_1|table_2|table_3) ',否则 table_1 也会匹配到 table_11 等等。 - Pyrocks
@Pyrocks 对的。已编辑答案。 - user3132194

10

pg_restore 没有排除表参数,但它有包括表参数。

-t table

--table=table

仅恢复指定表的定义和/或数据。可以使用多个-t开关指定多个表。这可以与-n选项结合使用以指定模式。

如果您有大量的表格,这确实需要一些打字,但它允许您通过仅留下列表中的名称来排除特定的表格。


2
谢谢。是的,我们有很多表格,但我正在制作一个rake任务来自动化这个过程,所以我只需要做一次。可以循环遍历表格,并有一个排除列表包括其中的两个表格。 - covard
1
@covard,你能否分享一下你的rake任务呢?这将会非常有用。 - Guillermo Siliceo Trueba

6

这个命令没有起作用:

pg_restore -L restore.pgdump.list | psql

由 Jesper Grann Laursen 回答!

这里按照以下顺序进行操作:

pg_restore -l $pgdump_file > restore.pgdump.list

;2429; 0 27550 TABLE DATA public <table_to_explore> <database>

pg_restore -v -L restore.pgdump.list -d dbname pgdump.file

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接