This is an automated email from the ASF dual-hosted git repository.

JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git


The following commit(s) were added to refs/heads/master by this push:
     new 422aea3b4d [core] Support integer and datetime timestamps in 
merge_map_with_keytime (#11084)
422aea3b4d is described below

commit 422aea3b4d974b14df1123e53ae09230b0f905dc
Author: yuzelin <[email protected]>
AuthorDate: Wed Nov 11 11:55:59 2026 +0800

    [core] Support integer and datetime timestamps in merge_map_with_keytime 
(#11084)
---
 .../primary-key-table/merge-engine/aggregation.mdx | 15 ++++-
 .../aggregate/FieldMergeMapWithKeyTimeAgg.java     | 17 ++++-
 .../FieldMergeMapWithKeyTimeAggFactory.java        |  8 ++-
 .../compact/aggregate/FieldAggregatorTest.java     | 74 ++++++++++++----------
 .../paimon/table/PrimaryKeySimpleTableTest.java    | 36 ++++++++---
 .../pypaimon/tests/test_field_aggregators.py       | 48 ++++++++++++++
 6 files changed, 148 insertions(+), 50 deletions(-)

diff --git a/docs/docs/primary-key-table/merge-engine/aggregation.mdx 
b/docs/docs/primary-key-table/merge-engine/aggregation.mdx
index 24a92f696c..0c47f78432 100644
--- a/docs/docs/primary-key-table/merge-engine/aggregation.mdx
+++ b/docs/docs/primary-key-table/merge-engine/aggregation.mdx
@@ -195,9 +195,18 @@ count of distinct event IDs.
 ### merge_map_with_keytime
 
   The merge_map_with_keytime function merges input maps with key-level partial 
updates based on timestamps.
-  Each key in the map carries a string timestamp. During merging, the entry 
with the greater
-  timestamp in lexicographic order is retained. Use equally padded numeric 
strings or a consistent
-  sortable date/time format; the implementation reads this field as a string.
+  Each key in the map carries a timestamp. During merging, the entry with the 
greater
+  timestamp is retained. The timestamp field supports:
+
+  - `CHAR`, `VARCHAR`, or `STRING`: compared lexicographically by UTF-8 bytes. 
Use equally padded
+    numeric strings or a consistent sortable date/time format. This differs 
from the previous Java
+    UTF-16 string ordering for some supplementary Unicode characters; ASCII 
timestamps are unaffected.
+  - `TINYINT`, `SMALLINT`, `INT`, or `BIGINT`: compared numerically without 
conversion to floating point.
+  - `DATE`: compared by date.
+  - `TIME`: compared by time of day, without a date component.
+  - `TIMESTAMP` or `TIMESTAMP_LTZ`: compared at the declared precision, 
including nanoseconds.
+    Spark's `TIMESTAMP_NTZ` maps to Paimon's `TIMESTAMP` and is also supported.
+
   It only supports `MAP<key_type, ROW<value_field, ts_field>>` type, where the 
ROW must have at least 2 fields.
 
   Use `fields.<field-name>.ts-field=<field_name_in_row>` to specify the 
timestamp field name in the ROW type.
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/mergetree/compact/aggregate/FieldMergeMapWithKeyTimeAgg.java
 
b/paimon-core/src/main/java/org/apache/paimon/mergetree/compact/aggregate/FieldMergeMapWithKeyTimeAgg.java
index f273140801..af788221e7 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/mergetree/compact/aggregate/FieldMergeMapWithKeyTimeAgg.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/mergetree/compact/aggregate/FieldMergeMapWithKeyTimeAgg.java
@@ -21,7 +21,10 @@ package org.apache.paimon.mergetree.compact.aggregate;
 import org.apache.paimon.data.InternalArray;
 import org.apache.paimon.data.InternalMap;
 import org.apache.paimon.data.InternalRow;
+import org.apache.paimon.types.DataTypeRoot;
 import org.apache.paimon.types.MapType;
+import org.apache.paimon.types.RowType;
+import org.apache.paimon.utils.InternalRowUtils;
 
 import java.util.HashMap;
 import java.util.Map;
@@ -34,6 +37,8 @@ public class FieldMergeMapWithKeyTimeAgg extends 
FieldAggregator {
     private final InternalArray.ElementGetter keyGetter;
     private final InternalArray.ElementGetter valueGetter;
     private final int timestampFieldIndex;
+    private final InternalRow.FieldGetter timestampFieldGetter;
+    private final DataTypeRoot timestampFieldTypeRoot;
     private final boolean overwriteOnEqualTs;
 
     /** See {@link BinaryMapKeys}: a binary key has no value equality of its 
own. */
@@ -49,6 +54,11 @@ public class FieldMergeMapWithKeyTimeAgg extends 
FieldAggregator {
         this.keyGetter = 
InternalArray.createElementGetter(dataType.getKeyType());
         this.valueGetter = 
InternalArray.createElementGetter(dataType.getValueType());
         this.timestampFieldIndex = timestampFieldIndex;
+        RowType rowType = (RowType) dataType.getValueType();
+        this.timestampFieldGetter =
+                InternalRow.createFieldGetter(
+                        rowType.getTypeAt(timestampFieldIndex), 
timestampFieldIndex);
+        this.timestampFieldTypeRoot = 
rowType.getTypeAt(timestampFieldIndex).getTypeRoot();
         this.overwriteOnEqualTs = overwriteOnEqualTs;
         this.binaryKey = BinaryMapKeys.isBinary(dataType.getKeyType());
     }
@@ -112,9 +122,10 @@ public class FieldMergeMapWithKeyTimeAgg extends 
FieldAggregator {
                 if (existingRow.isNullAt(timestampFieldIndex)) {
                     resultMap.put(key, newRow);
                 } else {
-                    String newTs = 
newRow.getString(timestampFieldIndex).toString();
-                    String existingTs = 
existingRow.getString(timestampFieldIndex).toString();
-                    int comparison = newTs.compareTo(existingTs);
+                    Object newTs = timestampFieldGetter.getFieldOrNull(newRow);
+                    Object existingTs = 
timestampFieldGetter.getFieldOrNull(existingRow);
+                    int comparison =
+                            InternalRowUtils.compare(newTs, existingTs, 
timestampFieldTypeRoot);
                     if (comparison > 0 || (comparison == 0 && 
overwriteOnEqualTs)) {
                         resultMap.put(key, newRow);
                     }
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/mergetree/compact/aggregate/factory/FieldMergeMapWithKeyTimeAggFactory.java
 
b/paimon-core/src/main/java/org/apache/paimon/mergetree/compact/aggregate/factory/FieldMergeMapWithKeyTimeAggFactory.java
index 6f05b30077..14218f2f50 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/mergetree/compact/aggregate/factory/FieldMergeMapWithKeyTimeAggFactory.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/mergetree/compact/aggregate/factory/FieldMergeMapWithKeyTimeAggFactory.java
@@ -82,8 +82,12 @@ public class FieldMergeMapWithKeyTimeAggFactory implements 
FieldAggregatorFactor
 
         DataType tsFieldType = rowType.getTypeAt(tsFieldIndex);
         checkArgument(
-                
tsFieldType.getTypeRoot().getFamilies().contains(DataTypeFamily.CHARACTER_STRING),
-                "Timestamp field '%s' for field '%s' must be a string type 
(CHAR/VARCHAR) but was '%s'.",
+                tsFieldType.isAnyOf(
+                        DataTypeFamily.CHARACTER_STRING,
+                        DataTypeFamily.INTEGER_NUMERIC,
+                        DataTypeFamily.DATETIME),
+                "Timestamp field '%s' for field '%s' must be 
CHAR/VARCHAR/STRING, TINYINT/SMALLINT/INT/BIGINT or "
+                        + "DATE/TIME/TIMESTAMP/TIMESTAMP_LTZ but was '%s'.",
                 rowType.getFieldNames().get(tsFieldIndex),
                 field,
                 tsFieldType);
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/mergetree/compact/aggregate/FieldAggregatorTest.java
 
b/paimon-core/src/test/java/org/apache/paimon/mergetree/compact/aggregate/FieldAggregatorTest.java
index 2104a689c9..821b21de0c 100644
--- 
a/paimon-core/src/test/java/org/apache/paimon/mergetree/compact/aggregate/FieldAggregatorTest.java
+++ 
b/paimon-core/src/test/java/org/apache/paimon/mergetree/compact/aggregate/FieldAggregatorTest.java
@@ -72,6 +72,9 @@ import org.apache.paimon.utils.TypeCheckUtils;
 import org.apache.paimon.shade.guava30.com.google.common.collect.ImmutableMap;
 
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
 
 import java.io.IOException;
 import java.math.BigDecimal;
@@ -3079,25 +3082,43 @@ public class FieldAggregatorTest {
         return result;
     }
 
-    @Test
-    public void testFieldMergeMapWithKeyTimeAgg() {
+    private static Stream<Arguments> mergeMapTimestampValues() {
+        return Stream.of(
+                Arguments.of(DataTypes.STRING(), "100", "110"),
+                Arguments.of(DataTypes.TINYINT(), (byte) 100, (byte) 110),
+                Arguments.of(DataTypes.SMALLINT(), (short) 100, (short) 110),
+                Arguments.of(DataTypes.INT(), 9, 100),
+                Arguments.of(DataTypes.BIGINT(), Long.MAX_VALUE - 1, 
Long.MAX_VALUE),
+                Arguments.of(DataTypes.DATE(), -1, 0),
+                Arguments.of(DataTypes.TIME(3), 86_399_998, 86_399_999),
+                Arguments.of(
+                        DataTypes.TIMESTAMP(9),
+                        Timestamp.fromEpochMillis(0, 1),
+                        Timestamp.fromEpochMillis(0, 2)),
+                Arguments.of(
+                        DataTypes.TIMESTAMP_WITH_LOCAL_TIME_ZONE(9),
+                        Timestamp.fromEpochMillis(0, 1),
+                        Timestamp.fromEpochMillis(0, 2)));
+    }
+
+    @ParameterizedTest
+    @MethodSource("mergeMapTimestampValues")
+    public void testFieldMergeMapWithKeyTimeAgg(DataType tsType, Object older, 
Object newer) {
         MapType mapType =
                 DataTypes.MAP(
                         DataTypes.STRING(),
                         DataTypes.ROW(
                                 DataTypes.FIELD(0, "actual_value", 
DataTypes.STRING()),
-                                DataTypes.FIELD(1, "dbsync_ts", 
DataTypes.STRING())));
-        FieldMergeMapWithKeyTimeAgg agg = new 
FieldMergeMapWithKeyTimeAgg("test", mapType, 1);
+                                DataTypes.FIELD(1, "dbsync_ts", tsType)));
+        FieldAggregator agg =
+                new FieldMergeMapWithKeyTimeAggFactory()
+                        .create(mapType, new CoreOptions(new HashMap<>()), 
"f");
 
         GenericMap map1 =
-                createTestMap(
-                        createEntry("key1", "A", "17682882903686900100"),
-                        createEntry("key2", "B", "17682882903686900100"));
+                createTestMap(createEntry("key1", "A", older), 
createEntry("key2", "B", newer));
         GenericMap map2 =
-                createTestMap(
-                        createEntry("key1", "A1", "17682882903686900200"),
-                        createEntry("key3", "C", "17682882903686900200"));
-        GenericMap map3 = createTestMap(createEntry("key2", "B2", 
"17682882903686900050"));
+                createTestMap(createEntry("key1", "A1", newer), 
createEntry("key3", "C", newer));
+        GenericMap map3 = createTestMap(createEntry("key2", "B2", older));
 
         Object acc = agg.agg(null, map1);
         assertTestMap(acc, createExpectedEntry("key1", "A"), 
createExpectedEntry("key2", "B"));
@@ -3165,37 +3186,22 @@ public class FieldAggregatorTest {
     }
 
     @Test
-    public void 
testFieldMergeMapWithKeyTimeAggFactoryRejectsNonStringTsField() {
-        // The merge path reads the ts field via InternalRow#getString, so a 
non-string ts field
-        // (declared BIGINT/TIMESTAMP/INT, which is natural for a "ts" field) 
is accepted at DDL
-        // today and only throws ClassCastException at the first 
merge/compaction, naming neither
-        // the field nor the function. Validate it is a string type at factory 
creation.
+    public void 
testFieldMergeMapWithKeyTimeAggFactoryRejectsUnsupportedTsField() {
         MapType mapType =
                 DataTypes.MAP(
                         DataTypes.STRING(),
                         DataTypes.ROW(
                                 DataTypes.FIELD(0, "actual_value", 
DataTypes.STRING()),
-                                DataTypes.FIELD(1, "dbsync_ts", 
DataTypes.BIGINT())));
+                                DataTypes.FIELD(1, "dbsync_ts", 
DataTypes.DOUBLE())));
         assertThatThrownBy(
                         () ->
                                 new FieldMergeMapWithKeyTimeAggFactory()
                                         .create(mapType, new CoreOptions(new 
HashMap<>()), "f"))
                 .isInstanceOf(IllegalArgumentException.class)
-                .hasMessageContaining("must be a string type");
-    }
-
-    @Test
-    public void testFieldMergeMapWithKeyTimeAggFactoryAcceptsStringTsField() {
-        MapType mapType =
-                DataTypes.MAP(
-                        DataTypes.STRING(),
-                        DataTypes.ROW(
-                                DataTypes.FIELD(0, "actual_value", 
DataTypes.STRING()),
-                                DataTypes.FIELD(1, "dbsync_ts", 
DataTypes.STRING())));
-        assertThat(
-                        new FieldMergeMapWithKeyTimeAggFactory()
-                                .create(mapType, new CoreOptions(new 
HashMap<>()), "f"))
-                .isNotNull();
+                .hasMessage(
+                        "Timestamp field 'dbsync_ts' for field 'f' must be 
CHAR/VARCHAR/STRING, "
+                                + "TINYINT/SMALLINT/INT/BIGINT or 
DATE/TIME/TIMESTAMP/TIMESTAMP_LTZ "
+                                + "but was 'DOUBLE'.");
     }
 
     /**
@@ -3279,12 +3285,12 @@ public class FieldAggregatorTest {
         return row.getString(0).toString();
     }
 
-    private Map.Entry<BinaryString, InternalRow> createEntry(String key, 
String value, String ts) {
+    private Map.Entry<BinaryString, InternalRow> createEntry(String key, 
String value, Object ts) {
         return new AbstractMap.SimpleEntry<>(
                 BinaryString.fromString(key),
                 GenericRow.of(
                         value == null ? null : BinaryString.fromString(value),
-                        ts == null ? null : BinaryString.fromString(ts)));
+                        ts instanceof String ? 
BinaryString.fromString((String) ts) : ts));
     }
 
     private Map.Entry<String, String> createExpectedEntry(String key, String 
value) {
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeySimpleTableTest.java
 
b/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeySimpleTableTest.java
index a76ef75730..62fdc5c8f2 100644
--- 
a/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeySimpleTableTest.java
+++ 
b/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeySimpleTableTest.java
@@ -28,6 +28,7 @@ import org.apache.paimon.data.GenericArray;
 import org.apache.paimon.data.GenericMap;
 import org.apache.paimon.data.GenericRow;
 import org.apache.paimon.data.InternalRow;
+import org.apache.paimon.data.Timestamp;
 import org.apache.paimon.disk.IOManager;
 import org.apache.paimon.disk.IOManagerImpl;
 import org.apache.paimon.fs.FileIOFinder;
@@ -95,8 +96,9 @@ import org.apache.commons.math3.random.RandomDataGenerator;
 import org.assertj.core.api.Assertions;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.Arguments;
 import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
 import org.junit.jupiter.params.provider.ValueSource;
 
 import java.io.File;
@@ -118,6 +120,7 @@ import java.util.function.BiFunction;
 import java.util.function.Consumer;
 import java.util.function.Function;
 import java.util.stream.Collectors;
+import java.util.stream.Stream;
 
 import static java.util.Collections.singletonList;
 import static java.util.Collections.singletonMap;
@@ -160,10 +163,29 @@ import static 
org.assertj.core.api.Assertions.assertThatThrownBy;
 /** Tests for {@link PrimaryKeyFileStoreTable}. */
 public class PrimaryKeySimpleTableTest extends SimpleTableTestBase {
 
+    private static Stream<Arguments> mergeMapTimestampTypes() {
+        Map<DataType, Object> timestamps = new HashMap<>();
+        timestamps.put(DataTypes.STRING(), BinaryString.fromString("100"));
+        timestamps.put(DataTypes.BIGINT(), Long.MAX_VALUE);
+        timestamps.put(DataTypes.TIMESTAMP(9), Timestamp.fromEpochMillis(0, 
1));
+        timestamps.put(
+                DataTypes.TIMESTAMP_WITH_LOCAL_TIME_ZONE(9), 
Timestamp.fromEpochMillis(0, 1));
+        return timestamps.entrySet().stream()
+                .flatMap(
+                        entry ->
+                                Stream.of(
+                                        Arguments.of(
+                                                false, false, entry.getKey(), 
entry.getValue()),
+                                        Arguments.of(false, true, 
entry.getKey(), entry.getValue()),
+                                        Arguments.of(true, false, 
entry.getKey(), entry.getValue()),
+                                        Arguments.of(
+                                                true, true, entry.getKey(), 
entry.getValue())));
+    }
+
     @ParameterizedTest
-    @CsvSource({"false,false", "false,true", "true,false", "true,true"})
-    public void testMergeMapOverwriteOnEqualTs(boolean partialUpdate, boolean 
overwrite)
-            throws Exception {
+    @MethodSource("mergeMapTimestampTypes")
+    public void testMergeMapOverwriteOnEqualTs(
+            boolean partialUpdate, boolean overwrite, DataType tsType, Object 
ts) throws Exception {
         RowType rowType =
                 RowType.of(
                         new DataType[] {
@@ -173,7 +195,7 @@ public class PrimaryKeySimpleTableTest extends 
SimpleTableTestBase {
                                     DataTypes.STRING(),
                                     DataTypes.ROW(
                                             DataTypes.FIELD(4, "v", 
DataTypes.STRING()),
-                                            DataTypes.FIELD(5, "ts", 
DataTypes.STRING()))),
+                                            DataTypes.FIELD(5, "ts", tsType))),
                             DataTypes.BIGINT()
                         },
                         new String[] {"pt", "a", "attrs", "seq"});
@@ -198,9 +220,7 @@ public class PrimaryKeySimpleTableTest extends 
SimpleTableTestBase {
                         new GenericMap(
                                 Collections.singletonMap(
                                         BinaryString.fromString("k"),
-                                        GenericRow.of(
-                                                BinaryString.fromString(value),
-                                                
BinaryString.fromString("100"))));
+                                        
GenericRow.of(BinaryString.fromString(value), ts)));
         Function<InternalRow, String> value =
                 row -> row.getMap(2).valueArray().getRow(0, 
2).getString(0).toString();
         try (StreamTableWrite write = table.newWrite(commitUser);
diff --git a/paimon-python/pypaimon/tests/test_field_aggregators.py 
b/paimon-python/pypaimon/tests/test_field_aggregators.py
index 57e2b1fb0e..afcec2f6f0 100644
--- a/paimon-python/pypaimon/tests/test_field_aggregators.py
+++ b/paimon-python/pypaimon/tests/test_field_aggregators.py
@@ -2572,6 +2572,54 @@ class FieldMergeMapWithKeyTimeAggTest(unittest.TestCase):
             fields = self.DEFAULT_FIELDS
         return GenericRow(list(values), fields)
 
+    def test_timestamp_types(self):
+        cases = [
+            ("TINYINT", -128, 127),
+            ("SMALLINT", -32768, 32767),
+            ("INT", 9, 100),
+            ("BIGINT", -(1 << 63), (1 << 63) - 1),
+            ("BIGINT", (1 << 63) - 2, (1 << 63) - 1),
+            ("DATE", datetime.date(1969, 12, 31), datetime.date(1970, 1, 1)),
+            ("TIME(3)", datetime.time(23, 59, 59, 998000), datetime.time(23, 
59, 59, 999000)),
+            ("TIMESTAMP(9)", Timestamp(0, 1), Timestamp(0, 2)),
+            ("TIMESTAMP_LTZ(9)", Timestamp(-1, 999998), Timestamp(-1, 999999)),
+            ("TIMESTAMP(6)", datetime.datetime(2026, 1, 1, microsecond=1),
+             datetime.datetime(2026, 1, 1, microsecond=2)),
+            ("TIMESTAMP_LTZ(6)",
+             datetime.datetime(2026, 1, 1, 8, 
tzinfo=datetime.timezone(datetime.timedelta(hours=8))),
+             datetime.datetime(2026, 1, 1, 0, 0, 1, 
tzinfo=datetime.timezone.utc)),
+        ]
+        for type_name, older, newer in cases:
+            for overwrite in (False, True):
+                for named in (False, True):
+                    for dict_row in (False, True):
+                        with self.subTest(type=type_name, overwrite=overwrite, 
named=named, dict_row=dict_row):
+                            fields = [DataField(0, "v", AtomicType("STRING")),
+                                      DataField(1, "ts", 
AtomicType(type_name))]
+                            settings = {"fields.field0.overwrite-on-equal-ts": 
str(overwrite).lower()}
+                            if named:
+                                fields.reverse()
+                                settings["fields.field0.ts-field"] = "ts"
+                            agg = self._make(RowType(True, fields), 
CoreOptions(Options(settings)))
+
+                            def entry(value, ts):
+                                row = {"v": value, "ts": ts}
+                                if not dict_row:
+                                    row = GenericRow([row[f.name] for f in 
fields], fields)
+                                return {"k": row}
+
+                            old = entry("old", older)
+                            new = entry("new", newer)
+                            equal = entry("equal", newer)
+                            null_ts = entry("null", None)
+                            self.assertEqual(agg.agg(old, new), new)
+                            self.assertEqual(agg.agg(new, old), new)
+                            self.assertEqual(agg.agg(new, equal), equal if 
overwrite else new)
+                            self.assertEqual(agg.agg(equal, new), new if 
overwrite else equal)
+                            self.assertEqual(agg.agg(new, null_ts), new)
+                            self.assertEqual(agg.agg(null_ts, new), new)
+                            self.assertEqual(agg.agg(new, {"k": None}), {})
+
     def test_field_merge_map_with_key_time_dict_row_default_ts(self):
         agg = self._make()
 

Reply via email to