Configure ETL in DTS migration or synchronization tasks

更新时间:
复制 MD 格式

Data Transmission Service (DTS) provides stream-based extract, transform, and load (ETL) data processing capabilities. Combined with DTS’s efficient stream data replication, this feature enables real-time extraction, transformation, manipulation, and loading of streaming data. This topic describes how to configure ETL within a DTS link and provides relevant syntax information to help you use ETL for scenarios such as data filtering, data masking, recording data modification timestamps, and auditing data changes.

Background information

DTS is a data migration and synchronization service typically used for data relocation or real-time data transmission. Sometimes, users need to transform or filter real-time data before writing it to the destination database. To meet this need, DTS offers stream-based ETL data processing using a domain-specific language (DSL) scripting language to flexibly define data processing logic. For an overview of DSL and its configuration syntax, see Introduction to data processing DSL syntax.

DTS supports configuring ETL in two ways:

Note

Both DTS migration tasks and synchronization tasks support ETL configuration. This topic uses synchronization tasks as an example. The configuration method for migration tasks is similar.

Supported databases

The following table lists supported source and destination databases for ETL.

Source database

Destination database

SQL Server

  • AnalyticDB for MySQL 3.0

  • SQL Server

  • MySQL

  • PolarDB for MySQL

MySQL

  • AnalyticDB for MySQL 3.0

  • AnalyticDB for PostgreSQL

  • Kafka

  • ClickHouse cluster

  • MySQL

  • PolarDB for MySQL

  • Elasticsearch

  • Redis

Self-managed Oracle

  • AnalyticDB for MySQL 3.0

  • AnalyticDB for PostgreSQL

  • Kafka

  • MaxCompute

  • PolarDB-X 2.0

  • PolarDB for PostgreSQL (Compatible with Oracle)

PolarDB for MySQL

  • AnalyticDB for MySQL 3.0

  • MySQL

  • PolarDB for MySQL

PolarDB for PostgreSQL (Compatible with Oracle)

  • AnalyticDB for MySQL 3.0

  • PolarDB for PostgreSQL (Compatible with Oracle)

PolarDB-X 1.0

  • Kafka

  • Tablestore

PolarDB-X 2.0

  • PolarDB-X 2.0

  • AnalyticDB for MySQL 3.0

  • MySQL

  • PolarDB for MySQL

Self-managed Db2 for LUW

MySQL

Self-managed Db2 for i

MySQL

PolarDB for PostgreSQL

  • PolarDB for PostgreSQL

  • PostgreSQL

PostgreSQL

  • PolarDB for PostgreSQL

  • PostgreSQL

  • ApsaraDB SelectDB Edition

TiDB

  • PolarDB for MySQL

  • MySQL

  • AnalyticDB for MySQL 3.0

MongoDB

Lindorm

Configure ETL when creating a synchronization task

Notes

  • If your ETL script adds new columns, manually add those columns to the destination database. Otherwise, the ETL script will not take effect. For example, in e_set(`new_column`, dt_now()), you must manually add new_column to the destination database.

  • DSL scripts handle data transformation and cleaning operations only. They do not support creating database objects.

  • Fields referenced in a DSL script must exist in the source database and must not be filtered out by any filter condition. Otherwise, the task may fail.

  • DSL scripts are case-sensitive. Database names, table names, and field names must exactly match those in the source database.

  • DSL scripts do not support multiple expressions. Use the e_compose function to combine multiple expressions into one.

  • All DML changes from all tables in the source database must produce identical column information after DSL processing. Otherwise, the task may fail. For example, if you use the e_set function to add a column, ensure that INSERT, UPDATE, and DELETE operations from the source database all result in the same additional column in the destination table. For more information, see Record data modification time.

Procedure

  1. Create a synchronization task. For details, see Overview of synchronization solutions.

  2. In the Advanced Configurations step, set Configure ETL to Yes.

  3. In the input box, enter your ETL statement using the data processing DSL syntax.

    Note

    For example, to drop records where id is greater than 3, use e_if(op_gt(`id`, 3), e_drop()). Here, op_gt is an expression function that checks if a value is greater than another, and id is a variable. This script filters out records where id > 3.

  4. Complete the remaining steps as needed.

Modify ETL configuration on an existing synchronization task

Modifying ETL configuration on an existing synchronization task includes:

  • If you have an existing sync task that does not have ETL configured—that is, when you created the sync task, Configure ETL was set to No—you can change No to Yes and configure a DSL script.

  • If ETL was already configured, you can modify the existing DSL script or set Configure ETL to No.

    Important
    • To modify an existing DSL script, first move the synchronization object from Selected Objects back to Source Objects, then re-add it to Selected Objects before editing the DSL script.

    • Migration tasks do not support modifying DSL scripts.

Notes

  • Modifying ETL configuration on an existing synchronization task does not support changing the table schema in the destination database. To change the schema, do so in the destination database before starting the synchronization task.

  • Modifying ETL configuration may interrupt the data link. Proceed with caution.

  • ETL configuration changes apply only to incremental data processed after the task is restarted. They do not affect historical data processed before the change.

  • DSL scripts handle data transformation and cleaning operations only. They do not support creating database objects.

  • Fields referenced in a DSL script must exist in the source database and must not be filtered out by any filter condition. Otherwise, the task may fail.

  • DSL scripts are case-sensitive. Database names, table names, and field names must exactly match those in the source database.

  • DSL scripts do not support multiple expressions. Use the e_compose function to combine multiple expressions into one.

  • All DML changes from all tables in the source database must produce identical column information after DSL processing. Otherwise, the task may fail. For example, if you use the e_set function to add a column, ensure that INSERT, UPDATE, and DELETE operations from the source database all result in the same additional column in the destination table. For more information, see Record data modification time.

Procedure

  1. Log on to the list page of new DTS synchronization tasks.

  2. On the target synchronization task, click 点点点 and select Modify ETL Configurations.

  3. In the Advanced Configurations step, set Configure ETL to Yes.

  4. In the input box, enter your ETL statement using the data processing DSL syntax.

    Note

    For example, to drop records where id is greater than 3, use e_if(op_gt(`id`, 3), e_drop()). Here, op_gt is an expression function that checks if a value is greater than another, and id is a variable. This script filters out records where id > 3.

  5. Complete the remaining steps as needed.

Introduction to data processing DSL syntax

Data processing DSL is a scripting language designed by DTS specifically for data processing in data synchronization scenarios. It supports conditional functions and handles strings, dates, and numeric values, letting you flexibly define data processing logic with the following features:

  • Powerful functionality: Offers many functions and supports function composition.

  • Relatively simple syntax: Includes examples for common scenarios such as data filtering, transformation, and masking. For details, see Typical scenario examples.

  • High execution efficiency: Uses code generation technology to minimize performance impact on the synchronization process.

Note
  • In DSL syntax, column names use backticks (``), not single quotes ('').

  • This product references SLS data processing syntax. It supports JSON functions but not event-splitting functions. For SLS syntax, see Syntax introduction.

Typical scenario examples

Data filtering

  • Filter by numeric column: Drop records where id > 10000 so they are not synchronized: e_if(op_gt(`id`, 10000), e_drop()).

  • Filter by string match: Drop records where name contains "hangzhou": e_if(str_contains(`name`, "hangzhou"), e_drop()).

  • Filter by date: Do not synchronize records where order_timestamp is earlier than a specific time: e_if(op_lt(`order_timestamp`, "2015-02-23 23:54:55"), e_drop()).

  • Filter by multiple conditions:

    • Drop records where id > 1000 and name contains "hangzhou": e_if(op_and(str_contains(`name`, "hangzhou"), op_gt(`id`, 1000)), e_drop()).

    • Drop records where id > 1000 or name contains "hangzhou": e_if(op_or(str_contains(`name`, "hangzhou"), op_gt(`id`, 1000)), e_drop()).

Data masking

Masking: Replace the last four digits of the phone number column with asterisks: e_set(`phone`, str_mask(`phone`, 7, 10, '*')).

Record data modification time

  • Add a column to all tables: When __OPERATION__ is INSERT, UPDATE, or DELETE, add a column named "dts_sync_time" with the value of the log commit timestamp (__COMMIT_TIMESTAMP__).

    e_if(op_or(op_or(
            op_eq(__OPERATION__, __OP_INSERT__),
            op_eq(__OPERATION__, __OP_UPDATE__)),
            op_eq(__OPERATION__, __OP_DELETE__)),
        e_set(dts_sync_time, __COMMIT_TIMESTAMP__))
  • Add a column to a specific table "dts_test_table": When __OPERATION__ is INSERT, UPDATE, or DELETE, add a column named "dts_sync_time" with the value of the log commit timestamp (__COMMIT_TIMESTAMP__).

    e_if(op_and(
          op_eq(__TB__,'dts_test_table'),
          op_or(op_or(
            op_eq(__OPERATION__,__OP_INSERT__),
            op_eq(__OPERATION__,__OP_UPDATE__)),
            op_eq(__OPERATION__,__OP_DELETE__))),
          e_set(dts_sync_time,__COMMIT_TIMESTAMP__))
    Note

    You must manually add the "dts_sync_time" column to the destination table before starting the task.

Data change auditing

Record the type and time of data changes: Write the change type to the "operation_type" column and the change timestamp to the "updated" column in the destination database.

e_compose(
    e_switch(
        op_eq(__OPERATION__,__OP_DELETE__), e_set(operation_type, 'DELETE'),
        op_eq(__OPERATION__,__OP_UPDATE__), e_set(operation_type, 'UPDATE'),
        op_eq(__OPERATION__,__OP_INSERT__), e_set(operation_type, 'INSERT')),
    e_set(updated, __COMMIT_TIMESTAMP__),
    e_set(__OPERATION__,__OP_INSERT__)
)
Note

You must add the "operation_type" and "updated" columns to the destination table before starting the task.

Distinguish between full and incremental data

Record whether data comes from full or incremental migration in the is_increment_dml column. You can distinguish between full and incremental migration by checking the value of __COMMIT_TIMESTAMP__. In full migration, __COMMIT_TIMESTAMP__ is 0 (1970-01-01 08:00:00, affected by time zone). In incremental migration, it reflects the source database log write time. The corresponding ETL script is:

e_if_else(__COMMIT_TIMESTAMP__ > DATETIME('2000-01-01 00:00:00'), 
    e_set(`is_increment_dml`, True),
    e_set(`is_increment_dml`, False)
)

Data processing DSL syntax

Constants and variables

  • Constants

    Type

    Example

    int

    123

    float

    123.4

    string

    "hello1_world"

    boolean

    true or false

    datetime

    DATETIME('2021-01-01 10:10:01')

  • Variables

    Variable

    Description

    Data type

    Example value

    __TB__

    Table name

    string

    table

    __DB__

    Database name

    string

    mydb

    __OPERATION__

    Operation type

    string

    __OP_INSERT__, __OP_UPDATE__, __OP_DELETE__

    __BEFORE__

    Pre-image value for UPDATE operations (value before change)

    Note

    DELETE operations have only pre-image values.

    Special marker, no type

    v(`column_name`,__BEFORE__)

    __AFTER__

    Post-image value for UPDATE operations (value after change)

    Note

    INSERT operations have only post-image values.

    Special marker, no type

    v(`column_name`,__AFTER__)

    __COMMIT_TIMESTAMP__

    Transaction commit time

    datetime

    '2021-01-01 10:10:01'

    `column`

    Value of the specified column for a record

    string

    `id`, `name`

Expression functions

  • Numeric operations

    Function

    Syntax

    Value range

    Return value

    Example

    Addition

    op_sum(value1, value2)

    • value1: integer or floating-point number

    • value2: integer or floating-point number

    Returns an integer if both parameters are integers; otherwise, returns a floating-point number.

    op_sum(`col1`, 1.0)

    Subtraction

    op_sub(value1, value2)

    • value1: integer or floating-point number

    • value2: integer or floating-point number

    Returns an integer if both parameters are integers; otherwise, returns a floating-point number.

    op_sub(`col1`, 1.0)

    Multiplication

    op_mul(value1, value2)

    • value1: integer or floating-point number

    • value2: integer or floating-point number

    Returns an integer if both parameters are integers; otherwise, returns a floating-point number.

    op_mul(`col1`, 1.0)

    Division

    op_div_true(value1, value2)

    • value1: integer or floating-point number

    • value2: integer or floating-point number

    Returns an integer if both parameters are integers; otherwise, returns a floating-point number.

    op_div_true(`col1`, 2.0); if col1=15, returns 7.5.

    Modulo operation

    op_mod(value1, value2)

    • value1: integer or floating-point number

    • value2: integer or floating-point number

    Returns an integer if both parameters are integers; otherwise, returns a floating-point number.

    op_mod(`col1`, 10); if col1=23, returns 3.

  • Logical operations

    Function

    Syntax

    Valid values

    Return value

    Example

    Equality check

    op_eq(value1, value2)

    • value1: integer, floating-point number, or string

    • value2: integer, floating-point number, or string

    Boolean: true or false

    op_eq(`col1`, 23)

    Greater-than check

    op_gt(value1, value2)

    • value1: integer, floating-point number, or string

    • value2: integer, floating-point number, or string

    Boolean: true or false

    op_gt(`col1`, 1.0)

    is less than

    op_lt(value1, value2)

    • value1: integer, floating-point number, or string

    • value2: integer, floating-point number, or string

    Boolean: true or false

    op_lt(`col1`, 1.0)

    Greater-than-or-equal check

    op_ge(value1, value2)

    • value1: integer, floating-point number, or string

    • value2: integer, floating-point number, or string

    Boolean: true or false

    op_ge(`col1`, 1.0)

    Less-than-or-equal check

    op_le(value1, value2)

    • value1: integer, floating-point number, or string

    • value2: integer, floating-point number, or string

    Boolean: true or false

    op_le(`col1`, 1.0)

    AND operation

    op_and(value1, value2)

    • value1: boolean

    • value2: boolean

    Boolean: true or false

    op_and(`is_male`, `is_student`)

    OR operation

    op_or(value1, value2)

    • value1: boolean

    • value2: boolean

    Boolean: true or false

    op_or(`is_male`, `is_student`)

    IN operation

    op_in(value, json_array)

    • value: any type

    • json_array: JSON-formatted string

    Boolean: true or false

    op_in(`id`,json_array('["0","1","2","3","4","5","6","7","8"]'))

    Check if value is null

    op_is_null(value)

    value: any type

    Boolean: true or false

    op_is_null(`name`)

    Check if value is not null

    op_is_not_null(value)

    value: any type

    Boolean: true or false

    op_is_not_null(`name`)

  • String functions

    Function

    Syntax

    Value range

    Return value

    Example

    String concatenation

    op_add(str_1,str_2,...,str_n)

    • str_1: string

    • str_2: string

    • ...

    • str_n: string

    Concatenated string

    op_add(`col`,'hangzhou','dts')

    String formatting and concatenation

    str_format(format, value1, value2, value3, ...)

    • format: string with braces as placeholders, such as "part1: {}, part2: {}"

    • value1: any type

    • value2: any type

    Formatted string

    str_format("part1: {}, part2: {}", `col1`, `col2`); if col1="ab" and col2="12", returns "part1: ab, part2: 12".

    String replacement

    str_replace(original, oldStr, newStr, count)

    • original: original string

    • oldStr: string to replace

    • newStr: replacement string

    • count: integer, maximum number of replacements. Set to -1 for all occurrences.

    Replaced string

    str_replace(`name`, "a", 'b', 1); if name="aba", returns "bba". str_replace(`name`, "a", 'b', -1); if name="aba", returns "bbb".

    Replace values in all string-type fields (such as varchar, text, char)

    tail_replace_string_field(search, replace, all)

    • search: string to replace

    • replace: replacement string

    • all: whether to replace all matches; currently supports only true.

      Note

      If you do not want to replace all matches, use the str_replace function.

    Replaced string

    tail_replace_string_field('\u000f', '', true) replaces all occurrences of "\u000f" in string-type field values with a space.

    Remove specified characters from start and end of string

    str_strip(string_val, charSet)

    • string_val: original string

    • char_set: set of characters to remove

    String with leading and trailing characters removed

    str_strip(`name`, 'ab'); if name=axbzb, returns xbz.

    Convert string to lowercase

    str_lower(value)

    value: string column or string literal

    Lowercase string

    str_lower(`str_col`)

    Convert string to uppercase

    str_upper(value)

    value: string column or string literal

    Uppercase string

    str_upper(`str_col`)

    Convert string to number

    cast_string_to_long(value)

    value: string

    Integer

    cast_string_to_long(`col`)

    Convert number to string

    cast_long_to_string(value)

    value: integer

    String

    cast_long_to_string(`col`)

    Count substring occurrences

    str_count(str,pattern)

    • str: string column or string literal

    • pattern: substring to find

    Number of times the substring appears

    str_count(`str_col`, 'abc'); if str_col="zabcyabcz", returns 2.

    Find substring position

    str_find(str, pattern)

    • str: string column or string literal

    • pattern: substring to find

    Position of first match; returns `-1` if not found

    str_find(`str_col`, 'abc'); if `str_col="xabcy"`, returns `1`.

    Check if string consists only of letters

    str_isalpha(str)

    str: string column or string literal

    true or false

    str_isalpha(`str_col`)

    Check if string consists only of digits

    str_isdigit(str)

    • str: string column or string literal

    true or false

    str_isdigit(`str_col`)

    Regular expression matching

    regex_match(str,regex)

    • str: string column or string literal

    • regex: regular expression string column or string literal

    true or false

    regex_match(__TB__,'user_\\d+')

    Mask part of a string with a specified character for data masking, such as replacing the last four digits of a phone number with asterisks

    str_mask(str, start, end, maskStr)

    • str: string column or string literal

    • start: integer, starting position for masking (minimum 0)

    • end: integer, ending position for masking (maximum string length minus one)

    • maskStr: single-character string, such as '#'

    String with characters from start to end masked

    str_mask(`phone`, 7, 10, '#')

    Extract part of string after cond

    substring_after(str, cond)

    • str: original string

    • cond: string

    String

    Note

    Result does not include cond.

    substring_after(`col`, 'abc')

    Extract part of string before cond

    substring_before(str, cond)

    • str: original string

    • cond: string

    String

    Note

    Result does not include cond.

    substring_before(`col`, 'efg')

    Extract part of string between cond1 and cond2

    substring_between(str, cond1, cond2)

    • str: original string

    • cond1: string

    • cond2: string

    String

    Note

    Result does not include cond1 or cond2.

    substring_between(`col`, 'abc','efg')

    Check if value is a string type

    is_string_value(value)

    value: string or column name

    Boolean: true or false

    is_string_value(`col1`)

    Replace content in string-type fields; starts from the end in reverse order

    tail_replace_string_field(search, replace, all)

    search: string to replace

    replace: replacement string

    all: whether to replace all; true or false

    Replaced string

    Replace "\u000f" with a space in all string field values.

    tail_replace_string_field('\u000f','',true)

    Get value of a field in MongoDB

    bson_value("field1","field2","field3",...)

    • field1: top-level field name

    • field2: second-level field name

    Value of the specified field in the document

    • e_set(`user_id`, bson_value("id"))

    • e_set(`user_name`, bson_value("person","name"))

  • Date and time functions

    Function

    Syntax

    Value range

    Return value

    Example

    Current system time

    dt_now()

    None

    DATETIME, accurate to seconds

    dts_now()

    dt_now_millis()

    None

    DATETIME, accurate to milliseconds

    dt_now_millis()

    Convert UTC timestamp (seconds) to DATETIME

    dt_fromtimestamp(value,[timezone])

    • value: integer

    • timezone: time zone (optional)

    DATETIME, accurate to seconds

    dt_fromtimestamp(1626837629)

    dt_fromtimestamp(1626837629,'GMT+08')

    Convert UTC timestamp (milliseconds) to DATETIME

    dt_fromtimestamp_millis(value,[timezone])

    • value: integer

    • timezone: time zone (optional)

    DATETIME, accurate to milliseconds

    dt_fromtimestamp_millis(1626837629123);

    dt_fromtimestamp_millis(1626837629123,'GMT+08')

    Convert DATETIME to UTC timestamp (seconds)

    dt_parsetimestamp(value,[timezone])

    • value: DATETIME

    • timezone: time zone (optional)

    Integer

    dt_parsetimestamp(`datetime_col`)

    dt_parsetimestamp(`datetime_col`,'GMT+08')

    Convert DATETIME to UTC timestamp (milliseconds)

    dt_parsetimestamp_millis(value,[timezone])

    • value: DATETIME

    • timezone: time zone (optional)

    Integer

    dt_parsetimestamp_millis(`datetime_col`)

    dt_parsetimestamp_millis(`datetime_col`,'GMT+08')

    Convert DATETIME to string

    dt_str(value, format)

    • value: DATETIME

    • format: string in yyyy-MM-dd HH:mm:ss format

    String

    dt_str(`col1`, 'yyyy-MM-dd HH:mm:ss')

    Convert string to DATETIME

    dt_strptime(value,format)

    • value: string

    • format: string in yyyy-MM-dd HH:mm:ss format

    DATETIME

    dt_strptime('2021-07-21 03:20:29', 'yyyy-MM-dd hh:mm:ss')

    Adjust time by adding or subtracting years, months, days, hours, minutes, or seconds

    dt_add(value, [years=intVal],

    [months=intVal],

    [days=intVal],

    [hours=intVal],

    [minutes=intVal]

    )

    • value: DATETIME

    • intVal: integer

      Note

      The minus sign (−) indicates subtraction.

    DATETIME

    • dt_add(datetime_col,years=-1)

    • dt_add(datetime_col,years=1,months=1)

  • Conditional expressions

    Function

    Syntax

    Value range

    Return value

    Example

    Similar to the ternary operator (? :) in C, returns a value based on a condition

    (cond ? val_1 : val_2)

    • cond: boolean field or expression

    • val_1: return value 1

    • val_2: return value 2

      Note

      val_1 and val_2 must be of the same type.

    Returns val_1 if cond is true; otherwise, returns val_2

    (id>1000? 1 : 0)

  • JSON functions

    Note

    The value type represents any field type in the database.

    Function

    Syntax

    Value range

    Return value

    Example

    Convert a JSON array string to a Set

    json_array(arrayText)

    Note

    Can only be used in expressions that return a boolean.

    arrayText: string, the JSON array string to convert

    Set

    op_in(`id`,json_array('["0","1","2","3"]')) returns the Set ["0","1","2","3"].

    Create a JSON array with specified data

    json_array2(item...)

    item...: value type, data for the JSON array

    JSON array

    json_array2("0","1","2","3") returns ["0","1","2","3"].

    Create a JSON object with specified data

    json_object(item...)

    item...: data of a JSON object (key-value pairs), consisting of a key name (string) and a key value (value type), separated by a comma (,).

    JSON

    json_object('name','ZhangSan','age',32, 'loginId',100) returns {"name":"ZhangSan","age":32,"loginId":100}.

    Insert data at a specified position (array) in a JSON object

    json_array_insert(json, kvPairs...)

    • json: string, the JSON object to modify

    • kvPairs...: data to insert. Each pair consists of a JSONPath (string) and a value (value type), separated by a comma.

    JSON

    Note
    • If the specified position does not exist, returns the original JSON object.

    • If the element at the specified position does not exist, the data is appended to the end of the target array.

    json_array_insert('{"Address":["City",1]}','$.Address[3]',100) returns {"Address":["City",1,100]}.

    Insert data at a specified position in a JSON object

    json_insert(json, kvPairs...)

    • json: string, the JSON object to modify

    • kvPairs...: data to insert. Each pair consists of a JSONPath (string) and a value (value type), separated by a comma.

    JSON

    Note
    • If the specified location exists, the system returns the JSON object to be operated on.

    • If the specified position does not exist, the data is added to the JSON object.

    json_insert('{"Address":["City","Xian","Number",1]}','$.ID',100) returns {"Address":["City","Xian","Number",1],"ID":100}.

    Insert or update data at a specified position in a JSON object

    json_set(json, kvPairs...)

    • json: string, the JSON object to modify

    • kvPairs...: data to insert or update. Each pair consists of a JSONPath (string) and a value (value type), separated by a comma.

    value type

    Note
    • If the specified position exists, updates the data.

    • If the specified position does not exist, adds the data to the JSON object.

    json_set('{"ID":1,"Address":["City","Xian","Number",1]}',"$.IP",100) returns {"ID":1,"Address":["City","Xian","Number",1], "IP":100}.

    Insert or update a key-value pair in a JSON object

    json_put(json, key, value)

    • json: string, the JSON object to modify

    • key: string, the key name to insert or update

    • value: value type, the value for the key

    JSON

    Note
    • If json is not a JSON object, returns null.

    • If the key exists, updates its value.

    • If the key does not exist, adds it to the JSON object.

    json_put('{"loginId":100}','loginTime','2024-10-10') returns {"loginId":100, "loginTime":"2024-10-10"}.

    Replace data at a specified position in a JSON object

    json_replace(json, kvPairs...)

    • json: string, the JSON object to modify

    • kvPairs...: data to replace. Each pair consists of a JSONPath (string) and a value (value type), separated by a comma.

    value type

    Note

    If the specified position does not exist, returns the original JSON object.

    json_replace('{"ID":1,"Address":["City","Xian","Number",1]}',"$.IP",100) returns {"ID":1,"Address":["City","Xian","Number",1]}.

    Check if specified data exists at a position in a JSON object

    json_contains(json, jsonPath, item)

    • json: string, the JSON object to query

    • jsonPath: string, the position in the JSON object

    • item: value type, the data to search for

    Boolean: true or false

    json_contains('{"ID":1,"Address":["City","Xian","Number",1]}','$.ID',1) returns true.

    Check whether a specified position exists in a JSON object.

    json_contains_path(json, jsonPath)

    • json: string, the JSON object to query

    • jsonPath: string, the position to check

    Boolean: true or false

    json_contains_path('{"ID":1,"Address":["City","Xian","Number",1]}','$.ID') returns true.

    Get data from a specified position in a JSON object

    json_extract(json, jsonPath)

    • json: string, the JSON object to query

    • jsonPath: string, the position in the JSON object

    value type

    json_extract('{"ID":1,"Address":["City","Xian","Number",1]}','$.ID') returns 1.

    Get the value of a specified key in a JSON object

    json_get(json, key)

    • json: string, the JSON object to query

    • key: string, the key name

    value type

    json_get('{"ID":1,"Address":["City","Xian","Number",1]}','ID') returns 1.

    Get all keys at a specified position in a JSON object

    json_keys(json, jsonPath)

    • json: string, the JSON object to query

    • jsonPath: string, the position in the JSON object

    JSON array

    json_keys('{"ID":1,"Address":["City","Xian","Number",1]}','$') returns ["ID","Address"].

    Get the length (number of keys) at a specified position in a JSON object

    json_length(json, jsonPath)

    • json: string, the JSON object to query

    • jsonPath: string, the position in the JSON object

      Note

      If jsonPath is "$", it is equivalent to json_length(json).

    Integer

    json_length('{"ID":1,"Address":["City","Xian","Number",1]}','$') returns 2.

    Get the length (number of keys) at the root of a JSON object

    json_length(json)

    json: string, the JSON object to query

    Integer

    json_length('{"ID":1,"Address":["City","Xian","Number",1]}') returns 2.

    Parse a JSON string into a JSON object

    json_parse(json)

    json: string, the JSON string to parse

    value type

    json_parse('{"ID":1,"Address":["City","Xian","Number",1]}') returns {"ID":1,"Address":["City","Xian","Number",1]}.

    Remove data from a specified position in a JSON object

    json_remove(json, jsonPath)

    • json: string, the JSON object to modify

    • jsonPath: string, the position in the JSON object

    JSON

    json_remove('{"loginId":100, "loginTime":"2024-10-10"}','$.loginTime') returns {"loginId":100}.

Global functions

  • Flow control functions

    Function

    Syntax

    Parameters

    Example

    if statement

    e_if(bool_expr, func_invoke)

    • bool_expr: boolean constant or function call. Constants: true or false. Function call example: op_gt(`id`, 10).

    • func_invoke: function call. Supported: e_drop, e_keep, e_set, e_if, e_compose

    e_if(op_gt(`id`, 10), e_drop()); drops the record if ID > 10.

    if-else statement

    e_if_else(bool_expr, func_invoke1, func_invoke2)

    • bool_expr: boolean constant or function call. Constants: true or false. Function call example: op_gt(`id`, 10).

    • func_invoke1: function call executed if condition is true.

    • func_invoke2: function call executed if condition is false.

    e_if_else(op_gt(`id`, 10), e_set(`tag`, 'large'), e_set(`tag`, 'small')); sets tag to "large" if ID > 10, otherwise to "small".

    Switch-like statement that evaluates multiple conditions and executes the first matching operation. Executes a default operation if no conditions match.

    s_switch(condition1, func1, condition2, func2, ..., default=default_func)

    • condition1: boolean constant or function call. Constants: true or false. Function call example: op_gt(`id`, 10).

    • func_invoke: function call. Checks condition1; if true, executes this function and exits the switch. If false, checks the next condition.

    • default_func: function call executed if all conditions are false.

    e_switch(op_gt(`id`, 100), e_set(`str_col`, '>100'), op_gt(`id`, 90), e_set(`str_col`, '>90'), default=e_set(`str_col`, '<=90')).

    Combine multiple operations

    e_compose(func1, func2, func3, ...)

    • func1: function call. Can be e_set, e_drop, e_if.

    • func2: function call. Can be e_set, e_drop, e_if.

    e_compose(e_set(`str_col`, 'test'), e_set(`dt_col`, dt_now())); sets str_col to "test" and dt_col to the current time.

  • Data manipulation functions

    Function

    Syntax

    Parameters

    Example

    Drop this record (do not synchronize)

    e_drop()

    None

    e_if(op_gt(`id`, 10), e_drop()); drops records where ID > 10.

    Keep this record (synchronize to destination)

    e_keep(condition)

    condition: boolean expression

    e_keep(op_gt(id, 1)); synchronizes only records where ID > 1.

    Set column value

    e_set(`col`, val, NEW)

    • col: column name

    • val: constant or function call. Must match col's data type.

    • NEW: converts col to val's data type (optional)

      Important

      If you omit NEW, do not include the preceding comma. Ensure data type compatibility to avoid task errors.

    • e_set(`dt_col`, dt_now()); sets dt_col to current time.

    • e_set(`col1`, `col2` + 1); sets col1 to col2 + 1.

    • e_set(`col1`, 1, NEW); converts col1 to numeric type and sets it to 1.

    MongoDB field retention, field dropping, and field name mapping

    e_expand_bson_value('*', 'fieldA',{"fieldB":"fieldC"})

    • *: field names to retain; * means all fields.

    • fieldA: field names to drop.

    • {"fieldB":"fieldC"}: field name mapping; fieldB is the source field name, fieldC is the destination field name.

      Note

      Field name mapping is optional.

    e_expand_bson_value("*", "_id,name"); writes all fields except _id and name to the destination.