ETL stored procedure

Updated at:

When you need to perform full-text searches or complex analysis on business data in PolarDB for PostgreSQL, running these operations directly on the database may affect the stability of your core services. The AutoETL feature provided by PolarDB can automatically and continuously synchronize data from read/write nodes to PolarSearch nodes within the same cluster, providing a one-stop data service. You can synchronize data without deploying or maintaining separate ETL tools, while isolating search and analysis workloads from online transaction processing workloads.

Note

When you use AutoETL to create a pipeline, you authorize the AutoETL engine to access PolarDB data for synchronization by default.

Feature overview

AutoETL is a built-in data synchronization feature in PolarDB for PostgreSQL. It allows data to flow automatically between different types of nodes within a cluster. The current version only supports data synchronization from PolarDB for PostgreSQL to PolarSearch nodes in the same cluster for high-performance search and analysis.

You can use the built-in DBMS_ETL toolkit to create and manage data synchronization pipelines directly with SQL commands. AutoETL offers three flexible data synchronization methods:

  • Single-table synchronization (dbms_etl.sync_by_table): Synchronizes a single source table completely to a destination index.

  • Multi-table aggregation (dbms_etl.sync_by_map): Aggregates multiple source tables using JOIN operations and synchronizes the result to a destination index.

  • Custom SQL (dbms_etl.sync_by_sql): Uses Flink SQL-compatible syntax for complex data cleaning, transformation, and aggregation.

Scope

Before you use the AutoETL feature, make sure the following requirements are met:

  • Cluster version:

    • PostgreSQL 16 (minor engine version 2.0.16.11.15.0 or later)

    • PostgreSQL 14 (minor engine version 2.0.14.22.43.0 or later)

  • Synchronization direction: Data can only be synchronized from PolarDB for PostgreSQL to PolarSearch nodes within the same cluster.

  • DDL limits: You cannot perform DDL operations on a source table that is part of a synchronization pipeline. To modify the table, you must recreate the ETL pipeline.

  • Computing resources: AutoETL uses CUs as computing units. By default, the CU count of a cluster is twice the sum of CPUs across all PolarSearch nodes in the cluster. On the AutoETL tab of the Settings and Management > Search Management page in the console, you can view the number of CUs used by the cluster.

Create a synchronization pipeline

Single-table synchronization

  1. Data preparation

    In PolarDB for PostgreSQL, run the following SQL statement to create a sample database and table, and then insert test data.

    CREATE SCHEMA IF NOT EXISTS db1;
    CREATE TABLE IF NOT EXISTS db1.t1 (
        id INT PRIMARY KEY,
        c1 VARCHAR(100),
        c2 VARCHAR(100)
    );
    INSERT INTO db1.t1(id, c1, c2) VALUES
    (1, 'apple', 'red'),
    (2, 'banana', 'yellow'),
    (3, 'grape', 'purple');
  2. Create the synchronization pipeline

    Use the dbms_etl.sync_by_table stored procedure to create a synchronization task from the db1.t1 table to the dest index on the PolarSearch node.

    Syntax

    SELECT dbms_etl.sync_by_table('search', '<source_table>', '<sink_table>', '<column_list>');

    Parameters

    Parameter

    Description

    search

    The synchronization destination. This is fixed to search, which represents the PolarSearch node.

    <source_table>

    The name of the source table, in SchemaName.TableName format.

    <sink_table>

    The name of the destination index in the PolarSearch node.

    <column_list>

    A list of column names to synchronize, separated by commas (,). If this is an empty string (""), all columns from the source table are synchronized.

    Limits

    • The source table must have a primary key or a unique key.

    • When you specify a column_list, it must include the primary key or unique key.

    • Do not use the same source or destination table in different synchronization pipelines.

    • After the pipeline is created, new columns added to the source table are not automatically synchronized. To synchronize new columns, recreate the pipeline.

    • If you want to use a custom configuration for the destination index, create the index and define its settings in the PolarSearch node before you create the synchronization pipeline. If the destination index does not exist when you create the pipeline, the system creates it automatically.

    Examples

    • Synchronize the entire db1.t1 table to the dest index in PolarSearch:

      SELECT dbms_etl.sync_by_table('search', 'db1.t1', 'dest', '');
    • Synchronize the id and c1 columns of the db1.t1 table to the dest index:

      SELECT dbms_etl.sync_by_table('search', 'db1.t1', 'dest1', 'id, c1');
    • Synchronize the id and c1 columns of the db1.t1 table to the dest index and specify field name mapping (id is mapped to d_id, and c1 is mapped to d_c1):

      SELECT dbms_etl.sync_by_table('search', 'db1.t1', 'dest2', 'd_id(id), d_c1(c1)');
  3. Verify the data

    Connect to the PolarSearch node and use an Elasticsearch-compatible REST API to run a query and confirm that the data is synchronized.

    # Replace <polarsearch_endpoint> with the endpoint of the PolarSearch node
    curl -u <user>:<password> -X GET "http://<polarsearch_endpoint>/dest/_search"

Multi-table aggregation

  1. Data preparation

    In PolarDB for PostgreSQL, run the following SQL statement to create a sample database and tables, and then insert test data.

    CREATE SCHEMA IF NOT EXISTS db2;
    CREATE SCHEMA IF NOT EXISTS db3;
    CREATE SCHEMA IF NOT EXISTS db4;
    
    CREATE TABLE IF NOT EXISTS db2.t2 (id INT PRIMARY KEY, c2 INT);
    CREATE TABLE IF NOT EXISTS db3.t3 (id INT PRIMARY KEY, c3 VARCHAR(10));
    CREATE TABLE IF NOT EXISTS db4.t4 (id INT PRIMARY KEY, c4 INT);
    
    INSERT INTO db2.t2(id, c2) VALUES (1, 111), (2, 222), (4, 444);
    INSERT INTO db3.t3(id, c3) VALUES (1, 'aaa'), (3, 'ccc'), (4, 'ddd');
    INSERT INTO db4.t4(id, c4) VALUES (1, 11), (2, 22), (3, 33);
  2. Create the synchronization pipeline

    Use the dbms_etl.sync_by_map stored procedure to join data from multiple tables and aggregate it into an index on a PolarSearch node.

    Syntax

    SELECT dbms_etl.sync_by_map(
        'search',
        '<columns_map>', -- Mapping of destination index fields to source table fields
        '<join_fields>', -- Join keys between tables
        '<join_types>',  -- Join type (inner, left)
        '<filter>'       -- Data filter condition
    );

    Parameters

    Parameter

    Format example

    Description

    columns_map

    dest.c4(db4.t4.c4),dest.c2(db2.t2.c2)

    The mapping between destination index fields and source table fields.

    In this example, the c4 field of the destination index dest comes from db4.t4.c4, and the c2 field comes from db2.t2.c2.

    join_fields

    dest.id=db4.t4.id,db2.t2.id

    The join keys between tables.

    In this example, the document ID of the destination index (dest.id) is composed of db4.t4.id and db2.t2.id. db4.t4.id and db2.t2.id are also the join conditions.

    join_types

    inner,left

    The join type between tables. The join order corresponds to the order of tables in join_fields. In this example, t4 INNER JOIN t2 is performed, and then the result is LEFT JOIN t3.

    filter

    db4.t4.c4 > 10 AND db2.t2.c2 < 100

    A standard SQL WHERE clause used to filter source table data before synchronization.

    Limits

    • All source tables involved in the synchronization must have a primary key.

    • This feature uses stream processing. Only eventual consistency is guaranteed during synchronization.

    • The update mode for the destination index is delete then insert.

    Examples

    • Two tables INNER JOIN: Perform an INNER JOIN between db4.t4 and db2.t2 on the id field, and synchronize t4.c4 and t2.c2 to the dest index's c4 and c2 fields.

      SELECT dbms_etl.sync_by_map(
        'search',
        'dest.c4(db4.t4.c4),dest.c2(db2.t2.c2)',
        'dest.id=db4.t4.id,db2.t2.id',
        'inner',
        ''
      );
    • Mixed JOIN and filter on multiple tables: Three tables db4.t4, db2.t2, and db3.t3 are joined. An INNER JOIN is performed between t4 and t2, and a LEFT JOIN is performed between t4 and t3. The data is then filtered for records where t4.c4 > 10 and t2.c2 < 100.

      SELECT dbms_etl.sync_by_map(
        'search',
        'dest.c4(db4.t4.c4),dest.c2(db2.t2.c2),dest.c3(db3.t3.c3)',
        'dest.id=db4.t4.id,db2.t2.id,db3.t3.id',
        'inner,left',
        'db4.t4.c4 > 10 and db2.t2.c2 < 100'
      );
  3. Verify the data

    Connect to the PolarSearch node and use an Elasticsearch-compatible REST API to run a query and confirm that the data is synchronized.

    # Replace <polarsearch_endpoint> with the endpoint of the PolarSearch node
    curl -u <user>:<password> -X GET "http://<polarsearch_endpoint>/dest/_search"

Custom SQL

  1. Data preparation

    In PolarDB for PostgreSQL, run the following SQL statement to create a sample database and table, and then insert test data.

    CREATE SCHEMA IF NOT EXISTS syncbysql_test;
    
    CREATE TABLE IF NOT EXISTS syncbysql_test.test_source (
        id SERIAL PRIMARY KEY,
        polardb_document JSONB NOT NULL
    );
    INSERT INTO syncbysql_test.test_source (polardb_document) VALUES
      ('{
          "mailTemplateId": {"S": "TPL-001"},
          "title": {"S": "Welcome Registration Notification"},
          "createdAt": {"S": "2026-01-15 10:30:00"},
          "updatedAt": {"S": "2026-01-15 10:30:00"}
      }'),
      ('{
          "mailTemplateId": {"S": "TPL-002"},
          "title": {"S": "Order Confirmation Email"},
          "createdAt": {"S": "2026-02-01 14:20:00"},
          "updatedAt": {"S": "2026-02-10 09:15:00"}
      }'),
      ('{
          "mailTemplateId": {"S": "TPL-003"},
          "title": {"S": "Password Reset Reminder"},
          "createdAt": {"S": "2026-02-20 08:00:00"},
          "updatedAt": {"S": "2026-03-01 16:45:00"}
      }');
  2. Create the synchronization pipeline

    For scenarios that require complex transformations, aggregations, or calculations, the dbms_etl.sync_by_sql stored procedure supports Flink SQL syntax to define the data synchronization logic.

    Important

    Security warning: Do not hard-code passwords in SQL statements. The following example only demonstrates the syntax. Its WITH clause contains a plaintext password, which is a major security risk. In a production environment, use a more secure method to manage credentials.

    Syntax

    SELECT dbms_etl.sync_by_sql('search', '<sync_sql>');

    Example

    Write the value of the polardb_document JSON field from the test_source table in syncbysql_test to PolarSearch.

    The system automatically replaces the placeholders {postgresql_host}, {postgresql_port}, {postgresql_user}, {postgresql_password}, {search_host}, {search_port}, {search_user}, and {search_password} in the SQL statement. You only need to use these fixed placeholders in your SQL statement.

    select dbms_etl.sync_by_sql(
        'search',
        'CREATE TEMPORARY TABLE test_source_for_sync (
          polardb_document STRING
    ) WITH (
        ''schema-name'' = ''syncbysql_test'',    -- Replace with the schema of the table
        ''database-name'' = ''testdb'',          -- Replace with the database of the table
        ''connector''= ''postgres-cdc'',
        ''hostname'' = ''{pg_host}'',
        ''port'' = ''{pg_port}'',
        ''username'' = ''{pg_user}'',
        ''password'' = ''{pg_password}'',
        ''table-name'' = ''test_source'',        -- Replace with the table to be synchronized
        ''slot.name'' = ''test_slot_3'',        -- Customize a name. This example uses test_slot_3.
        ''decoding.plugin.name'' = ''pgoutput''
    );
    
    CREATE TEMPORARY TABLE test_source_opensearch (
        mail_template_id STRING,
        title STRING,
        created_at STRING,
        updated_at STRING,
        PRIMARY KEY (mail_template_id) NOT ENFORCED
    ) WITH (
        ''connector'' = ''opensearch'',
        ''hosts'' = ''{search_host}'',
        ''index'' = ''test_source_opensearch'',
        ''username'' = ''{search_user}'',
        ''password'' = ''{search_password}''
    );
    
    INSERT INTO test_source_opensearch
    SELECT
        -- Modify this section based on the properties you need to import
        JSON_VALUE(polardb_document, ''$.mailTemplateId.S'') AS mail_template_id,
        JSON_VALUE(polardb_document, ''$.title.S'') AS title,
        JSON_VALUE(polardb_document, ''$.createdAt.S'') AS created_at,
        JSON_VALUE(polardb_document, ''$.updatedAt.S'') AS updated_at
    FROM test_source_for_sync
    WHERE JSON_VALUE(polardb_document, ''$.mailTemplateId.S'') IS NOT NULL; 
    ') AS sync_id;
  3. Verify the data

    Connect to the PolarSearch node and use an Elasticsearch-compatible REST API to run a query and confirm that the data is synchronized.

    # Replace <polarsearch_endpoint> with the endpoint of the PolarSearch node
    curl -u <user>:<password> -X GET "http://<polarsearch_endpoint>/test_source_opensearch/_search"

Manage synchronization pipelines

You can use the following commands to view or delete synchronization pipelines.

View pipelines

  • View all pipelines:

    SELECT dbms_etl.show_sync_link();
  • View a specific pipeline by ID: Replace <sync_id> with the ID returned in Step 2.

    SELECT dbms_etl.show_sync_link_by_id('<sync_id>');

Delete a pipeline

Important

Deleting a synchronization pipeline is a high-risk operation. Make sure that you confirm the operation before you proceed. This operation stops data synchronization of the pipeline and cleans up related resources, but does not delete the index data in PolarSearch.

This operation stops data synchronization and cleans up related resources.

SELECT dbms_etl.drop_sync_link('<sync_id>');

The system processes the drop_sync_link command differently depending on the state of the pipeline:

  • For a pipeline in the active state, its status first changes to dropping. After the system cleans up the pipeline resources and destination index data, the status changes to dropped.

  • For a pipeline in the dropped state, the system completely purges the pipeline's information.

  • The system does not support deleting pipelines in other states.

FAQ

How do I map fields from a PolarDB table to index fields in a PolarSearch node?

AutoETL provides two field mapping methods:

  • Implicit mapping (sync_by_table): When you use sync_by_table, the indexed field names in the PolarSearch node default to the column names in the PolarDB for PostgreSQL source table. You can use the <column_list> parameter to specify the columns to create and synchronize.

  • Explicit mapping (sync_by_map): When you rename fields or aggregate multiple tables, you can use the sync_by_map <columns_map> parameter to explicitly define the mapping between destination fields and source table columns. For example, dest.title(db1.posts.post_title) indicates that the post_title column in the db1.posts table is mapped to the title field in the dest index.