MaxCompute SQL connector

Updated at:

This topic describes the syntax, WITH parameters, and examples of the MaxCompute connector.

Background information

MaxCompute (formerly ODPS) is a fast, fully managed, exabyte-scale data warehouse solution for batch storage and computing of structured data. It provides massive data warehousing, analytics, and modeling services.

The MaxCompute connector supports the following capabilities.

Category

Details

Supported table types

Source table, dimension table, sink table, and data ingestion sink

Running modes

Streaming mode and batch mode

Data formats

Not supported

Metrics

Metrics

  • Source table

    numRecordsIn

    numRecordsInPerSecond

    numBytesIn

    numBytesInPerSecond

  • Sink table

    numRecordsOut

    numRecordsOutPerSecond

    numBytesOut

    numBytesOutPerSecond

  • Dimension table

    dim.odps.cacheSize

Note

For details about these metrics, see Metrics.

API types

DataStream, SQL, and data ingestion YAML jobs

Update and delete support

Batch Tunnel and Stream Tunnel support only data insertion. Upsert Tunnel supports insert, update, and delete operations.

For how to use MaxCompute as the sink of a data ingestion YAML job, see MaxCompute YAML connector.

Prerequisites

Create a MaxCompute table. For details, see Create a table.

Limitations

  • The MaxCompute connector supports only at-least-once semantics.

    Note

    At-least-once semantics guarantees no data loss, but duplicate data may be written to MaxCompute in rare cases. Duplicate data behaves differently for different MaxCompute tunnels. For details about MaxCompute tunnels, see How do I select a data tunnel?

  • By default, a source table operates in full mode. It reads only the partition specified by the partition parameter, finishes after reading all data, and switches to the finished state. It does not monitor whether new partitions are created.

    To continuously monitor new partitions, specify startPartition in the WITH parameters to use the incremental source table mode.

    Note
    • A dimension table checks the latest partition on every refresh and is not subject to this limitation.

    • After the source table starts, new data added to a partition is not read. Run the job only when the partition data is complete.

SQL

The MaxCompute connector can be used in SQL jobs as a source table, dimension table, or sink table.

Syntax

CREATE TEMPORARY TABLE odps_source(
  id INT,
  user_name VARCHAR,
  content VARCHAR
) WITH (
  'connector' = 'odps', 
  'endpoint' = '<yourEndpoint>',
  'project' = '<yourProjectName>',
  'schemaName' = '<yourSchemaName>',
  'tableName' = '<yourTableName>',
  'accessId' = '${secret_values.ak_id}',
  'accessKey' = '${secret_values.ak_secret}',
  'partition' = 'ds=2018****'
);

Parameters in the WITH clause

General

Parameter

Description

Data type

Required

Default value

Remarks

connector

Table type.

String

Yes

None

Fixed value: odps.

endpoint

MaxCompute endpoint.

String

Yes

None

See Endpoint.

tunnelEndpoint

Endpoint of the MaxCompute Tunnel service.

String

No

None

See Endpoint.

Note

If this parameter is not specified, MaxCompute allocates tunnel connections through its internal load balancing service.

project

MaxCompute project name.

String

Yes

None

None.

schemaName

MaxCompute schema name.

String

No

None

Required only when the MaxCompute project has the schema feature enabled. Set this parameter to the schema that owns the MaxCompute table. For details, see Schema operations.

Note

Supported only in VVR 8.0.6 and later.

tableName

MaxCompute table name.

String

Yes

None

None.

accessId

MaxCompute AccessKey ID.

String

Yes

None

For details, see How do I view the AccessKey ID and AccessKey secret?

Important

To prevent AccessKey leakage, store the AccessKey as a variable. For details, see Project variables.

accessKey

MaxCompute AccessKey secret.

String

Yes

None

partition

MaxCompute partition name.

String

No

None

Not required for non-partitioned tables or incremental source tables.

compressAlgorithm

Compression algorithm used by MaxCompute Tunnel.

String

No

SNAPPY

Valid values:

  • RAW (no compression)

  • ZLIB

  • SNAPPY

    SNAPPY delivers a significant throughput improvement over ZLIB. In test scenarios, throughput improves by about 50%.

quotaName

Name of the exclusive MaxCompute data transmission service quota.

String

No

None

Set this parameter to use the exclusive MaxCompute data transmission service.

Important
  • Supported only in VVR 8.0.3 and later.

  • This parameter takes effect only when endpoint is set to a VPC address. If endpoint is set to a public address or tunnelEndpoint is specified, tunnelEndpoint or the default data tunnel is used and quotaName does not take effect.

Note

For details about exclusive MaxCompute data transmission, see Purchase and use an exclusive data transmission resource group .

kms.endpoint

The KMS gateway address (dedicated gateway or shared gateway).

String

Required when you use KMS credentials

None

The shared gateway endpoint is fixed by region, for example, kms.cn-beijing.aliyuncs.com. For a dedicated gateway, enter the VPC address of the KMS instance.

Note

Supported only in VVR 11.10 and later.

kms.akless.assume-role.role-name

The name of the RAM role used to access KMS.

String

Required when you use KMS credentials

None

The role must be referenced in advance under Security Services > Access Security > RAM Roles.

Note

Supported only in VVR 11.10 and later.

kms.ca

The path of the CA certificate for a dedicated KMS gateway.

String

Required only for dedicated gateways

None

Download the CA certificate from the KMS instance details page, upload it on the Flink File Management page, and then copy the OSS path. The fully managed storage format is oss://flink-fullymanaged-<workspace ID>/artifacts/namespaces/<namespace name>/<file name>. The OSS bucket format is oss://<bound bucket name>/artifacts/namespaces/<namespace name>/<file name>. This parameter is not required for shared gateways.

Note

Supported only in VVR 11.10 and later.

Source table only

Parameter

Description

Data type

Required

Default value

Remarks

maxPartitionCount

Maximum number of partitions that can be read.

Integer

No

100

If the number of partitions to read exceeds this parameter, the following error occurs: The number of matched partitions exceeds the default limit.

Important

Reading too many partitions at once increases MaxCompute load and slows job startup. Verify that the partition parameter is not misconfigured. If reading a large number of partitions is required, increase maxPartitionCount manually.

useArrow

Specifies whether to read data in Arrow format.

Boolean

No

false

Arrow format enables the MaxCompute Storage API.

Important
  • Takes effect only in batch jobs.

  • Supported only in VVR 8.0.8 and later.

splitSize

Size of the data pulled at a time when reading data in Arrow format.

MemorySize

No

256 MB

Supported only in VVR 8.0.8 and later.

Important

Takes effect only in batch jobs.

compressCodec

Compression algorithm used when reading data in Arrow format.

String

No

""

Valid values:

  • "" (no compression)

  • ZSTD

  • LZ4_FRAME

Specifying a compression algorithm improves throughput compared with no compression.

Important
  • Takes effect only in batch jobs.

  • Supported only in VVR 8.0.8 and later.

dynamicLoadBalance

Specifies whether to allow dynamic shard allocation.

Boolean

No

false

Valid values:

  • true: allowed

  • false: not allowed

Dynamic shard allocation uses the processing performance of different Flink nodes and reduces the overall read time of the source table. However, different nodes then read different amounts of data, which causes data skew.

Important
  • Takes effect only in batch jobs.

  • Supported only in VVR 8.0.8 and later.

source.dynamic-parallelism.enabled

Specifies whether to allow the platform to automatically scale the source table without a restart.

Boolean

No

false

This is an experimental feature for scenarios that require minimal business interruption.

This feature involves job topology changes. Before you enable it, take a snapshot of the Flink job for recovery.

Note
  • Takes effect only for streaming jobs with automatic tuning enabled. For more information, see Configure automatic tuning.

  • Supported only in VVR 11.10 and later.

Incremental source table only

The incremental source table discovers new partitions by polling the MaxCompute server for all partition information at intervals. Data in a new partition must be completely written before the partition is read. For details, see What do I do if an incremental MaxCompute source table detects a new partition while data is still being written to the partition? Use startPartition to specify the start position. Only partitions whose lexicographic order is greater than or equal to the start position are read. For example, partition year=2023,month=10 is lexicographically smaller than partition year=2023,month=9. Pad partition values with zeros to keep the lexicographic order correct, for example year=2023,month=09.

Parameter

Description

Data type

Required

Default value

Remarks

startPartition

Start partition position for incremental reads (inclusive).

String

Yes

None

  • When this parameter is specified, the incremental source table mode is enabled and the partition parameter is ignored.

  • For multi-level partitions, declare the value of each partition column in descending order of partition level.

subscribeIntervalInSec

Interval for polling MaxCompute for the partition list.

Integer

No

30

Unit: seconds.

modifiedTableOperation

Action to take when partition data is modified during partition reads.

Enum (NONE, SKIP)

No

NONE

The download session is stored in checkpoints. Each time the job recovers from a checkpoint, Flink tries to resume reading from that session. If the session is unavailable because the partition data was modified, the Flink job keeps restarting. In this case, set this parameter. Valid values:

  • NONE: change startPartition to a value greater than the unavailable partition, and then start the job without state.

  • SKIP: if you do not want to start without state, change the mode to SKIP. Flink skips unavailable partitions when it tries to restore the session from a checkpoint.

Important
  • Supported only in VVR 8.0.3 and later.

  • In NONE and SKIP modes, data already read from a modified partition is not rolled back, and unread data is not read.

Sink table only

Parameter

Description

Data type

Required

Default value

Remarks

useStreamTunnel

Specifies whether to upload data with MaxCompute Stream Tunnel.

Boolean

No

false

Valid values:

  • true: upload data with MaxCompute Stream Tunnel.

  • false: upload data with MaxCompute Batch Tunnel.

Note

For details about how to select a data tunnel, see How do I select a data tunnel?

Important

When data is uploaded with Stream Tunnel and a server node undergoes disaster recovery, such as an unexpected restart or shutdown, the client receives 502 errors for a long time. Use VVR 11.1 or later, which adds exception detection optimizations for this scenario.

flushIntervalMs

Flush interval of the MaxCompute Tunnel Writer buffer.

Long

No

30000 (30 seconds)

Data is first written to the buffer and then written to the target table in batches when the buffer is full or the flushIntervalMs interval is reached.

  • Stream Tunnel: flushed data is immediately visible.

  • Batch Tunnel: data is visible only after the checkpoint completes. Set flushIntervalMs to 0 to disable scheduled flush and avoid latency.

Unit: milliseconds.

Note

This parameter can be used together with batchSize. Data is flushed when either condition is met.

batchSize

Flush size of the MaxCompute Tunnel Writer buffer.

Long

No

67108864 (64 MB)

Unit: bytes.

Records are first stored in the MaxCompute buffer. When the buffer reaches the specified size (batchSize), the buffered data is written to the target MaxCompute table.

Note

This parameter can be used together with flushIntervalMs. Data is flushed when either condition is met.

numFlushThreads

Number of threads that flush the MaxCompute Tunnel Writer buffer.

Integer

No

1

Each MaxCompute sink subtask creates numFlushThreads threads to flush data. When the value is greater than 1, data in different partitions is flushed concurrently, which improves flush efficiency.

numCommitThreads

Number of threads that the MaxCompute Tunnel Writer uses to commit data.

Integer

No

1

Each MaxCompute sink subtask creates numCommitThreads threads to commit changes. When the value is greater than 1, data in different partitions is committed concurrently, which improves commit efficiency.

Note
  • Applies to Batch Tunnel and Stream Tunnel writes, but not to Delta Table writes.

  • Supported only in VVR 11.10 and later.

slotNum

Number of slots used by MaxCompute Tunnel Writer.

Integer

No

0

For details about slot limits, see Data transmission service overview.

dynamicPartitionLimit

Maximum number of dynamic partitions that can be written.

Integer

No

100

If the number of dynamic partitions written by the sink table between two checkpoints exceeds dynamicPartitionLimit, the following error occurs: Too many dynamic partitions.

Important

Writing a large number of partitions at once puts pressure on the MaxCompute service and slows down sink flushes and job checkpoints. When this error occurs, verify that so many partitions are required. If they are, increase the dynamicPartitionLimit parameter manually.

retryTimes

Maximum number of retries for requests to the MaxCompute server.

Integer

No

3

Creating sessions, committing sessions, and flushing data can temporarily fail when the MaxCompute service is unavailable. These operations are retried based on this configuration.

sleepMillis

Retry interval.

Integer

No

1000

Unit: milliseconds.

enableUpsert

Specifies whether to upload data with MaxCompute Upsert Tunnel.

Boolean

No

false

Valid values:

  • true: use Upsert Tunnel to process INSERT, UPDATE_AFTER, and DELETE data in Flink.

  • false: use Batch Tunnel or Stream Tunnel, based on the useStreamTunnel parameter, to process INSERT and UPDATE_AFTER data in Flink.

Important
  • In upsert mode, if MaxCompute sink commits fail, take a long time, or return errors, limit the sink parallelism to 10 or less.

  • Supported only in VVR 8.0.6 and later.

upsertAsyncCommit

Specifies whether to commit sessions asynchronously in upsert mode.

Boolean

No

false

Valid values:

  • true: commit asynchronously. Commits take less time, but written data is not immediately readable when the commit completes.

  • false: commit synchronously (default). Commits wait until the server finishes processing the session.

Note

Supported only in VVR 8.0.6 and later.

upsertCommitTimeoutMs

Timeout for committing sessions in upsert mode.

Integer

No

120000

(120 seconds)

Unit: milliseconds.

Note

Supported only in VVR 8.0.6 and later.

sink.operation

Write mode for Delta Table writes.

String

No

insert

Valid values:

  • insert: append data.

  • upsert: update data.

Note

Supported only in VVR 8.0.10 and later.

sink.parallelism

Parallelism for Delta Table writes.

Integer

No

None

  • Write parallelism. If this parameter is not set, the parallelism of the upstream data is used.

  • Supported only in VVR 8.0.10 and later.

Important

Make sure the Delta Table property write.bucket.num is a multiple of this value. This delivers the best write performance and saves the most memory on sink nodes.

sink.file-cached.enable

Specifies whether to use the file cache mode when writing to dynamic partitions of a Delta table.

Boolean

No

false

Valid values:

  • true: use the file cache mode.

  • false: do not use the file cache mode.

The file cache mode reduces the number of small files written to the server but increases write latency. Use the file cache mode when the sink table parallelism is high.

Note

Supported only in VVR 8.0.10 and later.

sink.file-cached.writer.num

Number of concurrent data uploads per task in the file cache mode.

Integer

No

16

  • Takes effect only when sink.file-cached.enable is set to true.

  • Do not increase this value significantly. Writing to too many partitions at the same time can cause out-of-memory (OOM) errors.

Note

Supported only in VVR 8.0.10 and later.

sink.bucket.check-interval

Interval for checking file size in the file cache mode. Unit: milliseconds (ms).

Integer

No

60000

Takes effect only when sink.file-cached.enable is set to true.

Note

Supported only in VVR 8.0.10 and later.

sink.file-cached.rolling.max-size

Maximum size of a single cache file in the file cache mode.

MemorySize

No

16 M

  • Takes effect only when sink.file-cached.enable is set to true.

  • If a file exceeds this size, the file data is uploaded to the server.

Note

Supported only in VVR 8.0.10 and later.

sink.file-cached.memory

Maximum off-heap memory used by written files in the file cache mode.

MemorySize

No

64 M

Takes effect only when sink.file-cached.enable is set to true.

Note

Supported only in VVR 8.0.10 and later.

sink.file-cached.memory.segment-size

Buffer size used for writing files in the file cache mode.

MemorySize

No

128 KB

Takes effect only when sink.file-cached.enable is set to true.

Note

Supported only in VVR 8.0.10 and later.

sink.file-cached.flush.always

Specifies whether to use caching when writing files in the file cache mode.

Boolean

No

true

Takes effect only when sink.file-cached.enable is set to true.

Note

Supported only in VVR 8.0.10 and later.

sink.file-cached.write.max-retries

Number of retries for data uploads in the file cache mode.

Integer

No

3

Takes effect only when sink.file-cached.enable is set to true.

Note

Supported only in VVR 8.0.10 and later.

upsert.writer.max-retries

Number of retries after Upsert Writer fails to write to a bucket.

Integer

No

3

Note

Supported only in VVR 8.0.10 and later.

upsert.writer.buffer-size

Cache size of data for a single Upsert Writer in Flink.

MemorySize

No

64 m

  • When the total buffer size of all buckets reaches the preset threshold, the system automatically triggers a flush and updates the data on the server.

  • An upsert writer writes to multiple buckets at the same time. Increase this value to improve write efficiency.

  • Writing to many partitions can cause OOM errors. In this case, decrease this value.

Note

Supported only in VVR 8.0.10 and later.

upsert.writer.bucket.buffer-size

Cache size of data for a single bucket in Flink.

MemorySize

No

1 m

Decrease this value when cluster memory resources are insufficient.

Note

Supported only in VVR 8.0.10 and later.

upsert.write.bucket.num

Number of buckets for writing to the table.

Integer

Yes

None

Must be the same as the write.bucket.num property value of the Delta Table you write to.

Note

Supported only in VVR 8.0.10 and later.

upsert.write.slot-num

Number of tunnel slots used by a single session.

Integer

No

1

Note

Supported only in VVR 8.0.10 and later.

upsert.commit.max-retries

Number of retries for Upsert Session Commit.

Integer

No

3

Note

Supported only in VVR 8.0.10 and later.

upsert.commit.thread-num

Parallelism for Upsert Session Commit.

Integer

No

16

Do not set this value too high. More concurrent commits consume more resources and can cause performance problems or excessive resource consumption.

Note

Supported only in VVR 8.0.10 and later.

upsert.commit.timeout

Timeout for Upsert Session Commit. Unit: seconds (s).

Integer

No

600

Note

Supported only in VVR 8.0.10 and later.

upsert.flush.concurrent

Maximum number of buckets that can be written concurrently in a single partition.

Integer

No

2

Each bucket flush occupies one tunnel slot.

Note

Supported only in VVR 8.0.10 and later.

insert.commit.thread-num

Parallelism for Commit Session.

Integer

No

16

Note

Supported only in VVR 8.0.10 and later.

insert.arrow-writer.enable

Specifies whether to use Arrow format.

Boolean

No

false

Valid values:

  • true: use Arrow format.

  • false: do not use Arrow format.

Note

Supported only in VVR 8.0.10 and later.

insert.arrow-writer.batch-size

Maximum number of rows in an Arrow batch.

Integer

No

512

Note

Supported only in VVR 8.0.10 and later.

insert.arrow-writer.flush-interval

Writer flush interval. Unit: milliseconds (ms).

Integer

No

100000

Note

Supported only in VVR 8.0.10 and later.

insert.writer.buffer-size

Buffer size of Buffered Writer.

MemorySize

No

64 M

Note

Supported only in VVR 8.0.10 and later.

upsert.partial-column.enable

Specifies whether to update only some columns.

Boolean

No

false

Takes effect only when the sink table is a Delta Table. For details, see PK table - partial column update.

Valid values:

  • true: update only the specified columns.

  • false: update all columns.

Data is written in the following ways, depending on whether the sink table contains data with the same primary key:

  • If the sink table contains data with the same primary key, the row is updated by primary key with the values of the specified columns that are not null.

  • If the sink table does not contain data with the same primary key, a row is inserted with the values of the specified columns. Columns other than the specified columns are inserted with null.

Note

Supported only in VVR 8.0.11 and later.

Dimension table only

A MaxCompute dimension table loads all data from the specified partition when the job starts. The partition parameter supports functions such as max_pt(). When the cache expires and is reloaded, the partition parameter is parsed again to load the latest partition. With max_two_pt(), the dimension table can load two partitions. In other cases, only a single partition can be specified.

Parameter

Description

Data type

Required

Default value

Remarks

cache

Cache policy.

String

Yes

None

Currently, MaxCompute dimension tables support only the ALL policy, which must be declared explicitly. This policy suits scenarios where the remote table contains little data and MISS KEY cases (rows in the source table that cannot be joined with the dimension table by the ON condition) are very common.

ALL: caches all data in the dimension table. Before the job runs, the system loads all dimension table data into the cache. All subsequent dimension table queries are served from the cache. If data is not found in the cache, the key does not exist, and the full cache is reloaded when the cache expires.

Note
  • The system loads dimension table data asynchronously. When you use CACHE ALL, increase the memory of the dimension table JOIN node by at least 4 times the remote table data size. The exact value depends on the MaxCompute storage compression algorithm.

  • If the MaxCompute dimension table is large, use the SHUFFLE_HASH hint to distribute dimension table data evenly across subtasks. For details, see How do I use the SHUFFLE_HASH hint for a dimension table?

  • When a very large MaxCompute dimension table causes frequent JVM garbage collection and job failures, and increasing the memory of the dimension table JOIN node does not help, use a KV dimension table that supports the LRU cache policy instead, such as an ApsaraDB for HBase dimension table.

cacheSize

Maximum number of rows to cache.

Long

No

100000

If the dimension table data size exceeds cacheSize, the following error occurs: Row count of table <table-name> partition <partition-name> exceeds maxRowCount limit.

Important

A large dimension table consumes a lot of JVM heap memory and slows down job startup and dimension table updates. Verify that so much data needs to be cached. If it does, increase this parameter manually.

cacheTTLMs

Cache timeout, which is the interval between cache updates.

Long

No

Long.MAX_VALUE (never updated)

Unit: milliseconds.

cacheReloadTimeBlackList

Update time blacklist. The cache is not updated during the periods specified by this parameter.

String

No

None

This parameter prevents cache updates during critical periods, such as campaign traffic peaks, which can make the job unstable. For details about the format, see How do I configure the CacheReloadTimeBlackList parameter?

maxLoadRetries

Maximum number of attempts for cache updates, including the initial data load at job startup. After this number of attempts, the job fails.

Integer

No

10

None.

Data type mappings

For the data types supported by MaxCompute, see 2.0 data types.

MaxCompute type

Flink type

BOOLEAN

BOOLEAN

TINYINT

TINYINT

SMALLINT

SMALLINT

INT

INTEGER

BIGINT

BIGINT

FLOAT

FLOAT

DOUBLE

DOUBLE

DECIMAL(precision, scale)

DECIMAL(precision, scale)

CHAR(n)

CHAR(n)

VARCHAR(n)

VARCHAR(n)

STRING

STRING

BINARY

BYTES

DATE

DATE

DATETIME

TIMESTAMP(3)

TIMESTAMP

TIMESTAMP(9)

TIMESTAMP_NTZ

TIMESTAMP(9)

ARRAY

ARRAY

MAP

MAP

STRUCT

ROW

JSON

STRING

VECTOR

VECTOR

Important

If a MaxCompute table contains both nested complex type fields (ARRAY, MAP, or STRUCT) and JSON type fields, specify tblproperties('columnar.nested.type'='true') when you create the MaxCompute table so that Flink can read and write the table correctly.

Examples

SQL

Source table example

Read all data

By default, the source table operates in full mode and reads the partition specified by the partition parameter.

CREATE TEMPORARY TABLE odps_source (
  cid VARCHAR,
  rt DOUBLE
) WITH (
  'connector' = 'odps',
  'endpoint' = '<yourEndpointName>',
  'project' = '<yourProjectName>',
  'tableName' = '<yourTableName>',
  'accessId' = '${secret_values.ak_id}',
  'accessKey' = '${secret_values.ak_secret}',
  'partition' = 'ds=201809*'
);

CREATE TEMPORARY TABLE blackhole_sink (
  cid VARCHAR,
  invoke_count BIGINT
) WITH (
  'connector' = 'blackhole'
);

INSERT INTO blackhole_sink
SELECT
   cid,
   COUNT(*) AS invoke_count
FROM odps_source GROUP BY cid;
Read incremental data

Starts incremental reads from the partition specified by startPartition.

CREATE TEMPORARY TABLE odps_source (
  cid VARCHAR,
  rt DOUBLE
) WITH (
  'connector' = 'odps',
  'endpoint' = '<yourEndpointName>',
  'project' = '<yourProjectName>',
  'tableName' = '<yourTableName>',
  'accessId' = '${secret_values.ak_id}',
  'accessKey' = '${secret_values.ak_secret}',
  'startPartition' = 'yyyy=2018,MM=09,dd=05' -- Start reading from the partition that corresponds to 20180905.
);

CREATE TEMPORARY TABLE blackhole_sink (
  cid VARCHAR,
  invoke_count BIGINT
) WITH (
  'connector' = 'blackhole'
);

INSERT INTO blackhole_sink
SELECT cid, COUNT(*) AS invoke_count
FROM odps_source GROUP BY cid;

Use KMS to host AccessKey pairs

The following example uses a sink table. Source tables and dimension tables are configured in the same way. Set both accessId and accessKey to secret://kms.<secret-name>.<field-name> and configure the KMS parameters. We recommend that you use a generic secret whose SecretData is {"AccessKeyId":"...","AccessKeySecret":"..."}. For preparations such as creating a secret and authorizing a RAM role, see KMS credential management integration.

CREATE TEMPORARY TABLE odps_sink (
  id INT,
  user_name VARCHAR,
  content VARCHAR
) WITH (
  'connector' = 'odps',
  'endpoint' = '<yourEndpoint>',
  'project' = '<yourProjectName>',
  'tableName' = '<yourTableName>',
  'accessId'  = 'secret://kms.my-odps-ak.AccessKeyId',
  'accessKey' = 'secret://kms.my-odps-ak.AccessKeySecret',
  'kms.endpoint' = 'kms.cn-beijing.aliyuncs.com',
  'kms.akless.assume-role.role-name' = 'FlinkRoleForKMSRead'
);

Sink table example

Write to a fixed partition

Writes to the fixed partition specified by partition.

CREATE TEMPORARY TABLE datagen_source (
  id INT,
  len INT,
  content VARCHAR
) WITH (
  'connector' = 'datagen'
);

CREATE TEMPORARY TABLE odps_sink (
  id INT,
  len INT,
  content VARCHAR
) WITH (
  'connector' = 'odps',
  'endpoint' = '<yourEndpoint>',
  'project' = '<yourProjectName>',
  'tableName' = '<yourTableName>',
  'accessId' = '${secret_values.ak_id}',
  'accessKey' = '${secret_values.ak_secret}',
  'partition' = 'ds=20180905' -- Write to the fixed partition ds=20180905.
);

INSERT INTO odps_sink
SELECT
  id, len, content
FROM datagen_source;
Write to dynamic partitions

Specifies the partition based on the table partition field partition.

CREATE TEMPORARY TABLE datagen_source (
  id INT,
  len INT,
  content VARCHAR,
  c TIMESTAMP
) WITH (
  'connector' = 'datagen'
);

CREATE TEMPORARY TABLE odps_sink (
  id  INT,
  len INT,
  content VARCHAR,
  ds VARCHAR -- Dynamic partition columns must be declared explicitly.
) WITH (
  'connector' = 'odps',
  'endpoint' = '<yourEndpoint>',
  'project' = '<yourProjectName>',
  'tableName' = '<yourTableName>',
  'accessId' = '${secret_values.ak_id}',
  'accessKey' = '${secret_values.ak_secret}',
  'partition' = 'ds' -- Leave the value empty to route data to partitions based on the ds field.
);

INSERT INTO odps_sink
SELECT
   id,
   len,
   content,
   DATE_FORMAT(c, 'yyMMdd') as ds
FROM datagen_source;

Dimension table example

One-to-one dimension table

A one-to-one dimension table requires a primary key.

CREATE TEMPORARY TABLE datagen_source (
  k INT,
  v VARCHAR
) WITH (
  'connector' = 'datagen'
);

CREATE TEMPORARY TABLE odps_dim (
  k INT,
  v VARCHAR,
  PRIMARY KEY (k) NOT ENFORCED  -- A one-to-one dimension table requires a primary key.
) WITH (
  'connector' = 'odps',
  'endpoint' = '<yourEndpoint>',
  'project' = '<yourProjectName>',
  'tableName' = '<yourTableName>',
  'accessId' = '${secret_values.ak_id}',
  'accessKey' = '${secret_values.ak_secret}',
  'partition' = 'ds=20180905',
  'cache' = 'ALL'
);

CREATE TEMPORARY TABLE blackhole_sink (
  k VARCHAR,
  v1 VARCHAR,
  v2 VARCHAR
) WITH (
  'connector' = 'blackhole'
);

INSERT INTO blackhole_sink
SELECT k, s.v, d.v
FROM datagen_source AS s
INNER JOIN odps_dim FOR SYSTEM_TIME AS OF PROCTIME() AS d ON s.k = d.k;
One-to-many dimension table

A one-to-many dimension table does not require a primary key.

CREATE TEMPORARY TABLE datagen_source (
  k INT,
  v VARCHAR
) WITH (
  'connector' = 'datagen'
);

CREATE TEMPORARY TABLE odps_dim (
  k INT,
  v VARCHAR
  -- A one-to-many dimension table does not require a primary key.
) WITH (
  'connector' = 'odps',
  'endpoint' = '<yourEndpoint>',
  'project' = '<yourProjectName>',
  'tableName' = '<yourTableName>',
  'accessId' = '${secret_values.ak_id}',
  'accessKey' = '${secret_values.ak_secret}',
  'partition' = 'ds=20180905',
  'cache' = 'ALL'
);

CREATE TEMPORARY TABLE blackhole_sink (
  k VARCHAR,
  v1 VARCHAR,
  v2 VARCHAR
) WITH (
  'connector' = 'blackhole'
);

INSERT INTO blackhole_sink
SELECT k, s.v, d.v
FROM datagen_source AS s
INNER JOIN odps_dim FOR SYSTEM_TIME AS OF PROCTIME() AS d ON s.k = d.k;

DataStream

Important
  • To read and write data with DataStream, use the corresponding DataStream connector to connect to Flink. For details about how to configure the DataStream connector, see How to use DataStream connectors.

  • To protect intellectual property, starting from VVR 6.0.6, this connector can run a job locally for up to 30 minutes in a single debugging session. After 30 minutes, the job exits with an error. For details about running and debugging jobs that contain the MaxCompute connector locally, see Run and debug jobs that contain connectors locally.

  • Reading Delta Tables is not supported. A Delta Table is created with primary key and transactional=true. For details, see Basic concepts.

When you use the MaxCompute connector in DataStream, declare the MaxCompute table in SQL and connect the MaxCompute table with the data stream by converting between Table and DataStream.

Connect to the source table

StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
tEnv.executeSql(String.join(
    "\n",
    "CREATE TEMPORARY TABLE IF NOT EXISTS odps_source (",
    "  cid VARCHAR,",
    "  rt DOUBLE",
    ") WITH (",
    "  'connector' = 'odps',",
    "  'endpoint' = '<yourEndpointName>',",
    "  'project' = '<yourProjectName>',",
    "  'tableName' = '<yourTableName>',",
    "  'accessId' = '<yourAccessId>',",
    "  'accessKey' = '<yourAccessPassword>',",
    "  'partition' = 'ds=201809*'",
    ")");
DataStream<Row> source = tEnv.toDataStream(tEnv.from("odps_source"));
source.print();
env.execute("odps source"); 

Connect to the sink table

StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
tEnv.executeSql(String.join(
    "\n",
    "CREATE TEMPORARY TABLE IF NOT EXISTS odps_sink (",
    "  cid VARCHAR,",
    "  rt DOUBLE",
    ") WITH (",
    "  'connector' = 'odps',",
    "  'endpoint' = '<yourEndpointName>',",
    "  'project' = '<yourProjectName>',",
    "  'tableName' = '<yourTableName>',",
    "  'accessId' = '<yourAccessId>',",
    "  'accessKey' = '<yourAccessPassword>',",
    "  'partition' = 'ds=20180905'",
    ")");
DataStream<Row> data = env.fromElements(
    Row.of("id0", 3.),
    Row.of("id1", 4.));
tEnv.fromDataStream(data).insertInto("odps_sink").execute();

XML

The Maven dependency of the MaxCompute connector contains all classes required to build full source tables, incremental source tables, sink tables, and dimension tables. The MaxCompute DataStream connector is available in the Maven central repository.

<dependency>
    <groupId>com.alibaba.ververica</groupId>
    <artifactId>ververica-connector-odps</artifactId>
    <version>${vvr-version}</version>
</dependency>

FAQ