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 8430e75947 [spark] Delete partitions by value in metadata-only DELETE 
(#11296)
8430e75947 is described below

commit 8430e759471946e8489d36d6abe2c6efabab13e1
Author: YangJie <[email protected]>
AuthorDate: Sun Nov 22 05:57:04 2026 -0500

    [spark] Delete partitions by value in metadata-only DELETE (#11296)
---
 .../apache/paimon/operation/FileStoreCommit.java   |  8 +++
 .../paimon/operation/FileStoreCommitImpl.java      |  5 ++
 .../apache/paimon/table/sink/InnerTableCommit.java |  7 +++
 .../apache/paimon/table/sink/TableCommitImpl.java  |  9 ++++
 .../paimon/operation/FileStoreCommitTest.java      | 43 +++++++++++++++
 .../TruncatePaimonTableWithFilterExec.scala        | 61 ++++++++++++----------
 .../spark/sql/PaimonOptimizationTestBase.scala     | 50 ++++++++++++++++++
 7 files changed, 154 insertions(+), 29 deletions(-)

diff --git 
a/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommit.java 
b/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommit.java
index 74f229d262..159085df59 100644
--- a/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommit.java
+++ b/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommit.java
@@ -24,6 +24,7 @@ import org.apache.paimon.disk.IOManager;
 import org.apache.paimon.fs.FileIO;
 import org.apache.paimon.manifest.ManifestCommittable;
 import org.apache.paimon.operation.metrics.CommitMetrics;
+import org.apache.paimon.partition.PartitionPredicate;
 import org.apache.paimon.stats.Statistics;
 import org.apache.paimon.table.sink.CommitMessage;
 import org.apache.paimon.utils.FileStorePathFactory;
@@ -82,6 +83,13 @@ public interface FileStoreCommit extends AutoCloseable {
      */
     void dropPartitions(List<Map<String, String>> partitions, long 
commitIdentifier);
 
+    /**
+     * Drop the partitions {@code partitionFilter} matches in the latest 
snapshot of each commit
+     * attempt; a null filter matches every partition. The {@link 
Snapshot.CommitKind} of generated
+     * snapshot is {@link Snapshot.CommitKind#OVERWRITE}.
+     */
+    void dropPartitions(PartitionPredicate partitionFilter, long 
commitIdentifier);
+
     void truncateTable(long commitIdentifier);
 
     /** Compact the manifest entries only. */
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommitImpl.java
 
b/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommitImpl.java
index 8e99c9cf01..be7196ba74 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommitImpl.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommitImpl.java
@@ -749,6 +749,11 @@ public class FileStoreCommitImpl implements 
FileStoreCommit {
             partitionFilter = PartitionPredicate.fromPredicate(partitionType, 
predicate);
         }
 
+        dropPartitions(partitionFilter, commitIdentifier);
+    }
+
+    @Override
+    public void dropPartitions(PartitionPredicate partitionFilter, long 
commitIdentifier) {
         tryOverwritePartition(
                 partitionFilter, emptyList(), emptyList(), commitIdentifier, 
null, new HashMap<>());
     }
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/table/sink/InnerTableCommit.java 
b/paimon-core/src/main/java/org/apache/paimon/table/sink/InnerTableCommit.java
index 895e7693d4..42c34e8e20 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/table/sink/InnerTableCommit.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/table/sink/InnerTableCommit.java
@@ -20,6 +20,7 @@ package org.apache.paimon.table.sink;
 
 import org.apache.paimon.data.BinaryRow;
 import org.apache.paimon.metrics.MetricRegistry;
+import org.apache.paimon.partition.PartitionPredicate;
 
 import javax.annotation.Nullable;
 
@@ -38,6 +39,12 @@ public interface InnerTableCommit extends StreamTableCommit, 
BatchTableCommit {
      */
     InnerTableCommit withOverwriteStaticPartitions(List<BinaryRow> 
staticPartitions);
 
+    /**
+     * Truncate the partitions {@code partitionFilter} matches, as {@link
+     * BatchTableCommit#truncatePartitions} does for partition specs.
+     */
+    void truncatePartitions(PartitionPredicate partitionFilter);
+
     /**
      * If this is set to true, when there is no new data, no snapshot will be 
generated. By default,
      * empty commit is ignored.
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/table/sink/TableCommitImpl.java 
b/paimon-core/src/main/java/org/apache/paimon/table/sink/TableCommitImpl.java
index accf6e184b..5aff0c5841 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/table/sink/TableCommitImpl.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/table/sink/TableCommitImpl.java
@@ -32,6 +32,7 @@ import org.apache.paimon.metrics.MetricRegistry;
 import org.apache.paimon.operation.FileStoreCommit;
 import org.apache.paimon.operation.PartitionExpire;
 import org.apache.paimon.operation.metrics.CommitMetrics;
+import org.apache.paimon.partition.PartitionPredicate;
 import org.apache.paimon.stats.Statistics;
 import org.apache.paimon.tag.Tag;
 import org.apache.paimon.tag.TagAutoCreation;
@@ -70,6 +71,7 @@ import static java.util.Collections.emptyList;
 import static java.util.Collections.singletonList;
 import static org.apache.paimon.CoreOptions.ExpireExecutionMode;
 import static org.apache.paimon.table.sink.BatchWriteBuilder.COMMIT_IDENTIFIER;
+import static org.apache.paimon.utils.Preconditions.checkNotNull;
 import static org.apache.paimon.utils.Preconditions.checkState;
 import static 
org.apache.paimon.utils.ThreadPoolUtils.randomlyExecuteSequentialReturn;
 
@@ -230,6 +232,13 @@ public class TableCommitImpl implements InnerTableCommit {
         commit.dropPartitions(partitionSpecs, COMMIT_IDENTIFIER);
     }
 
+    @Override
+    public void truncatePartitions(PartitionPredicate partitionFilter) {
+        checkNotNull(partitionFilter, "Partition filter cannot be null.");
+        commit.withOperation(Snapshot.Operation.TRUNCATE);
+        commit.dropPartitions(partitionFilter, COMMIT_IDENTIFIER);
+    }
+
     @Override
     public void updateStatistics(Statistics statistics) {
         commit.commitStatistics(statistics, COMMIT_IDENTIFIER);
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/operation/FileStoreCommitTest.java
 
b/paimon-core/src/test/java/org/apache/paimon/operation/FileStoreCommitTest.java
index 2d5ab91edd..6a3f7845f7 100644
--- 
a/paimon-core/src/test/java/org/apache/paimon/operation/FileStoreCommitTest.java
+++ 
b/paimon-core/src/test/java/org/apache/paimon/operation/FileStoreCommitTest.java
@@ -27,6 +27,7 @@ import org.apache.paimon.TestKeyValueGenerator;
 import org.apache.paimon.catalog.RenamingSnapshotCommit;
 import org.apache.paimon.catalog.SnapshotCommit;
 import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.data.BinaryString;
 import org.apache.paimon.deletionvectors.BucketedDvMaintainer;
 import org.apache.paimon.deletionvectors.DeletionVector;
 import org.apache.paimon.fs.Path;
@@ -53,6 +54,7 @@ import org.apache.paimon.operation.commit.ConflictDetection;
 import org.apache.paimon.operation.commit.ManifestEntryChanges;
 import org.apache.paimon.operation.commit.RetryCommitResult;
 import org.apache.paimon.options.Options;
+import org.apache.paimon.partition.PartitionPredicate;
 import org.apache.paimon.predicate.PredicateBuilder;
 import org.apache.paimon.schema.FileSystemSchemaManager;
 import org.apache.paimon.schema.Schema;
@@ -889,6 +891,47 @@ public class FileStoreCommitTest {
         assertThat(actual).isEqualTo(expected);
     }
 
+    @Test
+    public void testDropPartitionsByPredicate() throws Exception {
+        Map<BinaryRow, List<KeyValue>> data =
+                generateData(ThreadLocalRandom.current().nextInt(50, 1000));
+        TestFileStore store = createStore(false);
+        store.commitData(
+                
data.values().stream().flatMap(Collection::stream).collect(Collectors.toList()),
+                gen::getPartition,
+                kv -> 0);
+
+        // A predicate on dt alone also drops an hr partition the first commit 
did not write.
+        BinaryString dropped = data.keySet().iterator().next().getString(0);
+        PartitionPredicate partitionFilter =
+                PartitionPredicate.fromPredicate(
+                        TestKeyValueGenerator.DEFAULT_PART_TYPE,
+                        new 
PredicateBuilder(TestKeyValueGenerator.DEFAULT_PART_TYPE)
+                                .equal(0, dropped));
+        store.commitData(
+                Collections.singletonList(
+                        gen.nextPartitionedData(RowKind.INSERT, 
dropped.toString(), 10)),
+                gen::getPartition,
+                kv -> 0);
+        try (FileStoreCommitImpl commit = store.newCommit()) {
+            commit.dropPartitions(partitionFilter, Long.MAX_VALUE);
+        }
+
+        Snapshot snapshot = store.snapshotManager().latestSnapshot();
+        
assertThat(snapshot.commitKind()).isEqualTo(Snapshot.CommitKind.OVERWRITE);
+        List<KeyValue> expectedKvs = new ArrayList<>();
+        data.forEach(
+                (partition, kvs) -> {
+                    if (!partition.getString(0).equals(dropped)) {
+                        expectedKvs.addAll(kvs);
+                    }
+                });
+        gen.sort(expectedKvs);
+        List<KeyValue> actualKvs = store.readKvsFromSnapshot(snapshot.id());
+        gen.sort(actualKvs);
+        
assertThat(store.toKvMap(actualKvs)).isEqualTo(store.toKvMap(expectedKvs));
+    }
+
     @Test
     public void testDropEmptyPartition() throws Exception {
         TestFileStore store = createStore(false);
diff --git 
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/execution/TruncatePaimonTableWithFilterExec.scala
 
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/execution/TruncatePaimonTableWithFilterExec.scala
index 3093d15e84..1e122f6984 100644
--- 
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/execution/TruncatePaimonTableWithFilterExec.scala
+++ 
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/execution/TruncatePaimonTableWithFilterExec.scala
@@ -18,55 +18,58 @@
 
 package org.apache.paimon.spark.execution
 
+import org.apache.paimon.CoreOptions
+import org.apache.paimon.options.Options
 import org.apache.paimon.partition.PartitionPredicate
 import org.apache.paimon.spark.leafnode.PaimonLeafV2CommandExec
 import org.apache.paimon.table.{FileStoreTable, Table}
-import org.apache.paimon.utils.InternalRowPartitionComputer
+import org.apache.paimon.table.sink.BatchTableCommit
 
 import org.apache.spark.sql.catalyst.InternalRow
 import org.apache.spark.sql.catalyst.expressions.Attribute
 
 import java.util.{Collections => JCollections}
 
-import scala.collection.JavaConverters._
-
 case class TruncatePaimonTableWithFilterExec(
     table: Table,
     partitionPredicate: Option[PartitionPredicate])
   extends PaimonLeafV2CommandExec {
 
   override def run(): Seq[InternalRow] = {
+    partitionPredicate match {
+      case Some(p) =>
+        table match {
+          case fileStoreTable: FileStoreTable =>
+            if 
(fileStoreTable.newSnapshotReader().withPartitionFilter(p).partitions().isEmpty)
 {
+              withCommit(table)(_.commit(JCollections.emptyList()))
+            } else {
+              // The commit matches the predicate against the partition values 
themselves. A spec
+              // rebuilt from a value does not always parse back to it, such 
as a blank string,
+              // whose name is the default partition name.
+              val commit = fileStoreTable.newCommit(
+                CoreOptions.createCommitUser(new 
Options(fileStoreTable.options())))
+              try {
+                commit.truncatePartitions(p)
+              } finally {
+                commit.close()
+              }
+            }
+          case _ =>
+            throw new UnsupportedOperationException("Unsupported truncate 
table")
+        }
+      case _ =>
+        withCommit(table)(_.truncateTable())
+    }
+    Nil
+  }
+
+  private def withCommit(table: Table)(operation: BatchTableCommit => Unit): 
Unit = {
     val commit = table.newBatchWriteBuilder().newCommit()
     try {
-      partitionPredicate match {
-        case Some(p) =>
-          table match {
-            case fileStoreTable: FileStoreTable =>
-              val matchedPartitions =
-                
fileStoreTable.newSnapshotReader().withPartitionFilter(p).partitions().asScala
-              if (matchedPartitions.nonEmpty) {
-                val partitionComputer = new InternalRowPartitionComputer(
-                  fileStoreTable.coreOptions().partitionDefaultName(),
-                  fileStoreTable.schema().logicalPartitionType(),
-                  fileStoreTable.partitionKeys.asScala.toArray,
-                  fileStoreTable.coreOptions().legacyPartitionName()
-                )
-                val dropPartitions =
-                  
matchedPartitions.map(partitionComputer.generatePartValues(_).asScala.asJava)
-                commit.truncatePartitions(dropPartitions.asJava)
-              } else {
-                commit.commit(JCollections.emptyList())
-              }
-            case _ =>
-              throw new UnsupportedOperationException("Unsupported truncate 
table")
-          }
-        case _ =>
-          commit.truncateTable()
-      }
+      operation(commit)
     } finally {
       commit.close()
     }
-    Nil
   }
 
   override def output: Seq[Attribute] = Nil
diff --git 
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/PaimonOptimizationTestBase.scala
 
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/PaimonOptimizationTestBase.scala
index 0550e1e4e6..010ade7c7b 100644
--- 
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/PaimonOptimizationTestBase.scala
+++ 
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/PaimonOptimizationTestBase.scala
@@ -175,6 +175,56 @@ abstract class PaimonOptimizationTestBase extends 
PaimonSparkTestBase with Expre
     }
   }
 
+  test("Paimon Optimization: metadata only delete of partitions whose names do 
not parse back") {
+    withTable("t") {
+      sql("CREATE TABLE t (a INT, p STRING) PARTITIONED BY (p)")
+      sql("INSERT INTO t VALUES (1, ' '), (2, NULL), (3, 'a')")
+      // A blank value's partition name is the null partition's.
+      val df = sql("DELETE FROM t WHERE p = ' '")
+      checkTruncatePaimonTable(df)
+      checkAnswer(sql("SELECT a FROM t"), Seq(Row(2), Row(3)))
+    }
+    withTable("t") {
+      sql("CREATE TABLE t (a INT, p1 STRING, p2 BINARY) PARTITIONED BY (p1, 
p2)")
+      sql(
+        "INSERT INTO t VALUES (1, 'x', CAST(' ' AS BINARY)), (2, 'x', NULL), 
(3, 'y', NULL), " +
+          "(4, 'x', X'FF')")
+      // X'FF' is not valid UTF-8, so its partition name holds other bytes.
+      val df = sql("DELETE FROM t WHERE p1 = 'x'")
+      checkTruncatePaimonTable(df)
+      checkAnswer(sql("SELECT a FROM t"), Seq(Row(3)))
+    }
+  }
+
+  test("Paimon Optimization: metadata only delete of a timestamp partition off 
UTC") {
+    withTimeZone("Asia/Shanghai") {
+      withTable("t") {
+        sql("CREATE TABLE t (a INT, p TIMESTAMP) PARTITIONED BY (p)")
+        // The legacy name of 10:30:00 is its UTC wall clock, which parses 
back as 02:30:00 here.
+        sql(
+          "INSERT INTO t VALUES (1, CAST('2024-06-01 10:30:00' AS TIMESTAMP)), 
" +
+            "(2, CAST('2024-06-01 02:30:00' AS TIMESTAMP))")
+        val df = sql("DELETE FROM t WHERE p = TIMESTAMP '2024-06-01 10:30:00'")
+        checkTruncatePaimonTable(df)
+        checkAnswer(sql("SELECT a FROM t"), Seq(Row(2)))
+      }
+    }
+  }
+
+  test("Paimon Optimization: metadata only delete leaves expired partitions 
alone") {
+    withTable("t") {
+      sql("CREATE TABLE t (a INT, dt STRING) PARTITIONED BY (dt)")
+      sql("INSERT INTO t VALUES (1, '2020-01-01'), (2, '2099-01-01')")
+      sql(
+        "ALTER TABLE t SET TBLPROPERTIES ('partition.expiration-time' = '7 d', 
" +
+          "'partition.expiration-check-interval' = '0 s', " +
+          "'partition.timestamp-pattern' = '$dt', 
'partition.timestamp-formatter' = 'yyyy-MM-dd')")
+      val df = sql("DELETE FROM t WHERE dt = '2099-01-01'")
+      checkTruncatePaimonTable(df)
+      checkAnswer(sql("SELECT a FROM t"), Seq(Row(1)))
+    }
+  }
+
   test(s"Paimon Optimization: eval subqueries for delete table with 
ScalarSubquery") {
     withPk.foreach(
       hasPk => {

Reply via email to