Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions docs/docs/append-table/streaming.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,61 @@ INSERT INTO my_table SELECT product_id, price, sales, dt FROM source_table;
Short checkpoint intervals can produce many small data files. Choose a compaction approach together with your
checkpoint interval and write parallelism.

### Materialize Changelog Records as Events

Some pipelines consume changelog payloads as independent events. Enable `sink.changelog-as-append` to store each
received `INSERT`, `UPDATE_BEFORE`, `UPDATE_AFTER` and `DELETE` payload as an `INSERT` in a non-keyed file-store table.
Duplicate payloads remain separate records. For example, `+I(value=0), -U(value=0), +U(value=1000)` produces three
append events, including two records with `value=0`. A delete becomes a recorded event; it does not remove an earlier
event. This option is disabled by default and applies only to the Flink SQL table sink.

Declare two nullable physical fields for the generated values: a `STRING` (or `VARCHAR` of at least 13 characters)
for the original row kind and a `BIGINT` for conversion-time epoch milliseconds. Configure their names and supply
typed nulls in the insert. The sink fills these fields, overwriting any supplied values:

```sql
CREATE TABLE change_events (
entity_id STRING,
total BIGINT,
original_kind STRING,
emitted_ms BIGINT
) WITH (
'bucket' = '-1',
'sink.changelog-as-append' = 'true',
'sink.changelog-as-append.kind-field' = 'original_kind',
'sink.changelog-as-append.time-field' = 'emitted_ms'
);

INSERT INTO change_events
SELECT entity_id, SUM(amount), CAST(NULL AS STRING), CAST(NULL AS BIGINT)
FROM source_updates
GROUP BY entity_id;
```

Readers see an insert-only event relation. `original_kind` contains `INSERT`, `UPDATE_BEFORE`, `UPDATE_AFTER` or
`DELETE` as ordinary data; it does not control the sign of a downstream aggregation. Consumers can derive a timestamp
with `TO_TIMESTAMP_LTZ(emitted_ms, 3)`.

The sink requests before-images and full delete payloads where the planner and source can provide them. It preserves
records actually delivered to the sink, not necessarily every original source event: upstream operators can combine
changes, and missing payloads or history cannot be reconstructed. Retaining before-images and equal duplicates can
increase storage volume compared with keyed state.

The mode rejects primary-key tables, format tables, delegated lake-stream writes, `INSERT OVERWRITE`,
`ignore-delete=true`, `ignore-update-before=true`, `rowkind.field`, and `sink.key-only-deletes.enabled=true`. Payload
fields must have no defaults so that received NULL values are preserved. The configured kind and time fields cannot
be partition fields. Generated partition expressions can derive their values from the materialized kind or time.

:::note Conversion time and replay

`emitted_ms` is wall-clock time at the conversion operator, not source event time or checkpoint commit time. It is not
globally ordered across subtasks. Records reprocessed after failure or replay can receive a new timestamp, potentially
changing downstream time-window assignment. This mode does not promise deterministic timestamps across recovery.
Adding or removing the conversion operator changes the job topology; assess savepoint compatibility before changing
the mode on an existing job.

:::

## Manage Small Files

| Approach | When it runs | How to select it |
Expand Down
18 changes: 18 additions & 0 deletions docs/generated/flink_connector_configuration.html
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,24 @@
<td>Integer</td>
<td>Sets how many writer subtasks write each bucket. Set to -1 to let every writer subtask write every bucket. Only takes effect when 'sink.striped-bucket-write.enabled' is true.</td>
</tr>
<tr>
<td><h5>sink.changelog-as-append</h5></td>
<td style="word-wrap: break-word;">false</td>
<td>Boolean</td>
<td>Materialize each received INSERT, UPDATE_BEFORE, UPDATE_AFTER and DELETE payload as an independent INSERT event in a non-keyed file-store table. Duplicate payloads are retained. Requires explicit kind and time fields and payload columns without defaults. Does not support lake-stream writes, overwrite, ignore-delete, ignore-update-before, rowkind.field or key-only deletes. Only applies to the Flink SQL table sink. Disabled by default.</td>
</tr>
<tr>
<td><h5>sink.changelog-as-append.kind-field</h5></td>
<td style="word-wrap: break-word;">(none)</td>
<td>String</td>
<td>Nullable physical STRING field populated with the original Flink row kind when sink.changelog-as-append is enabled. Must accommodate UPDATE_BEFORE and cannot be a partition field. The sink overwrites the supplied value.</td>
</tr>
<tr>
<td><h5>sink.changelog-as-append.time-field</h5></td>
<td style="word-wrap: break-word;">(none)</td>
<td>String</td>
<td>Nullable physical BIGINT field populated with conversion-time epoch milliseconds when sink.changelog-as-append is enabled. Cannot be a partition field. The sink overwrites the supplied value. This is not source event time or commit time; replay may assign a new timestamp.</td>
</tr>
<tr>
<td><h5>sink.clustering.sample-factor</h5></td>
<td style="word-wrap: break-word;">100</td>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
import org.apache.flink.configuration.ExecutionOptions;
import org.apache.flink.configuration.ReadableConfig;
import org.apache.flink.table.api.TableConfig;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.catalog.CatalogTable;
import org.apache.flink.table.catalog.ObjectIdentifier;
import org.apache.flink.table.connector.sink.DynamicTableSink;
Expand All @@ -72,6 +73,7 @@
import static java.lang.Boolean.parseBoolean;
import static org.apache.paimon.flink.FlinkConnectorOptions.FILESYSTEM_JOB_LEVEL_SETTINGS_ENABLED;
import static org.apache.paimon.flink.FlinkConnectorOptions.SCAN_BOUNDED;
import static org.apache.paimon.flink.FlinkConnectorOptions.SINK_CHANGELOG_AS_APPEND;
import static org.apache.paimon.flink.LogicalTypeConversion.toLogicalType;

/** Abstract paimon factory to create table source and table sink. */
Expand Down Expand Up @@ -107,6 +109,14 @@ public DynamicTableSource createDynamicTableSource(Context context) {
@Override
public DynamicTableSink createDynamicTableSink(Context context) {
if (LakeStreamTableFactory.isLakeStreamWrite(flinkCatalog, context)) {
Options options =
new Options(
context.getCatalogTable().getOptions(),
getDynamicConfigOptions(context));
if (options.get(SINK_CHANGELOG_AS_APPEND)) {
throw new ValidationException(
"sink.changelog-as-append is not supported for lake-stream writes.");
}
return createLakeStreamSink(context);
}
return createPaimonTableSink(context, buildPaimonTable(context));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,37 @@
/** Options for flink connector. */
public class FlinkConnectorOptions {

public static final ConfigOption<Boolean> SINK_CHANGELOG_AS_APPEND =
key("sink.changelog-as-append")
.booleanType()
.defaultValue(false)
.withDescription(
"Materialize each received INSERT, UPDATE_BEFORE, UPDATE_AFTER and DELETE "
+ "payload as an independent INSERT event in a non-keyed file-store table. "
+ "Duplicate payloads are retained. Requires explicit kind and time fields "
+ "and payload columns without defaults. Does not support lake-stream writes, "
+ "overwrite, ignore-delete, ignore-update-before, rowkind.field or key-only deletes. "
+ "Only applies to the Flink SQL table sink. Disabled by default.");

public static final ConfigOption<String> SINK_CHANGELOG_KIND_FIELD =
key("sink.changelog-as-append.kind-field")
.stringType()
.noDefaultValue()
.withDescription(
"Nullable physical STRING field populated with the original Flink row kind "
+ "when sink.changelog-as-append is enabled. Must accommodate UPDATE_BEFORE "
+ "and cannot be a partition field. The sink overwrites the supplied value.");

public static final ConfigOption<String> SINK_CHANGELOG_TIME_FIELD =
key("sink.changelog-as-append.time-field")
.stringType()
.noDefaultValue()
.withDescription(
"Nullable physical BIGINT field populated with conversion-time epoch milliseconds "
+ "when sink.changelog-as-append is enabled. Cannot be a partition field. "
+ "The sink overwrites the supplied value. This is not source event time or "
+ "commit time; replay may assign a new timestamp.");

public static final String NONE = "none";

public static final String TABLE_DYNAMIC_OPTION_PREFIX = "paimon.";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.paimon.flink.sink;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.table.runtime.typeutils.RowDataSerializer;
import org.apache.flink.table.types.logical.LogicalTypeRoot;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.table.types.logical.VarCharType;
import org.apache.flink.types.RowKind;

/** Materializes changelog payloads as independent log records before the append writer. */
final class ChangelogAsAppend implements MapFunction<RowData, RowData> {
private static final long serialVersionUID = 1L;

private final RowType rowType;
private final int kindField;
private final int timeField;
private transient RowDataSerializer serializer;
private transient RowData.FieldGetter[] getters;

ChangelogAsAppend(RowType rowType, String kindField, String timeField) {
this.rowType = rowType;
this.kindField = field(rowType, kindField, LogicalTypeRoot.VARCHAR);
this.timeField = field(rowType, timeField, LogicalTypeRoot.BIGINT);
if (this.kindField == this.timeField) {
throw new IllegalArgumentException("Changelog metadata fields must be distinct.");
}
}

private static int field(RowType rowType, String name, LogicalTypeRoot type) {
int index = rowType.getFieldNames().indexOf(name);
if (index < 0 || rowType.getTypeAt(index).getTypeRoot() != type) {
throw new IllegalArgumentException(
"Changelog metadata requires a physical " + type + " field: " + name);
}
if (!rowType.getTypeAt(index).isNullable()
|| (type == LogicalTypeRoot.VARCHAR
&& ((VarCharType) rowType.getTypeAt(index)).getLength() < 13)) {
throw new IllegalArgumentException(
"Changelog metadata fields must be nullable; kind field must fit UPDATE_BEFORE.");
}
return index;
}

@Override
public RowData map(RowData input) {
if (serializer == null) {
serializer = new RowDataSerializer(rowType);
getters = new RowData.FieldGetter[rowType.getFieldCount()];
for (int i = 0; i < getters.length; i++) {
getters[i] = RowData.createFieldGetter(rowType.getTypeAt(i), i);
}
}
// Deep copy first: upstream operators may reuse both rows and nested values.
RowData copy = serializer.copy(input);
GenericRowData output = new GenericRowData(RowKind.INSERT, getters.length);
for (int i = 0; i < getters.length; i++) {
output.setField(i, getters[i].getFieldOrNull(copy));
}
output.setField(kindField, StringData.fromString(input.getRowKind().name()));
output.setField(timeField, System.currentTimeMillis());
return output;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
package org.apache.paimon.flink.sink;

import org.apache.paimon.flink.PaimonDataStreamSinkProvider;
import org.apache.paimon.options.Options;
import org.apache.paimon.table.FormatTable;

import org.apache.flink.table.catalog.ObjectIdentifier;
Expand All @@ -31,6 +32,9 @@
import java.util.HashMap;
import java.util.Map;

import static org.apache.paimon.flink.FlinkConnectorOptions.SINK_CHANGELOG_AS_APPEND;
import static org.apache.paimon.utils.Preconditions.checkArgument;

/** Table sink for format tables. */
public abstract class FlinkFormatTableSinkBase
implements DynamicTableSink, SupportsOverwrite, SupportsPartitioning {
Expand All @@ -45,6 +49,10 @@ public FlinkFormatTableSinkBase(
ObjectIdentifier tableIdentifier,
FormatTable table,
DynamicTableFactory.Context context) {
// Batch planning can skip changelog negotiation, so validate when the sink is created.
checkArgument(
!Options.fromMap(table.options()).get(SINK_CHANGELOG_AS_APPEND),
"sink.changelog-as-append is not supported for format tables.");
this.tableIdentifier = tableIdentifier;
this.table = table;
this.context = context;
Expand Down
Loading