stream2000 commented on code in PR #10120:
URL: https://github.com/apache/hudi/pull/10120#discussion_r1399973545


##########
hudi-spark-datasource/hudi-spark/src/main/scala/org/apache/spark/sql/hudi/command/procedures/ShowMetadataTableColumnStatsProcedure.scala:
##########
@@ -0,0 +1,109 @@
+/*
+ * 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.spark.sql.hudi.command.procedures
+
+import org.apache.avro.generic.IndexedRecord
+import org.apache.hudi.avro.model.{BooleanWrapper, BytesWrapper, DateWrapper, 
DecimalWrapper, DoubleWrapper, FloatWrapper, HoodieMetadataColumnStats, 
IntWrapper, LongWrapper, StringWrapper, TimeMicrosWrapper, 
TimestampMicrosWrapper}
+import org.apache.hudi.common.config.HoodieMetadataConfig
+import org.apache.hudi.common.data.HoodieData
+import org.apache.hudi.common.table.{HoodieTableMetaClient, 
TableSchemaResolver}
+import org.apache.hudi.{AvroConversionUtils, ColumnStatsIndexSupport}
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.types.{DataTypes, Metadata, StructField, 
StructType}
+
+import java.util
+import java.util.function.Supplier
+
+
+class ShowMetadataTableColumnStatsProcedure extends BaseProcedure with 
ProcedureBuilder with Logging {
+  private val PARAMETERS = Array[ProcedureParameter](
+    ProcedureParameter.required(0, "table", DataTypes.StringType),
+    ProcedureParameter.optional(1, "targetColumns", DataTypes.StringType)
+  )
+
+  private val OUTPUT_TYPE = new StructType(Array[StructField](
+    StructField("file_name", DataTypes.StringType, nullable = true, 
Metadata.empty),
+    StructField("column_name", DataTypes.StringType, nullable = true, 
Metadata.empty),
+    StructField("min_value", DataTypes.StringType, nullable = true, 
Metadata.empty),
+    StructField("max_value", DataTypes.StringType, nullable = true, 
Metadata.empty),
+    StructField("null_num", DataTypes.LongType, nullable = true, 
Metadata.empty)
+  ))
+
+  def parameters: Array[ProcedureParameter] = PARAMETERS
+
+  def outputType: StructType = OUTPUT_TYPE
+
+  override def call(args: ProcedureArgs): Seq[Row] = {
+    super.checkArgs(PARAMETERS, args)
+
+    val table = getArgValueOrDefault(args, PARAMETERS(0))
+    val targetColumns = getArgValueOrDefault(args, 
PARAMETERS(1)).getOrElse("").toString
+    val targetColumnsSeq = targetColumns.split(",").toSeq
+    val basePath = getBasePath(table)
+    val metadataConfig = HoodieMetadataConfig.newBuilder
+      .enable(true)
+      .build
+    val metaClient = 
HoodieTableMetaClient.builder.setConf(jsc.hadoopConfiguration()).setBasePath(basePath).build
+    val schemaUtil = new TableSchemaResolver(metaClient)
+    var schema = 
AvroConversionUtils.convertAvroSchemaToStructType(schemaUtil.getTableAvroSchema)
+    val columnStatsIndex = new ColumnStatsIndexSupport(spark, schema, 
metadataConfig, metaClient)
+    val colStatsRecords: HoodieData[HoodieMetadataColumnStats] = 
columnStatsIndex.loadColumnStatsIndexRecords(targetColumnsSeq, false)
+
+    val rows = new util.ArrayList[Row]
+    colStatsRecords.collectAsList()
+      .stream()
+      .forEach(c => {
+        rows.add(Row(c.getFileName, c.getColumnName, 
getColumnStatsValue(c.getMinValue), getColumnStatsValue(c.getMaxValue), 
c.getNullCount.longValue()))
+      })
+    rows.stream().toArray().map(r => r.asInstanceOf[Row]).toList
+  }
+
+  def getColumnStatsValue(stats_value: Any): String = {
+    stats_value match {
+      case _: IntWrapper |
+           _: BooleanWrapper |
+           _: DateWrapper |
+           _: DoubleWrapper |
+           _: FloatWrapper |
+           _: LongWrapper |
+           _: StringWrapper |
+           _: TimeMicrosWrapper |
+           _: TimestampMicrosWrapper =>
+        String.valueOf(stats_value.asInstanceOf[IndexedRecord].get(0))
+      case _: BytesWrapper =>
+        var bytes_value = stats_value.asInstanceOf[BytesWrapper].getValue
+        util.Arrays.toString(bytes_value.array())
+      case _: DecimalWrapper =>
+        var decimal_value = stats_value.asInstanceOf[DecimalWrapper].getValue
+        util.Arrays.toString(decimal_value.array())
+      case _ => throw new Exception("Unsupported type.")

Review Comment:
   We should provide more information about the unsupported type here. like: 
   
   throw new HoodieException(s"Unsupported type: $type")



##########
hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/spark/sql/hudi/procedure/TestMetadataProcedure.scala:
##########
@@ -91,6 +91,56 @@ class TestMetadataProcedure extends 
HoodieSparkProcedureTestBase {
     }
   }
 
+  test("Test Call show_metadata_table_column_stats Procedure") {
+    withTempDir { tmp =>
+      val tableName = generateTableName
+      // create table
+      spark.sql(
+        s"""
+           |create table $tableName (
+           |  c1 int,
+           |  c2 boolean,
+           |  c3 binary,
+           |  c4 date,
+           |  c5 decimal,
+           |  c6 double,
+           |  c7 float,
+           |  c8 long,
+           |  c9 string,
+           |  c10 timestamp
+           |) using hudi
+           | location '${tmp.getCanonicalPath}/$tableName'
+           | tblproperties (
+           |  primaryKey = 'c1',
+           |  preCombineField = 'c8',
+           |  hoodie.metadata.enable="true",
+           |  hoodie.metadata.index.column.stats.enable="true"
+           | )
+       """.stripMargin)
+      // insert data to table
+
+      spark.sql(
+        s"""
+           |insert into table $tableName
+           |values (1, true, CAST('binary data' AS BINARY), CAST('2021-01-01' 
AS DATE), 10.5, 3.14, 2.5, 1000, 'example string', CAST('2021-01-01 00:00:00' 
AS TIMESTAMP))
+           |""".stripMargin)
+      spark.sql(
+        s"""
+           |insert into table $tableName
+           |values (10, false, CAST('binary data' AS BINARY), 
CAST('2022-02-02' AS DATE), 20.5, 6.28, 3.14, 2000, 'another string', 
CAST('2022-02-02 00:00:00' AS TIMESTAMP))
+           |""".stripMargin)
+
+      // collect column stats for table
+      for (i <- 1 to 10) {
+        val columnName = s"c$i"
+        val metadataStats = spark.sql(s"""call 
show_metadata_table_column_stats(table => '$tableName', targetColumns => 
'$columnName')""").collect()
+        assertResult(2) {

Review Comment:
   We can store the expected min-max values in an array and verify the min max 
result for each type here. 



-- 
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