PavithranRick commented on code in PR #17460:
URL: https://github.com/apache/hudi/pull/17460#discussion_r2632924828


##########
hudi-spark-datasource/hudi-spark/src/main/scala/org/apache/spark/sql/hudi/command/procedures/ShowCompactionProcedure.scala:
##########
@@ -57,24 +130,185 @@ class ShowCompactionProcedure extends BaseProcedure with 
ProcedureBuilder with S
     val tableName = getArgValueOrDefault(args, PARAMETERS(0))
     val tablePath = getArgValueOrDefault(args, PARAMETERS(1))
     val limit = getArgValueOrDefault(args, PARAMETERS(2)).get.asInstanceOf[Int]
+    val showArchived = getArgValueOrDefault(args, 
PARAMETERS(3)).get.asInstanceOf[Boolean]
+    val filter = getArgValueOrDefault(args, 
PARAMETERS(4)).get.asInstanceOf[String]
+    val startTime = getArgValueOrDefault(args, 
PARAMETERS(5)).get.asInstanceOf[String]
+    val endTime = getArgValueOrDefault(args, 
PARAMETERS(6)).get.asInstanceOf[String]
 
+    validateFilter(filter, outputType)
     val basePath: String = getBasePath(tableName, tablePath)
     val metaClient = createMetaClient(jsc, basePath)
 
-    assert(metaClient.getTableType == HoodieTableType.MERGE_ON_READ,
-      s"Cannot show compaction on a Non Merge On Read table.")
-    val compactionInstants = 
metaClient.getActiveTimeline.getInstants.iterator().asScala
+    if (metaClient.getTableType != HoodieTableType.MERGE_ON_READ) {
+      throw new IllegalArgumentException("Cannot show compaction on a Non 
Merge On Read table.")
+    }
+
+    val activeResults = 
getCombinedCompactionsWithPartitionMetadata(metaClient.getActiveTimeline, 
limit, metaClient, startTime, endTime, "ACTIVE")
+    val finalResults = if (showArchived) {
+      val archivedResults = 
getCombinedCompactionsWithPartitionMetadata(metaClient.getArchivedTimeline, 
limit, metaClient, startTime, endTime, "ARCHIVED")
+      val combinedResults = (activeResults ++ archivedResults)
+        .sortWith((a, b) => a.getString(0) > b.getString(0))
+      if (startTime.trim.nonEmpty && endTime.trim.nonEmpty) {
+        combinedResults
+      } else {
+        combinedResults.take(limit)
+      }
+    } else {
+      if (startTime.trim.nonEmpty && endTime.trim.nonEmpty) {
+        activeResults
+      } else {
+        activeResults.take(limit)
+      }
+    }
+    applyFilter(finalResults, filter, outputType)
+  }
+
+  private def getCombinedCompactionsWithPartitionMetadata(timeline: 
HoodieTimeline,
+                                                          limit: Int,
+                                                          metaClient: 
HoodieTableMetaClient,
+                                                          startTime: String,
+                                                          endTime: String,
+                                                          timelineType: 
String): Seq[Row] = {
+    import scala.collection.mutable.ListBuffer
+
+    val allRows = ListBuffer[Row]()
+
+    val filteredCompactionInstants = timeline.getInstants.iterator().asScala
       .filter(p => p.getAction == HoodieTimeline.COMPACTION_ACTION || 
p.getAction == HoodieTimeline.COMMIT_ACTION)
+      .filter { instant =>
+        val instantTime = instant.requestedTime()
+        val withinStartTime = if (startTime.nonEmpty) instantTime >= startTime 
else true
+        val withinEndTime = if (endTime.nonEmpty) instantTime <= endTime else 
true
+        withinStartTime && withinEndTime
+      }
       .toSeq
-      .sortBy(f => f.requestedTime)
-      .reverse
-      .take(limit)
-
-    compactionInstants.map(instant =>
-      (instant, CompactionUtils.getCompactionPlan(metaClient, 
instant.requestedTime))
-    ).map { case (instant, plan) =>
-      Row(instant.requestedTime, plan.getOperations.size(), 
instant.getState.name())
+    val allCompactionInstants = if (startTime.nonEmpty && endTime.nonEmpty) {
+      filteredCompactionInstants.sortBy(_.requestedTime).reverse
+    } else {
+      filteredCompactionInstants.sortBy(_.requestedTime).reverse.take(limit)
+    }
+
+    allCompactionInstants.foreach { compactionInstant =>
+      if (compactionInstant.getState == HoodieInstant.State.COMPLETED) {
+        Try {
+          val compactionMetadata = 
timeline.readCommitMetadata(compactionInstant)
+          compactionMetadata.getPartitionToWriteStats.entrySet.asScala.foreach 
{ partitionEntry =>
+            val partitionPath = partitionEntry.getKey
+            val writeStats = partitionEntry.getValue.asScala
+            val operationSize = Try {
+              val compactionPlan = 
CompactionUtils.getCompactionPlan(metaClient, compactionInstant.requestedTime)
+              compactionPlan.getOperations.size()
+            }.getOrElse(null)
+
+            writeStats.foreach { writeStat =>
+              val row = Row(
+                compactionInstant.requestedTime,
+                compactionInstant.getCompletionTime,
+                compactionInstant.getState.name,
+                compactionInstant.getAction,
+                timelineType,
+                operationSize,
+                partitionPath,
+                writeStat.getTotalLogFilesCompacted,
+                writeStat.getTotalUpdatedRecordsCompacted,
+                writeStat.getTotalLogSizeCompacted,
+                writeStat.getTotalWriteBytes
+              )
+              allRows += row
+            }
+          }
+          if (compactionMetadata.getPartitionToWriteStats.isEmpty) {
+            val operationSize = Try {
+              val compactionPlan = 
CompactionUtils.getCompactionPlan(metaClient, compactionInstant.requestedTime)
+              compactionPlan.getOperations.size()
+            }.getOrElse(null)
+
+            val totalLogFilesCompacted = 
compactionMetadata.getTotalLogFilesCompacted
+            val totalUpdatedRecordsCompacted = 
compactionMetadata.fetchTotalUpdateRecordsWritten
+            val totalLogSizeCompacted = compactionMetadata.getTotalLogFilesSize
+            val totalWriteBytes = compactionMetadata.fetchTotalBytesWritten
+
+            val row = Row(
+              compactionInstant.requestedTime,
+              compactionInstant.getCompletionTime,
+              compactionInstant.getState.name,
+              compactionInstant.getAction,
+              timelineType,
+              operationSize,
+              null,
+              totalLogFilesCompacted,
+              totalUpdatedRecordsCompacted,
+              totalLogSizeCompacted,
+              totalWriteBytes
+            )
+            allRows += row
+          }
+        }.recover {
+          case e: Exception =>
+            log.warn(s"Failed to read compaction metadata for instant 
${compactionInstant.requestedTime}: ${e.getMessage}")
+            val row = 
createErrorRowForCompletedWithPartition(compactionInstant, timelineType)
+            allRows += row
+        }
+      } else {
+        Try {
+          val compactionPlan = CompactionUtils.getCompactionPlan(metaClient, 
compactionInstant.requestedTime)
+          val stats = extractCompactionPlanStats(compactionPlan)
+          val operations = compactionPlan.getOperations.asScala
+          stats.involvedPartitions.foreach { partitionPath =>
+            val partitionOps = operations.filter(_.getPartitionPath == 
partitionPath)

Review Comment:
   yes. only the latest



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to