Purpose
This statement is used to import data from an external source.
The
LOAD DATAstatement in OceanBase Database supports loading the following types of input files:Server-side (OBServer node) files: Files located on the OBServer node of OceanBase Database. You can use the
LOAD DATA INFILEorLOAD DATA FROM URLstatement to load data from a server-side file into a database table.Client-side (local) files: Files located in the local file system of the client. You can use the
LOAD DATA LOCAL INFILEorLOAD DATA FROM URLstatement to load data from a local client file into a database table.Note
When OceanBase Database executes the
LOAD DATA LOCAL INFILEcommand, the system automatically adds theIGNOREoption.OSS files: Files located in the OSS file system. You can use the
LOAD DATA REMOTE_OSS INFILEstatement to load data from an OSS file into a database table.
LOAD DATA currently supports importing CSV format text files. The entire import process can be divided into the following steps:**
Parse the file: OceanBase Database reads the data from the file based on the user-provided filename and determines whether to parse the data in parallel or serial based on the specified degree of parallelism.
Distribute the data: Since OceanBase is a distributed database, data for each partition may be distributed across different OBServer nodes.
LOAD DATAcalculates which OBServer node should receive the parsed data.Insert the data: Upon receiving the data, the target OBServer node locally executes an
INSERToperation to insert the data into the corresponding partition.
Considerations
The
LOAD DATAstatement is prohibited for tables with triggers.To import data from an external file, you must have the
FILEprivilege and the following settings:- When loading server-side files, you must set the system variable secure_file_priv in advance to configure the accessible path for import or export files.
- To load a local client file, you must add the
--local-infile[=1]option when starting the MySQL/OBClient client to enable data loading from the local file system.
When using direct load for a specified partition, note that the target table cannot be a replicated table and must not contain auto-increment columns, identity columns, or global indexes.
Limitations on direct load (LOAD DATA syntax)
When using the LOAD DATA statement with hints such as APPEND and DIRECT(...) or tenant-level direct load configurations for import, in addition to the scope of application and limitations of the direct load capability described in Overview, the following statement-level LOAD DATA limitations also apply:
- Data import is not supported for a single row exceeding 2 MB.
- The
LOAD DATAstatement can be executed in a multi-row transaction and will automatically commit the previous transaction during execution. - For full direct load with unique indexes, the
REPLACEorIGNOREkeywords are not currently supported when duplicate unique index keys are encountered, nor is setting a tolerance row. - When the
load_modevalue ofDIRECT(...)isinc_replace, the statement does not allow theREPLACEorIGNOREkeywords.
Note
If a CSV file parsing error occurs during import, a obloaddata.log log file may be generated in the log subdirectory under the OBServer installation path. Type conversion failures and primary key conflicts are not recorded in this log file. When using the FROM FILES clause with the LOG ERRORS clause specified, the diagnostic information for failed rows is recorded according to that clause and the SHOW WARNINGS statement. For details, see log_errors below.
Syntax
-- Import a regular file
LOAD DATA
[/*+ PARALLEL(N) [load_batch_size(M)] [APPEND | direct(bool, int, [load_mode])] | NO_DIRECT */]
[REMOTE_OSS | LOCAL] INFILE 'file_name'
[REPLACE | IGNORE]
INTO TABLE table_name [PARTITION(PARTITION_OPTION)]
[COMPRESSION [=] {AUTO|NONE|GZIP|DEFLATE|ZSTD}]
[{FIELDS | COLUMNS}
[TERMINATED BY 'string']
[[OPTIONALLY] ENCLOSED BY 'char']
[ESCAPED BY 'char']
]
[LINES
[STARTING BY 'string']
[TERMINATED BY 'string']
]
[IGNORE number {LINES | ROWS}]
[(column_name_var
[, column_name_var] ...)]
load_mode:
'full'
| 'inc_replace'
PARTITION_OPTION:
partition_option_list
| subpartition_option_list
-- Import URL File
LOAD DATA
[/*+ PARALLEL(N) [load_batch_size(M)] [APPEND | direct(bool, int, [load_mode])] | NO_DIRECT */]
[REPLACE | IGNORE]
FROM { url_table_function_expr |
( SELECT expression_list FROM url_table_function_expr ) }
INTO TABLE table_name
[PARTITION(PARTITION_OPTION)]
[(column_name_var [, column_name_var] ...)]
[LOG ERRORS [REJECT LIMIT {integer | UNLIMITED}]]
load_mode:
'full'
| 'inc_replace'
url_table_function_expr:
FILES (
LOCATION = '<string>',
{
FORMAT = (
TYPE = 'CSV',
LINE_DELIMITER = '<string>' | <expr>,
FIELD_DELIMITER = '<string>' | <expr>,
PARSE_HEADER = { TRUE | FALSE },
ESCAPE = '<character>' | <expr>,
FIELD_OPTIONALLY_ENCLOSED_BY = '<character>' | <expr>,
ENCODING = 'charset',
NULL_IF = ('<string>' | <expr>, '<string>' | <expr> ...),
SKIP_HEADER = <int>,
SKIP_BLANK_LINES = { TRUE | FALSE },
TRIM_SPACE = { TRUE | FALSE },
EMPTY_FIELD_AS_NULL = { TRUE | FALSE }
)
| FORMAT = ( TYPE = 'PARQUET' | 'ORC' )
},
[PATTERN = '<regex_pattern>']
)
| SOURCE (
TYPE = 'ODPS',
ACCESSID = '<string>',
ACCESSKEY = '<string>',
ENDPOINT = '<string>',
TUNNEL_ENDPOINT = '<string>',
PROJECT_NAME = '<string>',
SCHEMA_NAME = '<string>',
TABLE_NAME = '<string>',
QUOTA_NAME = '<string>',
COMPRESSION_CODE = '<string>'
)
PARTITION_OPTION:
partition_option_list
| subpartition_option_list
Parameters
Parameter |
Description |
|---|---|
| parallel(N) | The degree of parallelism for loading data, which is 4 by default. |
| load_batch_size(M) | Specify the batch size for each insertion.MDefault:100. The recommended value range is [100, 1000]. |
| APPEND \ | Use the hint to enable the direct load feature.
NoticeWe recommend that you do not upgrade OceanBase Database while a direct load task is in progress, as this may cause the task to fail.
LOAD DATAFor more information about direct load, see Use the LOAD DATA statement to directly load data/files. |
| REMOTE_OSS \ | Optional. Valid values:
|
| file_name | Specifies the path and file name of the input file. The file_name format is as follows:
NoteWhen importing a file from OSS, ensure the following:
|
| REPLACE \ | If a unique key conflict occurs,REPLACEindicates that the conflicting row will be overwritten.IGNOREIndicates that the conflicting row is ignored.LOAD DATADetermine whether data is duplicate based on the table's primary key. If the table does not have a primary key, thenREPLACEandIGNOREThe options are equivalent. By default, neither is used for sorting.REPLACEOverwrite conflicting rows, and do not follow theIGNOREIgnoring conflicting rows; in case of a unique key conflict, the import may report an error and terminate.
Note
|
| url_table_function_expr | Optional. Use the FILES and SOURCE keywords to read data from a file system or data source. |
| table_name | The name of the table into which data is imported.
|
| PARTITION_OPTION | The partition name during direct load for a specified partition:
NoteSpecifying partitions is supported only for direct load and not for regular LOAD DATA. That is, if you do not add a direct load hint or configure direct load parameters, specifying partitions will not take effect when executing LOAD DATA. |
| COMPRESSION | Specifies the compression file format. Valid values:
|
| FIELDS \ COLUMNS | Specifies the format of the field.
|
| LINES STARTING BY | Specifies the line start character. |
| LINES TERMINATED BY | Specifies the line terminator. |
| IGNORE number { LINES \ ROWS } | Ignore the first few lines,LINESindicates the first few lines of a file,ROWSIndicates the first few rows of data specified by the field separator. By default, each field in the input file is matched with a column in the table. If the input file does not contain all columns, the missing columns are filled in by default according to the following rules:
NoteThe behavior is the same as that of single-file import for multi-file import. |
| column_name_var | Optional. Specifies the column names to import. |
| LOG ERRORS [REJECT LIMIT {integer \ UNLIMITED}] | Optional. Specifies to enable error diagnostics during the import of a URL external table. For more information, see log_errors.
NoteFor OceanBase Database V4.3.5, specifying error diagnostics is supported for the LOAD DATA statement syntax when importing a URL external table starting from V4.3.5 BP2. |
FILES
The FILES keyword consists of the LOCATION clause, the FORMAT clause, and the PATTERN clause.
The
LOCATIONclause specifies the path for storing external table files. Typically, the data files of an external table are placed in a single directory, which can contain subdirectories. When creating a table, the external table automatically collects all files in this directory.The local LOCATION format is
LOCATION = '[file:// | sfile://] local_file_path'.file://: This protocol header indicates that when encountering files with the same logical path across multiple OBServer nodes, they are treated as different files and processed separately. Each node independently reads the file from its local path.sfile://: This protocol header indicates that when files with the same logical path are found on multiple OBServer nodes, the system will deduplicate them based on the logical path to ensure only one copy of the data is read (supports multi-server load balancing).Notice
- When using
sfile://, the system performs a consistency check on file sizes. If files under the same logical path have inconsistent sizes across different OBServer nodes, the system reports an errorOB_INVALID_EXTERNAL_FILEto prevent incorrect results caused by data inconsistency. - For version V4.4.2, starting from V4.4.2 BP2, support for the
sfile://protocol header was added to the local Location path format in theLOAD DATAsyntax.
- When using
local_file_path: Can be a relative or absolute path. If a relative path is provided, the current directory must be the installation directory of OceanBase Database.secure_file_privspecifies the file paths that OBServer nodes are authorized to access.local_file_pathmust be a subpath of thesecure_file_privpath.
The format of the remote location is as follows:
LOCATION = '{oss|cos|S3}://$ACCESS_ID:$ACCESS_KEY@$HOST:s3_region/remote_file_path', where$ACCESS_ID,$ACCESS_KEY, and$HOSTare the access information required for accessing OSS, COS, and S3 respectively.s3_regionis the region information selected when using S3. This sensitive access information is stored in an encrypted manner in the database's system tables.LOCATION = 'hdfs://$ {hdfs_namenode_address}:${port}/PATH.localhost'whereportis the HDFS port number andPATHis the directory path in HDFS.- With Kerberos authentication:
LOCATION = 'hdfs://localhost:port/user?principal=xxx&keytab=xxx&krb5conf=xxx&configs=xxx'. Where:principal: the user for login authentication.keytab: the path of the keytab file for user authentication.krb5conf: the path to the Kerberos environment description file for the specified user.configs: Specifies additional HDFS configuration parameters. The default is empty, but in a Kerberos environment, this parameter typically has values that need to be configured. For example:dfs.data.transfer.protection=authentication,privacy, which specifies the data transfer protection level asauthenticationandprivacy.
- With Kerberos authentication:
Notice
When using an object storage path, the parameters of the path are separated by
&symbols. Ensure that the parameter values you enter consist only of uppercase and lowercase letters, numbers,\/-_$+=, and wildcard characters. Entering characters other than those listed above may cause the setting to fail.
The
FORMATclause is used to specify the format of the file to be read. Valid values are CSV, PARQUET, and ORC.When TYPE = 'CSV', the following fields are included:
LINE_DELIMITER: The line delimiter for the CSV file. Default:LINE_DELIMITER='\n'.FIELD_DELIMITER: Optional. Specifies the column delimiter for the CSV file. Default value:FIELD_DELIMITER='\t'.PARSE_HEADER: Optional. Specifies whether the first row of the CSV file contains column names for each column. The default isFALSE, which means the first row of the CSV file is not designated as column names.ESCAPE: Specifies the escape character for the CSV file. It must be one byte and defaults toESCAPE ='\'.FIELD_OPTIONALLY_ENCLOSED_BY: Optional. Specifies the character that encloses field values in a CSV file. The default is an empty string. When this option is used, enclosing characters are added only to fields of certain types, such as CHAR, VARCHAR, TEXT, and JSON.ENCODING: Specifies the character set encoding format of the file. If not specified, the default value isUTF8MB4.NULL_IF: The string that will be treated asNULL. The default value is empty.SKIP_HEADER: Skips the file header and specifies the number of rows to skip.SKIP_BLANK_LINES: Specifies whether to skip blank lines. The default value isFALSE, which means blank lines are not skipped.TRIM_SPACE: Specifies whether to delete leading and trailing spaces from fields in the file. The default value isFALSE, which means no spaces will be deleted.EMPTY_FIELD_AS_NULL: Specifies whether to treat empty strings asNULL. The default value isFALSE, which means empty strings are not treated asNULL.
When TYPE = 'PARQUET/ORC', no additional fields are required.
The
PATTERNclause specifies a regular expression pattern string for filtering files in theLOCATIONdirectory. For each file path in theLOCATIONdirectory, if it matches this pattern string, the external table accesses the file; otherwise, it skips the file. If this parameter is not specified, all files in theLOCATIONdirectory are accessible by default.
SOURCE
The SOURCE keyword does not contain other clauses. In this case, TYPE = 'ODPS' and the following fields are present:
ACCESSID: The ID of the ODPS user.ACCESSKEY: The password of the ODPS user.ENDPOINT: the connection address of the ODPS service.TUNNEL_ENDPOINT: The endpoint of the tunnel data transmission service.PROJECT_NAME: The project containing the table to be queried.SCHEMA_NAME: Optional. Specifies the schema of the table to query.TABLE_NAME: the name of the table to query.QUOTA_NAME: Optional. Specifies whether to use the specified quota.COMPRESSION_CODE: Optional. Specifies the compression format for the data source. Supported formats areZLIB,ZSTD,LZ4, andODPS_LZ4. If not specified, compression is disabled.
log_errors
LOG ERRORS: Enables error diagnostics during import, allowing failed rows to be recorded (in the current version, these are stored in thewarning buffer, which can be viewed usingshow warnings, with a maximum of 64 rows). This prevents the entire operation from terminating upon encountering the first error. Combined with theREJECT LIMITclause, it allows you to control the number of erroneous rows that are allowed.REJECT LIMIT: Optional. Specifies the maximum number of erroneous rows that are allowed:- The default value is 0, which means no error rows are allowed. The operation fails upon encountering the first error.
integer: The maximum number of erroneous rows allowed on a single node. For example, 10 indicates that a maximum of 10 error rows are allowed on one server.UNLIMITED: Allows an unlimited number of erroneous rows.
Notice
- If the
LOG ERRORSclause is not specified, the behavior is the normal import behavior, that is, an error is reported immediately upon encountering the first error. - If the
LOG ERRORSclause is specified but theREJECT LIMITclause is not specified, it is equivalent to specifying a diagnosticLIMITof 0. The operation will fail upon encountering the first error, but the first encountered error will be recorded, and the error code will also be a diagnostic error, namely "reject limit reached".Rules for wildcards during multi-file direct load
To facilitate multi-file imports, file wildcard functionality has been introduced. It applies to server-side and OSS file imports, but not to client-side file imports.
Server-side wildcard usage
Matching rules:
File name matching:
load data /*+ parallel(20) direct(true, 0) */ infile '/xxx/test.*.csv' replace into table t1 fields terminated by '|';Matching directory:
load data /*+ parallel(20) direct(true, 0) */ infile '/aaa*bb/test.1.csv' replace into table t1 fields terminated by '|';Matches both the directory and file name:
load data /*+ parallel(20) direct(true, 0) */ infile '/aaa*bb/test.*.csv' replace into table t1 fields terminated by '|';
Considerations:
At least one matching file must exist; otherwise, return error code 4027.
For the input of
load data /*+ parallel(20) direct(true, 0) */ infile '/xxx/test.1*.csv,/xxx/test.6*.csv' replace into table t1 fields terminated by '|';,/xxx/test.1*.csv,/xxx/test.6*.csvwill be considered a global match. If no match is found, error 4027 is reported.Only POSIX GLOB functions support the following wildcards:
test.6*(6|0).csvandtest.6*({0.csv,6.csv}|.csv). Although these files can be found using thelscommand, the GLOB function cannot match them and returns error 4027.
Use wildcard characters in Cloud Object Storage Service (
OSS)Matching rules:
Match file name:
load data /*+ parallel(20) direct(true, 0) */ remote_oss infile 'oss://xxx/test.*.csv?host=xxx&access_id=xxx&access_key=xxx' replace into table t1 fields terminated by '|';Considerations:
Directory matching is not supported. For example, the statement
load data /*+ parallel(20) direct(true, 0) */ remote_oss infile 'oss://aa*bb/test.*.csv?host=xxx&access_id=xxx&access_key=xxx' replace into table t1 fields terminated by '|';will returnOB_NOT_SUPPORTED.File name wildcards only support
*and?. Other wildcards, although allowed, will not match anything.
Examples
Note
LOAD DATAsupports using\Nto representNULLwhen loading data.Import data from a server-side file
Example 1: Import data from a file on the server side.
Set the global security path.
obclient> SET GLOBAL secure_file_priv = "/" Query OK, 0 rows affected obclinet> \q ByeNote
secure_file_privis aGLOBALvariable. You must execute\qto exit and make it effective.After reconnecting to the database, import data from an external file.
obclient> LOAD DATA INFILE 'test.sql' INTO TABLE t1; Query OK, 0 rows affected
Example 2: Use the
APPENDhint to enable direct load.LOAD DATA /*+ PARALLEL(4) APPEND */ INFILE '/home/admin/a.csv' INTO TABLE t;Example 3: Import a CSV file.
Import all columns from the
test1.csvfile.load data /*+ direct(true,0) parallel(2)*/ from files( location = "data/csv", format = ( type = 'csv', field_delimiter = ',', parse_header = true, skip_blank_lines = true ), pattern = 'test1.csv') into table t1;Read columns
c1andc2from thetest1.csvfile in thedata/csvdirectory and import them into columnscol1andcol2of tablet1.load data /*+ direct(true,0) parallel(2)*/ from ( select c1, c2 from files( location = 'data/csv' format = ( type = 'csv', field_delimiter = ',', parse_header = true, skip_blank_lines = true ), pattern = 'test1.csv')) into table t1 (col1, col2);
Example 4: Import a PARQUET file.
load data /*+ direct(true,0) parallel(2)*/ from files( location = "data/parquet", format = ( type = 'PARQUET'), pattern = 'test1.parquet') into table t1;Example 5: Import an ORC file.
load data /*+ direct(true,0) parallel(2)*/ from files( location = "data/orc", format = ( type = 'ORC'), pattern = 'test1.orc') into table t1;Example 5: Import an ODPS file.
load data /*+ direct(true,0) parallel(2)*/ from source ( type = 'ODPS', accessid = '$ODPS_ACCESSID', accesskey = '******', endpoint= '$ODPS_ENDPOINT', project_name = 'example_project', schema_name = '', table_name = 'example_table', quota_name = '', compression_code = '') into table t1;Import data from a client (local) file
Example 1: Import data from a local file to a table in OceanBase Database.
Open a terminal or command prompt window and enter the following command to start the client.
obclient --local-infile -hxxx.xxx.xxx.xxx -P2881 -uroot@mysql001 -p****** -A -DtestThe return result is as follows:
Welcome to the OceanBase. Commands end with ; or \g. Your OceanBase connection id is 3221719526 Server version: OceanBase 4.2.2.0 (r100000022023121309-f536833402c6efe9364d5a4b61830a858ef24d82) (Built Dec 13 2023 09:58:18) Copyright (c) 2000, 2018, OceanBase and/or its affiliates. All rights reserved. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. obclient [test]>Notice
To use the
LOAD DATA LOCAL INFILEfeature, use an OBClient client of version V2.2.4 or later. If you do not require a specific version of the OBClient client, you can also use a MySQL client to connect to the database.On the client, execute the
LOAD DATA LOCAL INFILEstatement to load the local data file.obclient [test]> LOAD DATA LOCAL INFILE '/home/admin/test_data/tbl1.csv' INTO TABLE tbl1 FIELDS TERMINATED BY ',';The return result is as follows:
Query OK, 3 rows affected Records: 3 Deleted: 0 Skipped: 0 Warnings: 0
Example 2: Import a compressed file directly by setting COMPRESSION.
LOAD DATA LOCAL INFILE '/your/file/lineitem.tbl.gz' INTO TABLE lineitem COMPRESSION GZIP FIELDS TERMINATED BY '|';Example 3: Direct load by partition using the PARTITION clause.
- Specify direct load for a partition
load data /*+ direct(true,0) parallel(2) load_batch_size(100) */ infile "$FILE_PATH" into table t1 partition(p0, p1) fields terminated by '|' enclosed by '' lines starting by '' terminated by '\n';- Specify direct load for a subpartition
load data /*+ direct(true,0) parallel(2) load_batch_size(100) */ infile "$FILE_PATH" into table t1 partition(p0sp0, p1sp1) fields terminated by '|' enclosed by '' lines starting by '' terminated by '\n';Import data from an OSS file
Example 1: Use the
direct(bool, int)hint to enable direct load. The direct load file can be stored on OSS.load data /*+ parallel(1) direct(false,0)*/ remote_oss infile 'oss://antsys-oceanbasebackup/backup_rd/xiaotao.ht/lineitem2.tbl?host=***.oss-cdn.***&access_id=***&access_key=***' into table lineitem fields terminated by '|' enclosed by '' lines starting by '' terminated by '\n';Import data from a server-side file as a URL external table
Notice
The IP addresses in the example commands have been masked. During verification, you must replace them with your actual machine IP address.
The following example shows how to create an external table when the external file is located locally or in MySQL-compatible mode of OceanBase Database. The procedure is as follows:
Prepare external files.
Run the following command to create a file named
column_conv.csvin the/home/admin/test_csvdirectory on the server where you want to log in to the OBServer node.[admin@xxx /home/admin/test_csv]# vi column_conv.csvThe file content is as follows:
1,short,short 2,long_text,long_text 3,long_text,long_textSet the path of the file to import.
Notice
For security reasons, when setting the system variable
secure_file_priv, you must connect to the database via a local Unix Socket to execute the SQL statement that modifies this global variable. For more information, see secure_file_priv.Run the following command to log in to the server where the OBServer node is located.
ssh admin@10.10.10.1Run the following command to connect to the
mysql001tenant using a local Unix socket connection.obclient -S /home/admin/oceanbase/run/sql.sock -uroot@mysql001 -p******Execute the following SQL statement to set the import path to
/home/admin/test_csv.SET GLOBAL secure_file_priv = "/home/admin/test_csv";
Reconnect to the
mysql001tenant.Example:
obclient -h10.10.10.1 -P2881 -uroot@mysql001 -p****** -A -Ddb_testCreate the table
test_tbl1.CREATE TABLE test_tbl1(col1 VARCHAR(5), col2 VARCHAR(5), col3 VARCHAR(5));Use the
LOAD DATAstatement to import data into tabletest_tbl1from the external URL table, specifying error diagnostics.LOAD DATA FROM FILES( LOCATION = '/home/admin/test_csv', FORMAT = ( TYPE = 'csv', FIELD_DELIMITER = ','), PATTERN = 'column_conv.csv') INTO TABLE test_tbl1 LOG ERRORS REJECT LIMIT UNLIMITED;The return result is as follows:
Query OK, 1 row affected, 2 warnings Records: 1 Deleted: 0 Skipped: 0 Warnings: 2View Warnings.
SHOW warnings;The return result is as follows:
+---------+------+----------------------------------------------------------------------------------------------------------------------+ | Level | Code | Message | +---------+------+----------------------------------------------------------------------------------------------------------------------+ | Warning | 1406 | fail to scan file column_conv.csv at line 2 for column "db_test"."test_tbl1"."col2", error: Data too long for column | | Warning | 1406 | fail to scan file column_conv.csv at line 3 for column "db_test"."test_tbl1"."col2", error: Data too long for column | +---------+------+----------------------------------------------------------------------------------------------------------------------+ 2 rows in setView the data in the
test_tbl1table.SELECT * FROM test_tbl1;The return result is as follows:
+------+-------+-------+ | col1 | col2 | col3 | +------+-------+-------+ | 1 | short | short | +------+-------+-------+ 1 row in set
References
- For more information about how to connect to OceanBase Database, see Overview of connection methods.
- For more examples of using the
LOAD DATAstatement, see Import data by using the LOAD DATA statement. - For more examples of using direct load with
LOAD DATA, see Import data by using direct load with LOAD DATA.
