Tip Try Routine Load out in this Quick Start Routine Load can continuously consume messages from Apache Kafka® and load data into the database. Routine Load can consume CSV, JSON, and Avro (supported since v3.0.1) data from a Kafka cluster and access Kafka via multiple security protocols, including
plaintext, ssl, sasl_plaintext, and sasl_ssl.
This topic describes the syntax, parameters, and examples of the CREATE ROUTINE LOAD statement.
Note
- For information about the application scenarios, principles, and basic operations of Routine Load, see Load data using Routine Load.
- You can load data into tables only as a user who has the INSERT privilege on those tables. If you do not have the INSERT privilege, follow the instructions provided in GRANT to grant the INSERT privilege to the user that you use to connect to your cluster.
Syntax
Parameters
database_name, job_name, table_name
database_name
Optional. The name of the database.
job_name
Required. The name of the Routine Load job. A table may receive data from multiple Routine Load jobs. We recommend that you set a meaningful Routine Load job name by using identifiable information, for example, Kafka topic name and the approximate job creation time, to distinguish multiple Routine Load jobs. The name of the Routine Load job must be unique within the same database.
table_name
Required. The name of the table to which data is loaded.
load_properties
Optional. The properties of the data. Syntax:
COLUMNS TERMINATED BY
The column separator for CSV-formatted data. The default column separator is \t (Tab). For example, you can use COLUMNS TERMINATED BY "," to specify the column separator as a comma.
Tip
- Ensure that the column separator specified here is the same as the column separator in the data to be ingested.
- You can use a UTF-8 string, such as a comma (,), tab, or pipe (|), whose length does not exceed 50 bytes as a text delimiter.
- Null values are denoted by using
\N. For example, a data record consists of three columns, and the data record holds data in the first and third columns but does not hold data in the second column. In this situation, you need to use\Nin the second column to denote a null value. This means the record must be compiled asa,\N,binstead ofa,,b.a,,bdenotes that the second column of the record holds an empty string.
ROWS TERMINATED BY
The row separator for CSV-formatted data. The default row separator is \n.
COLUMNS
The mapping between the columns in the source data and the columns in the table. For more information, see Column mapping in this topic.
column_name: If a column of the source data can be mapped to a column of the table without any computation, you only need to specify the column name. These columns can be referred to as mapped columns.column_assignment: If a column of the source data cannot be directly mapped to a column of the table, and the column’s values must be computed by using functions before data loading, you must specify the computation function inexpr. These columns can be referred to as derived columns. It is recommended to place derived columns after mapped columns because the database first parses mapped columns.
WHERE
The filter condition. Only data that meets the filter condition can be loaded into the database. For example, if you only want to ingest rows whose col1 value is greater than 100 and col2 value is equal to 1000, you can use WHERE col1 > 100 and col2 = 1000.
Note
The columns specified in the filter condition can be source columns or derived columns.
PARTITION
If a table is distributed on partitions p0, p1, p2 and p3, and you want to load the data only to p1, p2, and p3 in the database and filter out the data that will be stored in p0, then you can specify PARTITION(p1, p2, p3) as a filter condition. By default, if you do not specify this parameter, the data will be loaded into all the partitions. Example:
TEMPORARY PARTITION
The name of the temporary partition into which you want to load data. You can specify multiple temporary partitions, which must be separated by commas (,).
job_properties
Required. The properties of the load job. Syntax:
JobProperties field returned by SHOW ROUTINE LOAD contains the descriptive keys, such as loadInterval, beside the legacy keys, such as maxBatchIntervalS. Both show the values in effect, that is, after rounding.
A duration without a unit, such as
"10", is rejected.
Only versions that support the descriptive names accept them. A statement that uses them, including the output of SHOW CREATE ROUTINE LOAD for a job with a property set by a descriptive name, fails on an earlier version with an error such as load_interval is invalid property. During a rolling upgrade, use the descriptive names after the Leader FE is upgraded.
desired_concurrent_number
Required: NoDescription: The expected task parallelism of a single Routine Load job. Default value:
3. The actual task parallelism is determined by the minimum value of the multiple parameters: min(alive_be_number, partition_number, desired_concurrent_number, max_routine_load_task_concurrent_num).
alive_be_number: the number of alive BE nodes.partition_number: the number of partitions to be consumed.desired_concurrent_number: the expected task parallelism of a single Routine Load job. Default value:3.max_routine_load_task_concurrent_num: the default maximum task parallelism of a Routine Load job, which is5. See FE dynamic parameter.
max_batch_interval
Required: NoDescription: The scheduling interval for a task, that is, how often a task is executed. Unit: seconds. Value range:
5 ~ 60. Default value: 10. It is recommended to set a value larger than 10. If the scheduling is shorter than 10 seconds, too many tablet versions are generated due to an excessively high loading frequency.
max_batch_rows
Required: NoDescription: This property is only used to define the window of error detection. The window is the number of rows of data consumed by a single Routine Load task. The value is
10 * max_batch_rows. The default value is 10 * 200000 = 2000000. The Routine Load task detects error data in the error detection window. Error data refers to data that the database cannot parse, such as invalid JSON-formatted data.
max_error_number
Required: NoDescription: The maximum number of error data rows allowed within an error detection window. If the number of error data rows exceeds this value, the load job will pause. You can execute SHOW ROUTINE LOAD and view the error logs by using
ErrorLogUrls. After that, you can correct the error in Kafka according to the error logs. The default value is 0, which means error rows are not allowed. NOTE
- The last batch of tasks will succeed before the load job pauses when there are too many error data rows. That is, the qualified data will be loaded, and the unqualified data will be filtered. If you don’t want to filter too many unqualified data rows, set parameter
max_filter_ratio. - Error data rows do not include data rows that are filtered out by the WHERE clause.
- This parameter, along with the next parameter
max_filter_ratio, controls the maximum number of error data records. Whenmax_filter_ratiois not set, the value of this parameter takes effect. Whenmax_filter_ratiois set, the load job pauses as soon as the number of error data record reaches either the threshold set by this parameter or themax_filter_ratioparameter.
max_filter_ratio
Required: NoDescription: The maximum error tolerance of the load job. The error tolerance is the maximum percentage of data records that can be filtered out due to inadequate data quality in all data records requested by the load job. Valid values:
0 to 1. Default value: 1 (That means it won’t actually take effect).We recommend that you set it to
0. This way, if unqualified data records are detected, the load job pauses, thereby ensuring data correctness.If you want to ignore unqualified data records, you can set this parameter to a value greater than
0. This way, the load job can succeed even if the data file contains unqualified data records. NOTE
- The last batch of tasks will fail when there are too many error data rows larger than
max_filter_ratio. It’s a bit different with the effect ofmax_error_number. - Unqualified data records do not include data records that are filtered out by the WHERE clause.
- This parameter, along with the last parameter
max_error_number, controls the maximum number of error data records. When this parameter is not set (It works the same as settingmax_filter_ratio = 1), the value of themax_error_numberparameter takes effect. When this parameter is set, the load job pauses as soon as the number of error data records reaches either the threshold set by this parameter or themax_error_numberparameter.
strict_mode
Required: NoDescription: Specifies whether to enable the strict mode. Valid values:
true and false. Default value: false. When the strict mode is enabled, if the value for a column in the loaded data is NULL but the target table does not allow a NULL value for this column, the data row will be filtered out.
log_rejected_record_num
Required: NoDescription: Specifies the maximum number of unqualified data rows that can be logged. This parameter is supported from v3.1 onwards. Valid values:
0, -1, and any non-zero positive integer. Default value: 0.
- The value
0specifies that data rows that are filtered out will not be logged. - The value
-1specifies that all data rows that are filtered out will be logged. - A non-zero positive integer such as
nspecifies that up tondata rows that are filtered out can be logged on each BE.
REJECTED_RECORD_PATH field from the query against the information_schema.loads view.
timezone
Required: NoDescription: The time zone used by the load job. Default value:
Asia/Shanghai. The value of this parameter affects the results returned by functions such as strftime(), alignment_timestamp(), and from_unixtime(). The time zone specified by this parameter is a session-level time zone. For more information, see Configure a time zone.
partial_update
Required: NoDescription: Whether to use partial updates. Valid values:
TRUE and FALSE. Default value: FALSE, indicating to disable this feature.
merge_condition
Required: NoDescription: Specifies the name of the column you want to use as the condition to determine whether to update data. Data will be updated only when the value of the data to be loaded into this column is greater than or equal to the current value of this column. NOTE
Only Primary Key tables support conditional updates. The column that you specify cannot be a primary key column.
format
Required: NoDescription: The format of the data to be loaded. Valid values:
CSV, JSON, and Avro (supported since v3.0.1). Default value: CSV.
trim_space
Required: NoDescription: Specifies whether to remove spaces preceding and following column separators from the data file when the data file is in CSV format. Type: BOOLEAN. Default value:
false.For some databases, spaces are added to column separators when you export data as a CSV-formatted data file. Such spaces are called leading spaces or trailing spaces depending on their locations. By setting the
trim_space parameter, you can enable the database to remove such unnecessary spaces during data loading.Note that the database does not remove the spaces (including leading spaces and trailing spaces) within a field wrapped in a pair of
enclose-specified characters. For example, the following field values use pipe (|) as the column separator and double quotation marks (") as the enclose-specified character: | "Love StarRocks "|. If you set trim_space to true, the database processes the preceding field values as |"Love StarRocks"|.
enclose
Required: NoDescription: Specifies the character that is used to wrap the field values in the data file according to RFC4180 when the data file is in CSV format. Type: single-byte character. Default value:
NONE. The most prevalent characters are single quotation mark (') and double quotation mark (").All special characters (including row separators and column separators) wrapped by using the
enclose-specified character are considered normal symbols. The database can do more than RFC4180 as it allows you to specify any single-byte character as the enclose-specified character.If a field value contains an
enclose-specified character, you can use the same character to escape that enclose-specified character. For example, you set enclose to ", and a field value is a "quoted" c. In this case, you can enter the field value as "a ""quoted"" c" into the data file.
escape
Required: NoDescription: Specifies the character that is used to escape various special characters, such as row separators, column separators, escape characters, and
enclose-specified characters, which are then considered by the database to be common characters and are parsed as part of the field values in which they reside. Type: single-byte character. Default value: NONE. The most prevalent character is slash (\), which must be written as double slashes (\\) in SQL statements.NOTE
The character specified by
escape is applied to both inside and outside of each pair of enclose-specified characters.Two examples are as follows:
- When you set
encloseto"andescapeto\, the database parses"say \"Hello world\""intosay "Hello world". - Assume that the column separator is comma (
,). When you setescapeto\, the database parsesa, b\, cinto two separate field values:aandb, c.
strip_outer_array
Required: NoDescription: Specifies whether to strip the outermost array structure of the JSON-formatted data. Valid values:
true and false. Default value: false. In real-world business scenarios, JSON-formatted data may have an outermost array structure as indicated by a pair of square brackets []. In this situation, we recommend that you set this parameter to true, so the database removes the outermost square brackets [] and loads each inner array as a separate data record. If you set this parameter to false, the database parses the entire JSON-formatted data into one array and loads the array as a single data record. Use the JSON-formatted data [{"category" : 1, "author" : 2}, {"category" : 3, "author" : 4} ] as an example. If you set this parameter to true, {"category" : 1, "author" : 2} and {"category" : 3, "author" : 4} are parsed as two separate data records and are loaded into two data rows.
jsonpaths
Required: NoDescription: The names of the fields that you want to load from JSON-formatted data. The value of this parameter is a valid JsonPath expression. For more information, see table contains derived columns whose values are generated by using expressions) in this topic.
json_root
Required: NoDescription: The root element of the JSON-formatted data to load. The database extracts the elements of the root node through
json_root for parsing. By default, the value of this parameter is empty, indicating that all JSON-formatted data will be loaded. For more information, see Specify the root element of the JSON-formatted data to be loaded in this topic.
envelope
Required: NoDescription: Specifies the CDC envelope format of the JSON-formatted data. Valid value:
debezium. Default: not set (no envelope wrapping). When set to debezium, the database parses each Kafka message as a Debezium CDC event. The message must contain an op field (c=create, u=update, d=delete, r=snapshot read) and an after field (for c/u/r) or before field (for d) holding the actual row data. Tombstone messages where payload is null are silently skipped. Can only be specified when format is json. Cannot be used together with json_root or strip_outer_array.
task_consume_second
Required: NoDescription: The maximum time for each Routine Load task within the specified Routine Load job to consume data. Unit: second. Unlike the FE dynamic parameters
routine_load_task_consume_second (which applies to all Routine Load jobs within the cluster), this parameter is specific to an individual Routine Load job, which is more flexible. This parameter is supported since v3.1.0.
- When
task_consume_secondandtask_timeout_secondare not configured, the database uses the FE dynamic parametersroutine_load_task_consume_secondandroutine_load_task_timeout_secondto control the load behavior. - When only
task_consume_secondis configured, the default value fortask_timeout_secondis calculated astask_consume_second* 4. - When only
task_timeout_secondis configured, the default value fortask_consume_secondis calculated astask_timeout_second/4.
task_timeout_second
Required: NoDescription: The timeout duration for each Routine Load task within the specified Routine Load job. Unit: second. Unlike the FE dynamic parameter
routine_load_task_timeout_second (which applies to all Routine Load jobs within the cluster), this parameter is specific to an individual Routine Load job, which is more flexible. This parameter is supported since v3.1.0.
- When
task_consume_secondandtask_timeout_secondare not configured, the database uses the FE dynamic parametersroutine_load_task_consume_secondandroutine_load_task_timeout_secondto control the load behavior. - When only
task_timeout_secondis configured, the default value fortask_consume_secondis calculated astask_timeout_second/4. - When only
task_consume_secondis configured, the default value fortask_timeout_secondis calculated astask_consume_second* 4.
pause_on_fatal_parse_error
Required: NoDescription: Specifies whether to automatically pause the job upon encountering unrecoverable data parsing errors. Valid values:
true and false. Default value: false. This parameter is supported since v3.3.12/v3.4.2. Such parsing errors are typically caused by illegal data formats, such as:
- Importing a JSON array without setting
strip_outer_array. - Importing JSON data, but the Kafka message contains illegal JSON, such as
abcd.
data_source, data_source_properties
Required. The data source and relevant properties.
data_source
Required. The source of the data you want to load. Valid value: KAFKA.
data_source_properties
The properties of the data source.
kafka_broker_list
Required: YesDescription: Kafka’s broker connection information. The format is
<kafka_broker_ip>:<broker_ port>. Multiple brokers are separated by commas (,). The default port used by Kafka brokers is 9092. Example:"kafka_broker_list" = ""xxx.xx.xxx.xx:9092,xxx.xx.xxx.xx:9092".
kafka_topic
Required: YesDescription: The Kafka topic to be consumed. A Routine Load job can only consume messages from one topic.
kafka_partitions
Required: NoDescription: The Kafka partitions to be consumed, for example,
"kafka_partitions" = "0, 1, 2, 3". If this property is not specified, all partitions are consumed by default.
kafka_offsets
Required: NoDescription: The starting offset from which to consume data in a Kafka partition as specified in
kafka_partitions. If this property is not specified, the Routine Load job consumes data starting from the latest offsets in kafka_partitions. Valid values:
- A specific offset: consumes data starting from a specific offset.
OFFSET_BEGINNING: consumes data starting from the earliest offset possible.OFFSET_END: consumes data starting from the latest offset.
"kafka_offsets" = "1000, OFFSET_BEGINNING, OFFSET_END, 2000".
property.kafka_default_offsets
Required: NoDescription: The default starting offset for all consumer partitions. The supported values for this property are same as those for the
kafka_offsets property. Partitions that are discovered after the job already has consuming progress (for example, partitions added to the Kafka topic later) start from this offset, or from OFFSET_BEGINNING if this property is not specified.
property.kafka_partition_discovery
Required: NoDescription: Whether the Routine Load job keeps discovering new Kafka partitions even if
kafka_partitions is specified. Valid values: true and false (default). By default, specifying kafka_partitions pins the consumed partitions to that list, and partitions added to the topic later are not consumed. If this property is set to true, kafka_partitions and kafka_offsets only specify the starting offsets of the listed partitions, and the job consumes all partitions of the topic, including partitions added later. A partition that is not listed in kafka_partitions starts from the offset specified in property.kafka_default_offsets, or from OFFSET_BEGINNING if property.kafka_default_offsets is not specified. To start the unlisted partitions from the latest offset instead, explicitly set property.kafka_default_offsets to OFFSET_END. This property can only be used together with kafka_partitions.
confluent.schema.registry.url
Required: NoDescription: The URL of the Schema Registry where the Avro schema is registered. The database retrieves the Avro schema by using this URL. The format is as follows:
confluent.schema.registry.url = http[s]://[<schema-registry-api-key>:<schema-registry-api-secret>@]<hostname or ip address>[:<port>]
More data source-related properties
You can specify additional data source (Kafka) related properties, which are equivalent to using the Kafka command line--property. For more supported properties, see the properties for a Kafka consumer client in librdkafka configuration properties.
Note
If the value of a property is a file name, add the keyword FILE: preceding the file name. For information about how to create a file, see CREATE FILE.
- Specify the default initial offset for all the partitions to be consumed
- Specify the ID of the consumer group used by the Routine Load job
property.group.id is not specified, the database generates a random value based on the name of the Routine Load job, in the format of {job_name}_{random uuid}, such as simple_job_0a64fe25-3983-44b2-a4d8-f52d3af4c3e8.
-
Specify the security protocol and relevant parameters used by BE to access Kafka
The security protocol can be specified as
plaintext(default),ssl,sasl_plaintext, orsasl_ssl. And you need to configure the related parameters according to the specified security protocol. When the security protocol is set tosasl_plaintextorsasl_ssl, the following SASL authentication mechanisms are supported:- PLAIN
- SCRAM-SHA-256 and SCRAM-SHA-512
- OAUTHBEARER
- GSSAPI (Kerberos)
-
Access Kafka using the SSL security protocol:
-
Access Kafka using the SASL_PLAINTEXT security protocol and SASL/PLAIN authentication mechanism:
-
Access Kafka using the SASL_PLAINTEXT security protocol and SASL/GSSAPI (Kerberos) authentication mechanism:
Note
- Since StarRocks v3.1.4, SASL/GSSAPI (Kerberos) authentication is supported.
-
SASL related modules need to be installed on the BE machine.
FE and BE configuration items
For FE and BE configuration items related to Routine Load, see configuration items.Column mapping
Configure column mapping for loading CSV-formatted data
If the columns of the CSV-formatted data can be mapped one on one in sequence to the columns of the table, you do not need to configure the column mapping between the data and the table. If the columns of the CSV-formatted data cannot be mapped one on one in sequence to the columns of the table, you need to use thecolumns parameter to configure the column mapping between the data file and the table. This includes the following two use cases:
-
Same number of columns but different column sequence. Also, the data from the data file does not need to be computed by functions before it is loaded into the matching table columns.
-
In the
columnsparameter, you need to specify the names of the table columns in the same sequence as how the data file columns are arranged. -
For example, the table consists of three columns, which are
col1,col2, andcol3in sequence, and the data file also consists of three columns, which can be mapped to the table columnscol3,col2, andcol1in sequence. In this case, you need to specify"columns: col3, col2, col1".
-
In the
-
Different number of columns and different column sequence. Also, the data from the data file needs to be computed by functions before it is loaded into the matching table columns.
In the
columnsparameter, you need to specify the names of the table columns in the same sequence as how the data file columns are arranged and specify the functions you want to use to compute the data. Two examples are as follows:- The table consists of three columns, which are
col1,col2, andcol3in sequence. The data file consists of four columns, among which the first three columns can be mapped in sequence to the table columnscol1,col2, andcol3and the fourth column cannot be mapped to any of the table columns. In this case, you need to temporarily specify a name for the fourth column of the data file, and the temporary name must be different from any of the table column names. For example, you can specify"columns: col1, col2, col3, temp", in which the fourth column of the data file is temporarily namedtemp. - The table consists of three columns, which are
year,month, anddayin sequence. The data file consists of only one column that accommodates date and time values inyyyy-mm-dd hh:mm:ssformat. In this case, you can specify"columns: col, year = year(col), month=month(col), day=day(col)", in whichcolis the temporary name of the data file column and the functionsyear = year(col),month=month(col), andday=day(col)are used to extract data from the data file columncoland loads the data into the mapping table columns. For example,year = year(col)is used to extract theyyyydata from the data file columncoland loads the data into the table columnyear.
- The table consists of three columns, which are
Configure column mapping for loading JSON-formatted or Avro-formatted data
Note Since v3.0.1, the database supports loading Avro data by using Routine Load. When you load JSON or Avro data, the configuration for column mapping and transformation is the same. Therefore, in this section, JSON data is used as an example to introduce the configuration. If the keys of the JSON-formatted data have the same names as the columns of the table, you can load the JSON-formatted data by using the simple mode. In simple mode, you do not need to specify thejsonpaths parameter. This mode requires that the JSON-formatted data must be an object as indicated by curly brackets {}, such as {"category": 1, "author": 2, "price": "3"}. In this example, category, author, and price are key names, and these keys can be mapped one on one by name to the columns category, author, and price of the table. For examples, please see simple mode.
If the keys of the JSON-formatted data have different names than the columns of the table, you can load the JSON-formatted data by using the matched mode. In matched mode, you need to use the jsonpaths and COLUMNS parameters to specify the column mapping between the JSON-formatted data and the table:
- In the
jsonpathsparameter, specify the JSON keys in the sequence as how they are arranged in the JSON-formatted data. - In the
COLUMNSparameter, specify the mapping between the JSON keys and the table columns:- The column names specified in the
COLUMNSparameter are mapped one on one in sequence to the JSON-formatted data. - The column names specified in the
COLUMNSparameter are mapped one on one by name to the table columns.
- The column names specified in the
Examples
Load CSV-formatted data
This section uses CSV-formatted data as an example to describe how you can employ various parameter settings and combinations to meet your diverse loading requirements. Prepare a dataset Suppose you want to load CSV-formatted data from a Kafka topic namedordertest1.Every message in the dataset includes six columns: order ID, payment date, customer name, nationality, gender, and price.
example_tbl1 in the database example_db.
Consume data starting from specified offsets for specified partitions
If the Routine Load job needs to consume data starting from specified partitions and offsets, you need to configure the parameterskafka_partitions and kafka_offsets.
Improve loading performance by increasing task parallelism
To improve loading performance and avoid accumulative consumption, you can increase task parallelism by increasing thedesired_concurrent_number value when you create the Routine Load job. Task parallelism allows splitting one Routine Load job into as many parallel tasks as possible.
Note that the actual task parallelism is determined by the minimum value among the following multiple parameters:
max_routine_load_task_concurrent_num and desired_concurrent_number, you can increase the values of the other two parameters to increase the actual task parallelism.
Assume that the number of partitions to be consumed is 7, the number of alive BE nodes is 5, and max_routine_load_task_concurrent_num is the default value 5. If you want to increase the actual task parallelism, you can set desired_concurrent_number to 5 (the default value is 3). In this case, the actual task parallelism min(5,7,5,5) is configured at 5.
Configure column mapping
If the sequence of columns in the CSV-formatted data is inconsistent with the columns in the target table, assuming that the fifth column in the CSV-formatted data does not need to be imported to the target table, you need to specify the column mapping between the CSV-formatted data and the target table through theCOLUMNS parameter.
Target database and table
Create the target table example_tbl2 in the target database example_db according to the columns in the CSV-formatted data. In this scenario, you need to create five columns corresponding to the five columns in the CSV-formatted data, except for the fifth column that stores gender.
temp_gender in COLUMNS, and the other columns are directly mapped to the table example_tbl2.
Set filter conditions
If you want to load only data that meets certain conditions, you can set filter conditions in theWHERE clause, for example, price > 100.
Enable strict mode to filter out rows with NULL values
InPROPERTIES, you can set "strict_mode" = "true", which means that the Routine Load job is in strict mode. If there is a NULL value in a source column, but the destination table column does not allow NULL values, the row that holds a NULL value in the source column is filtered out.
Set error tolerance
If your business scenario has low tolerance for unqualified data, you need to set the error detection window and the maximum number of error data rows by configuring the parametersmax_batch_rows and max_error_number. When the number of error data rows within an error detection window exceeds the value of max_error_number, the Routine Load job pauses.
Specify the security protocol as SSL and configure the related parameters
If you need to specify the security protocol as SSL used by BE to access Kafka, you need to configure"property.security.protocol" = "ssl" and related parameters.
Setting trim_space, enclose, and escape
Suppose you want to load CSV-formatted data from a Kafka topic namedtest_csv. Every message in the dataset includes six columns: order ID, payment date, customer name, nationality, gender, and price.
test_csv into example_tbl1, with the intention of removing the spaces preceding and following column separators and setting enclose to " and escape to \, run the following command:
Load JSON-formatted data
Table column names consistent with JSON key names
Prepare a dataset For example, the following JSON-formatted data exists in the Kafka topicordertest2.
example_tbl3 in the target database example_db in the cluster. The column names are consistent with the keys names in the JSON-formatted data.
jsonpaths and COLUMNS parameters when creating the Routine Load job. The database extracts the keys of JSON-formatted data in the topic ordertest2 of the Kafka cluster according to the column names of the target table example_tbl3 and loads the JSON-formatted data into the target table.
- If the outermost layer of the JSON-formatted data is an array structure, you need to set
"strip_outer_array"="true"inPROPERTIESto strip the outermost array structure. Additionally, when you need to specifyjsonpaths, the root element of the entire JSON-formatted data is the flattened JSON object because the outermost array structure of the JSON-formatted data is stripped. - You can use
json_rootto specify the root element of the JSON-formatted data.
Table contains derived columns whose values are generated by using expressions
Prepare a dataset For example, the following JSON-formatted data exists in the topicordertest2 of the Kafka cluster.
example_tbl4 in the database example_db in the cluster. The column pay_dt is a derived column whose values are generated by computing values of the key pay_time in the JSON-formatted data.
jsonpaths and COLUMNS parameters when creating the Routine Load job.
You need to specify the keys of the JSON-formatted data and arrange them in sequence in the jsonpaths parameter.
And since the values in the key pay_time of the JSON-formatted data need to be converted to the DATE type before the values are stored in the pay_dt column of the example_tbl4 table, you need to specify the computation by using pay_dt=from_unixtime(pay_time,'%Y%m%d') in COLUMNS. The values of other keys in the JSON-formatted data can be directly mapped to the example_tbl4 table.
- If the outermost layer of the JSON data is an array structure, you need to set
"strip_outer_array"="true"in thePROPERTIESto strip the outermost array structure. Additionally, when you need to specifyjsonpaths, the root element of the entire JSON data is the flattened JSON object because the outermost array structure of the JSON data is stripped. - You can use
json_rootto specify the root element of the JSON-formatted data.
Table contains derived column whose values are generated by using CASE expression
Prepare a dataset For example, the following JSON-formatted data exists in the Kafka topictopic-expr-test.
tbl_expr_test in the database example_db in the cluster. The target table tbl_expr_test contains two columns, where the values of the col2 column need to be computed by using case expression on JSON data.
col2 column in the target table are generated using a CASE expression, you need to specify the corresponding expression in the COLUMNS parameter for the Routine load job.
col2 column are the output of the CASE expression.
Specify the root element of the JSON-formatted data to be loaded
You need to usejson_root to specify the root element of the JSON-formatted data to be loaded and the value must be a valid JsonPath expression.
Prepare a dataset
For example, the following JSON-formatted data exists in the topic ordertest3 of the Kafka cluster. And the root element of the JSON-formatted data to be loaded is $.RECORDS.
example_tbl3 in the database example_db in the cluster.
"json_root" = "$.RECORDS" in PROPERTIES to specify the root element of the JSON-formatted data to be loaded. Also, since the JSON-formatted data to be loaded is in an array structure, you must also set "strip_outer_array" = "true" to strip the outermost array structure.
Load Avro-formatted data
Since v3.0.1, the database supports loading Avro data by using Routine Load.Avro schema is simple
Suppose the Avro schema is relatively simple, and you need to load all fields of the Avro data. Prepare a dataset-
Avro schema
-
Create the following Avro schema file
avro_schema1.avsc: - Register the Avro schema in the Schema Registry.
-
Create the following Avro schema file
- Avro data
topic_1.
Target database and table
According to the fields of Avro data, create a table sensor_log1 in the target database sensor in the cluster. The column names of the table must match the field names in the Avro data. For the data types mapping when Avro data is loaded into the database, see [Data types mapping](#Data types mapping).
jsonpaths when creating the Routine Load job. Execute the following statement to submit a Routine Load job named sensor_log_load_job1 to consume the Avro messages in the Kafka topic topic_1 and load the data into the table sensor_log1 in the database sensor.
Avro schema contains a nested record-type field
Suppose the Avro schema contains a nested record-type field, and you need to load the subfield in a nested record-type field into the database. Prepare a dataset-
Avro schema
-
Create the following Avro schema file
avro_schema2.avsc. The outer Avro record includes five fields which areid,name,checked,sensor_type, anddatain sequence. And the fielddatahas a nested recorddata_record. - Register the Avro schema in the Schema Registry.
-
Create the following Avro schema file
- Avro data
topic_2.
Target database and table
According to the fields of Avro data, create a table sensor_log2 in the target database sensor in the cluster.
Suppose that in addition to loading the fields id, name, checked, and sensor_type of the outer Record, you also need to load the subfield data_y in the nested Record data_record.
jsonpaths to specify the fields of the Avro data that need to be loaded. Note that for the subfield data_y in the nested Record, you need to specify its jsonpath as "$.data.data_y".
Avro schema contains a Union field
Prepare a dataset Suppose the Avro schema contains a Union field, and you need to load the Union field into the database.-
Avro schema
-
Create the following Avro schema file
avro_schema3.avsc. The outer Avro record includes five fields which areid,name,checked,sensor_type, anddatain sequence. And the fielddatais of Union type and includes two elements,nulland a nested recorddata_record. - Register the Avro schema in the Schema Registry.
-
Create the following Avro schema file
- Avro data
topic_3.
Target database and table
According to the fields of Avro data, create a table sensor_log3 in the target database sensor in the cluster.
Suppose that in addition to loading the fields id, name, checked, and sensor_type of the outer Record, you also need to load the field data_y of the element data_record in the Union type field data.
jsonpaths to specify the fields that need to be loaded in the Avro data. Note that for the field data_y, you need to specify its jsonpath as "$.data.data_y".
data is null, the value loaded into the column data_y in the table is null. When the value for the Union type field data is a data record, the value loaded into the column data_y is of Long type.