更新时间:2025-05-29 GMT+08:00

极致性能的导入导出场景

对数据导入导出性能有极致要求,且是在相同版本的数据库实例之间进行数据的导出与导入的场景下,BINARY格式通过二进制格式去存储/读取数据,而非文本格式。相比其他格式有一定的性能优势,但其存在一些限制:

  1. GaussDB特有格式,不具备可移植性,且仅推荐在同版本的数据库之间导入导出时使用。
  2. 二进制格式与数据类型相关性更强。例如,在文本格式下,可以从一个smallint字段导出并导入到integer列中,但是在二进制格式下不可以。
  3. 部分数据类型不支持二进制导入导出,具体信息请参见BINARY约束

建议导出命令:

1
2
3
4
set client_encoding = '{server_encoding}';
copy {data_source} to '/path/export.bin' binary;
--data_source 可以是一个表名称,也可以是一个select语句
--server_encoding 可以通过show server_encoding获得

对应导入命令:

1
2
3
4
set client_encoding = '{file_encoding}';
copy {data_destination} from '/path/export.bin' binary;
--data_destination 只能是一个表名称
--file_encoding 为该二进制文件导出时指定的编码格式

用户应仔细研读该格式的相关约束条件。只有在完全确定待导出数据不会受到BINARY格式相关约束影响的情况下,才可以考虑选用BINARY格式,以此提升数据导出和导入的性能。

示例

  1. 数据准备。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    gaussdb=# create database db1 encoding='UTF-8' LC_COLLATE='en_US.UTF-8' LC_CTYPE ='en_US.UTF-8' dbcompatibility = 'A';
    CREATE DATABASE
    gaussdb=# \c db1
    Non-SSL connection (SSL connection is recommended when requiring high-security)
    You are now connected to database "db1" as user "omm".
    db1=# CREATE TABLE test_copy(id int, name text);
    CREATE TABLE
    db1=# insert into test_copy values(1, 'aaa');
    INSERT 0 1
    db1=# insert into test_copy values(3, e'cc\tc');
    INSERT 0 1
    db1=# insert into test_copy(name) values('ddd');
    INSERT 0 1
    db1=# insert into test_copy values(5, e'ee\\e');
    INSERT 0 1
    db1=# insert into test_copy values(6, ',');
    INSERT 0 1
    db1=# insert into test_copy values(7, '"');
    INSERT 0 1
    db1=# SELECT * FROM test_copy;
     id |   name    
    ----+-----------
      1 | aaa
      3 | cc      c
        | ddd
      5 | ee\e
      6 | ,
      7 | "
    (6 rows)
    

  2. 数据导出。

    1
    2
    3
    4
    db1=# set client_encoding = 'UTF-8';
    SET
    db1=# COPY test_copy TO '/home/xy/test.bin' BINARY;
    COPY 6
    

  3. 数据导入。

    db1=# truncate test_copy;
    TRUNCATE TABLE
    db1=# set client_encoding = 'UTF-8';
    SET
    db1=# copy test_copy from '/home/xy/test.bin' BINARY;
    COPY 6