This document explains how to use the aggregation merge engine.
Aggregation merge engine
-
Merge Policy
The engine groups rows by the same primary key and applies a specified aggregation function to each non-primary key field.
-
Configuration
To enable this feature, set the table property
'table.merge-engine' = 'aggregation'when you create a table. -
Usage
-
When you create a table in the console, select the merge policy and use the advanced configuration
'fields.<field_name>.agg' = '<function_name>'to specify an aggregation function for each non-primary key field. -
For aggregation functions that require additional parameters, such as a custom delimiter for
listagg, use the following format:'fields.<field_name>.agg' = '<function_name>', 'fields.<field_name>.<function_name>.<parameter_name>' = '<parameter_value>'If you do not specify an aggregation function for a field, the system uses
last_value_ignore_nullsas the default aggregation behavior.
-
-
Use Cases
-
Calculating cumulative totals and statistical metrics
-
Maintaining counters and measures
-
Tracking changes in maximum or minimum values
-
Building real-time dashboards and analytics
-
-
Limitations
-
Retraction semantics are not supported. The engine uses one-way aggregation logic and cannot reverse an aggregation. For example, it cannot subtract a deleted value from a
sumresult or undo amaxoperation to restore the second-largest value. -
Flink SQL does not support UPDATE or DELETE statements on this table. Delete operations can only be triggered by
-Drecords in the upstream changelog. -
Delete behavior is controlled by
table.delete.behavior, which defaults to silently ignoring deletes. For values and detailed behavior, see Delete Behavior.
-
Delete Behavior
The table.delete.behavior table property controls how delete operations are handled.
'table.delete.behavior' = 'ignore' -- Default value. Silently ignores delete operations.
'table.delete.behavior' = 'disable' -- Rejects delete operations and returns an error.
'table.delete.behavior' = 'allow' -- Executes delete operations according to the write mode.
|
Value |
Description |
|
|
Default. Delete operations are silently ignored. No error is returned, and the existing record remains unchanged. |
|
|
Delete operations are rejected and an error is returned. |
|
|
Delete operations are executed. The actual behavior depends on the write mode. |
When table.delete.behavior is set to allow:
|
Write mode |
Delete behavior |
|
Full-row update (default, all columns written) |
The entire record is deleted. All aggregated values for the primary key are permanently lost. |
|
Partial-column update (only some columns written) |
Only the target columns (excluding primary key columns) are set to |
Withallow, the changelog read by downstream consumers contains-Drecords. Withignoreordisable, it does not.
Example
CREATE TABLE product_stats (
product_id BIGINT,
price DOUBLE,
sales BIGINT,
last_update_time TIMESTAMP(3),
PRIMARY KEY (product_id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.price.agg' = 'max',
'fields.sales.agg' = 'sum'
-- No aggregation function is specified for last_update_time, so last_value_ignore_nulls is used by default.
);
-- Insert data. Records with the same primary key are automatically aggregated.
INSERT INTO product_stats VALUES
(1, 23.0, 15, TIMESTAMP '2024-01-01 10:00:00'),
(1, 30.2, 20, TIMESTAMP '2024-01-01 11:00:00');
SELECT * FROM product_stats WHERE product_id = 1;
-- Output:
-- +------------+-------+-------+---------------------+
-- | product_id | price | sales | last_update_time |
-- +------------+-------+-------+---------------------+
-- | 1 | 30.2 | 35 | 2024-01-01 11:00:00 |
-- +------------+-------+-------+---------------------+
-- price: 30.2 (the maximum of 23.0 and 30.2)
-- sales: 35 (the sum of 15 and 20)
-- last_update_time: 2024-01-01 11:00:00 (the last non-null value)
Supported aggregation functions
sum
Calculates the sum of values across multiple rows.
-
Supported Types:
TINYINT,SMALLINT,INT,BIGINT,FLOAT,DOUBLE,DECIMAL. -
Null Handling: Ignores null values.
CREATE TABLE test_sum (
id BIGINT,
amount DECIMAL(10, 2),
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.amount.agg' = 'sum'
);
INSERT INTO test_sum VALUES (1, 100.50), (1, 200.75);
SELECT * FROM test_sum WHERE id = 1;
-- Output:
-- +----+---------+
-- | id | amount |
-- +----+---------+
-- | 1 | 301.25 |
-- +----+---------+
product
Calculates the product of values across multiple rows.
-
Supported Types:
TINYINT,SMALLINT,INT,BIGINT,FLOAT,DOUBLE,DECIMAL. -
Null Handling: Ignores null values.
CREATE TABLE test_product (
id BIGINT,
discount_factor DOUBLE,
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.discount_factor.agg' = 'product'
);
INSERT INTO test_product VALUES (1, 0.9), (1, 0.8);
SELECT * FROM test_product WHERE id = 1;
-- Output:
-- +----+-----------------------+
-- | id | discount_factor |
-- +----+-----------------------+
-- | 1 | 0.7200000000000001 |
-- +----+-----------------------+
-- Note: Due to IEEE 754 double-precision floating-point arithmetic, the result is 0.7200000000000001 instead of 0.72.
-- For precise calculations, we recommend using the DECIMAL data type instead of DOUBLE.
max
Retains the maximum value.
-
Supported Types:
CHAR,STRING,TINYINT,SMALLINT,INT,BIGINT,FLOAT,DOUBLE,DECIMAL,DATE,TIME,TIMESTAMP,TIMESTAMP_LTZ. -
Null Handling: Ignores null values.
CREATE TABLE test_max (
id BIGINT,
temperature DOUBLE,
reading_time TIMESTAMP(3),
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.temperature.agg' = 'max',
'fields.reading_time.agg' = 'max'
);
INSERT INTO test_max VALUES
(1, 25.5, TIMESTAMP '2024-01-01 10:00:00'),
(1, 28.3, TIMESTAMP '2024-01-01 11:00:00');
SELECT * FROM test_max WHERE id = 1;
-- Output:
-- +----+-------------+---------------------+
-- | id | temperature | reading_time |
-- +----+-------------+---------------------+
-- | 1 | 28.3 | 2024-01-01 11:00:00 |
-- +----+-------------+---------------------+
min
Retains the minimum value.
-
Supported Types:
CHAR,STRING,TINYINT,SMALLINT,INT,BIGINT,FLOAT,DOUBLE,DECIMAL,DATE,TIME,TIMESTAMP,TIMESTAMP_LTZ. -
Null Handling: Ignores null values.
CREATE TABLE test_min (
id BIGINT,
lowest_price DECIMAL(10, 2),
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.lowest_price.agg' = 'min'
);
INSERT INTO test_min VALUES (1, 99.99), (1, 79.99), (1, 89.99);
SELECT * FROM test_min WHERE id = 1;
-- Output:
-- +----+--------------+
-- | id | lowest_price |
-- +----+--------------+
-- | 1 | 79.99 |
-- +----+--------------+
last_value
Overwrites the previous value with the most recent value.
-
Supported Types: All data types.
-
Null Handling: A null value overwrites the previous value.
CREATE TABLE test_last_value (
id BIGINT,
status STRING,
last_login TIMESTAMP(3),
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.status.agg' = 'last_value',
'fields.last_login.agg' = 'last_value'
);
INSERT INTO test_last_value VALUES (1, 'online', TIMESTAMP '2024-01-01 10:00:00');
INSERT INTO test_last_value VALUES (1, 'offline', TIMESTAMP '2024-01-01 11:00:00');
INSERT INTO test_last_value VALUES (1, CAST(NULL AS STRING), TIMESTAMP '2024-01-01 12:00:00');
-- A null value overwrites the previous 'offline' value.
SELECT * FROM test_last_value WHERE id = 1;
-- Output:
-- +----+--------+---------------------+
-- | id | status | last_login |
-- +----+--------+---------------------+
-- | 1 | null | 2024-01-01 12:00:00 |
-- +----+--------+---------------------+
last_value_ignore_nulls
Replaces the previous value with the most recent non-null value. This is the default aggregation behavior when no aggregation function is specified.
-
Supported Types: All data types.
-
Null Handling: Ignores null values and retains the previous value.
CREATE TABLE test_last_value_ignore_nulls (
id BIGINT,
email STRING,
phone STRING,
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.email.agg' = 'last_value_ignore_nulls',
'fields.phone.agg' = 'last_value_ignore_nulls'
);
INSERT INTO test_last_value_ignore_nulls VALUES (1, 'user@example.com', '123-456');
INSERT INTO test_last_value_ignore_nulls VALUES (1, CAST(NULL AS STRING), '789-012');
-- The null value for email is ignored, and the previous value is retained.
INSERT INTO test_last_value_ignore_nulls VALUES (1, 'new@example.com', CAST(NULL AS STRING));
-- The null value for phone is ignored, and the previous value is retained.
SELECT * FROM test_last_value_ignore_nulls WHERE id = 1;
-- Output:
-- +----+-----------------+---------+
-- | id | email | phone |
-- +----+-----------------+---------+
-- | 1 | new@example.com | 789-012 |
-- +----+-----------------+---------+
last_n
Unlike last_value, which retains only the latest single value, last_n appends newly written data to an array and retains only the most recent N elements. It is suitable for maintaining the most recent N records directly in a table, such as the last N operations of a user or the last N reports of a device, without developing additional window or filtering logic in your job.
-
Supported Types: ARRAY types with any element type.
-
Null Handling: Null values do not change the existing content of the field.
-
Deduplication: Supported in 1.0-ali-2.0 and later. Set
fields.<column_name>.last_n.distincttotrueto remove duplicates before retaining the last N distinct elements. Elements are ordered by their last occurrence, and null elements count as one distinct value. The default isfalse. -
Note: You must use
fields.<column_name>.last_n.sizeto specify the number of elements to retain. This parameter is required and must be a positive integer. If this parameter is missing, table creation fails. Elements are retained in the order in which writes reach the service. Each update rewrites the entire stored array.
CREATE TABLE test_last_n (
id BIGINT,
recent_events ARRAY<STRING>,
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.recent_events.agg' = 'last_n',
'fields.recent_events.last_n.size' = '3'
);
INSERT INTO test_last_n VALUES (1, ARRAY['search']);
INSERT INTO test_last_n VALUES (1, ARRAY['view']);
INSERT INTO test_last_n VALUES (1, ARRAY['add_to_cart']);
INSERT INTO test_last_n VALUES (1, ARRAY['pay']);
SELECT * FROM test_last_n WHERE id = 1;
-- Output:
-- +----+--------------------------+
-- | id | recent_events |
-- +----+--------------------------+
-- | 1 | [view, add_to_cart, pay] |
-- +----+--------------------------+
first_value
Retains the first value of a field and ignores all subsequent values.
-
Supported Types: All data types.
-
Null Handling: If the first value is null, the null value is retained.
CREATE TABLE test_first_value (
id BIGINT,
first_purchase_date DATE,
first_product STRING,
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.first_purchase_date.agg' = 'first_value',
'fields.first_product.agg' = 'first_value'
);
INSERT INTO test_first_value VALUES (1, '2024-01-01', 'ProductA'), (1, '2024-02-01', 'ProductB');
-- The second record is ignored, and the first value is retained.
SELECT * FROM test_first_value WHERE id = 1;
-- Output:
-- +----+---------------------+---------------+
-- | id | first_purchase_date | first_product |
-- +----+---------------------+---------------+
-- | 1 | 2024-01-01 | ProductA |
-- +----+---------------------+---------------+
listagg
Concatenates multiple string values into a single string, separated by a delimiter.
-
Supported Types:
STRING,CHAR. -
Null Handling: Skips null values.
-
Delimiter: The default delimiter is a comma (
,), but you can specify a custom delimiter as a parameter.
CREATE TABLE test_listagg (
id BIGINT,
tags1 STRING,
tags2 STRING,
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.tags1.agg' = 'listagg',
'fields.tags2.agg' = 'listagg',
'fields.tags2.listagg.delimiter' = ';' -- Specify a custom delimiter.
);
INSERT INTO test_listagg VALUES (1, 'developer', 'developer'), (1, 'java', 'java'), (1, 'flink', 'flink');
SELECT * FROM test_listagg WHERE id = 1;
-- Output:
-- +----+----------------------+----------------------+
-- | id | tags1 | tags2 |
-- +----+----------------------+----------------------+
-- | 1 | developer,java,flink | developer;java;flink |
-- +----+----------------------+----------------------+
string_agg
An alias for listagg. It concatenates multiple string values into a single string, separated by a delimiter.
-
Supported Types:
STRING,CHAR. -
Null Handling: Skips null values.
-
Delimiter: The default delimiter is a comma (
,), but you can specify a custom delimiter as a parameter.
CREATE TABLE test_string_agg (
id BIGINT,
tags STRING,
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.tags.agg' = 'string_agg',
'fields.tags.string_agg.delimiter' = ';' -- Specify a custom delimiter.
);
INSERT INTO test_string_agg VALUES (1, 'developer'), (1, 'java'), (1, 'flink');
SELECT * FROM test_string_agg WHERE id = 1;
-- Output:
-- +----+----------------------+
-- | id | tags |
-- +----+----------------------+
-- | 1 | developer;java;flink |
-- +----+----------------------+
rbm32
Performs union aggregation on serialized 32-bit RoaringBitmap values.
-
Supported Types:
BYTES. -
Null Handling: Ignores null values.
-
Note: Bitmap values use the standard 32-bit serialization format of the RoaringBitmap library. In Flink SQL you can call functions such as
rb_buildandrb_build_aggto build bitmaps directly, with no client-side serialization required. For more information, see SQL Functions.
CREATE TABLE user_visits (
user_id BIGINT,
visit_bitmap BYTES,
PRIMARY KEY (user_id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.visit_bitmap.agg' = 'rbm32'
);
-- Option 1: Build bitmaps in Flink SQL with rb_build.
INSERT INTO user_visits SELECT 1, rb_build(ARRAY[1, 2]);
INSERT INTO user_visits SELECT 1, rb_build(ARRAY[2, 3]);
-- Option 2: Insert bitmaps serialized on the client (hexadecimal literals).
-- Bitmap {1,2}
INSERT INTO user_visits VALUES (1, x'3A30000001000000000001001000000001000200');
-- Bitmap {2,3}
INSERT INTO user_visits VALUES (1, x'3A30000001000000000001001000000002000300');
SELECT user_id, rb_cardinality(visit_bitmap) AS uv FROM user_visits WHERE user_id = 1;
-- Result: visit_bitmap contains the union {1,2,3}, and uv is 3.
rbm64
Performs union aggregation on serialized 64-bit RoaringBitmap values.
-
Supported Types:
BYTES. -
Null Handling: Ignores null values.
-
Note: Roaring64Bitmap values must be serialized on the client in the 64-bit format of the RoaringBitmap library before being ingested. All RoaringBitmap SQL functions are based on the 32-bit format and do not apply to
rbm64.
CREATE TABLE session_interactions (
session_id BIGINT,
interaction_bitmap BYTES,
PRIMARY KEY (session_id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.interaction_bitmap.agg' = 'rbm64'
);
-- Insert serialized Roaring64Bitmap values.
-- Result: interaction_bitmap contains the union of all inserted bitmaps.
bool_and
Performs logical AND aggregation on boolean values. It returns true only if all values are true.
-
Supported Types:
BOOLEAN. -
Null Handling: Ignores null values.
CREATE TABLE test_bool_and (
id BIGINT,
has_all_permissions BOOLEAN,
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.has_all_permissions.agg' = 'bool_and'
);
INSERT INTO test_bool_and VALUES (1, true), (1, true), (1, false);
SELECT * FROM test_bool_and WHERE id = 1;
-- Output:
-- +----+---------------------+
-- | id | has_all_permissions |
-- +----+---------------------+
-- | 1 | false |
-- +----+---------------------+
bool_or
Performs logical OR aggregation on boolean values. It returns true if at least one value is true.
-
Supported Types:
BOOLEAN. -
Null Handling: Ignores null values.
CREATE TABLE test_bool_or (
id BIGINT,
has_any_alert BOOLEAN,
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.has_any_alert.agg' = 'bool_or'
);
INSERT INTO test_bool_or VALUES (1, false), (1, false), (1, true);
SELECT * FROM test_bool_or WHERE id = 1;
-- Output:
-- +----+---------------+
-- | id | has_any_alert |
-- +----+---------------+
-- | 1 | true |
-- +----+---------------+
merge_map
Merges map values by combining key-value pairs. For duplicate keys, the latest value wins. Supported in 1.0-ali-1.3 and later.
-
Supported Types:
MAP<K, V>. -
Null Handling: Null keys are not allowed. Null values are allowed.
-
Note: The built-in Fluss catalog in Flink does not support this function yet. Before you use merge_map, you must create a custom catalog that loads Fluss catalog JAR 1.0-ali-1.3 or later.
CREATE TABLE test_merge_map (
id BIGINT,
attributes MAP<INT, STRING>,
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.attributes.agg' = 'merge_map'
);
INSERT INTO test_merge_map VALUES
(1, MAP[1, 'a', 2, 'b']),
(1, MAP[2, 'c', 3, NULL]);
SELECT * FROM test_merge_map WHERE id = 1;
-- Output:
-- +----+--------------------------+
-- | id | attributes |
-- +----+--------------------------+
-- | 1 | {1=a, 2=c, 3=NULL} |
-- +----+--------------------------+
count
Counts non-null input values for each primary key. Each non-null input contributes one, regardless of its numeric value. Supported in 1.0-ali-2.0 and later.
-
Supported Types: BIGINT, for both input and stored count.
-
Null Handling: Null inputs do not increment the count. A null input initializes a NULL count to 0 and leaves an existing count unchanged.
-
Note: Only updates targeting this column contribute to the count. To count every row, provide a non-null value for this column in every row. To accumulate counts already computed upstream, use sum instead. When
'table.delete.behavior' = 'allow', a partial delete targeting the count column clears it to NULL rather than decrementing it.
CREATE TABLE event_counts (
id INT,
cnt BIGINT,
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.cnt.agg' = 'count'
);
INSERT INTO event_counts VALUES (1, 100), (1, 0), (1, NULL);
-- The stored cnt for id = 1 is 2.
collect
Collects array elements from multiple writes into a single array. Supported in 1.0-ali-2.0 and later.
-
Supported Types:
ARRAY<T>. -
Null Handling: Null elements are retained. Null inputs are ignored.
-
Deduplication: Set
fields.<column_name>.collect.distincttotrueto remove duplicates, retaining the first occurrence of each element. The default isfalse. Elements follow the order in which writes reach the server. -
Note: The collected array has no size limit, and every update rewrites the whole array. As the array grows, memory usage, write costs, and changelog volume increase. Use last_n when only a bounded number of recent elements is needed.
CREATE TABLE test_collect (
id BIGINT,
tags ARRAY<INT>,
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.tags.agg' = 'collect',
'fields.tags.collect.distinct' = 'true'
);
INSERT INTO test_collect VALUES
(1, ARRAY[1, 2, 2]),
(1, ARRAY[2, 3, NULL]);
SELECT * FROM test_collect;
-- Output: (1, [1, 2, 3, NULL])
hll_sketch
Aggregates serialized Apache DataSketches HLL sketches by union for approximate cardinality (distinct count) estimation. Supported in 1.0-ali-2.0 and later.
-
Supported Types:
BYTES. -
Null Handling: Null values are ignored.
-
Note: The input must be serialized HLL sketch bytes, not raw values. The stored value is a serialized sketch, not a distinct count. After reading the sketch bytes, use HllSketch.heapify(bytes).getEstimate() from the Apache DataSketches library to obtain the approximate distinct count.
CREATE TABLE daily_user_metrics (
metric_day STRING,
user_hll BYTES,
PRIMARY KEY (metric_day) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.user_hll.agg' = 'hll_sketch'
);
kll_double_sketch
Aggregates serialized Apache DataSketches KLL doubles sketches by merge for approximate percentile or quantile estimation, such as latency or transaction amount distributions. Supported in 1.0-ali-2.0 and later.
-
Supported Types:
BYTES. -
Null Handling: Null values are ignored.
-
Note: The input must be serialized KLL doubles sketch bytes. The engine does not build sketches from raw DOUBLE values. After reading, heapify the bytes as a KllDoublesSketch to query quantiles.
CREATE TABLE daily_latency_metrics (
metric_day STRING,
latency_kll BYTES,
PRIMARY KEY (metric_day) NOT ENFORCED
) WITH (
'table.merge-engine' = 'aggregation',
'fields.latency_kll.agg' = 'kll_double_sketch'
);