WangGuangxin commented on a change in pull request #24043: [SPARK-11412][SQL] 
Support merge schema for ORC
URL: https://github.com/apache/spark/pull/24043#discussion_r291839328
 
 

 ##########
 File path: 
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/orc/OrcUtils.scala
 ##########
 @@ -82,14 +83,95 @@ object OrcUtils extends Logging {
       : Option[StructType] = {
     val ignoreCorruptFiles = sparkSession.sessionState.conf.ignoreCorruptFiles
     val conf = sparkSession.sessionState.newHadoopConf()
-    // TODO: We need to support merge schema. Please see SPARK-11412.
     files.toIterator.map(file => readSchema(file.getPath, conf, 
ignoreCorruptFiles)).collectFirst {
       case Some(schema) =>
         logDebug(s"Reading schema from file $files, got Hive schema string: 
$schema")
         
CatalystSqlParser.parseDataType(schema.toString).asInstanceOf[StructType]
     }
   }
 
+  /**
+   * Read single ORC file schema using native version of ORC
+   */
+  def singleFileSchemaReader(file: String, conf: Configuration, 
ignoreCorruptFiles: Boolean)
+      : Option[StructType] = {
+    OrcUtils.readSchema(new Path(file), conf, ignoreCorruptFiles)
+      .map(s => 
CatalystSqlParser.parseDataType(s.toString).asInstanceOf[StructType])
+  }
+
+  /**
+   * Figures out a merged ORC schema with a distributed Spark job.
+   */
+  def mergeSchemasInParallel(
+      sparkSession: SparkSession,
+      files: Seq[FileStatus],
+      singleFileSchemaReader: (String, Configuration, Boolean) => 
Option[StructType])
+      : Option[StructType] = {
+    val serializedConf = new 
SerializableConfiguration(sparkSession.sessionState.newHadoopConf())
+
+    val filePaths = files.map(_.getPath.toString)
+
+    // Set the number of partitions to prevent following schema reads from 
generating many tasks
+    // in case of a small number of orc files.
+    val numParallelism = Math.min(Math.max(filePaths.size, 1),
+      sparkSession.sparkContext.defaultParallelism)
+
+    val ignoreCorruptFiles = sparkSession.sessionState.conf.ignoreCorruptFiles
+
+    // Issues a Spark job to read ORC schema in parallel.
+    val partiallyMergedSchemas =
+      sparkSession
+        .sparkContext
+        .parallelize(filePaths, numParallelism)
+        .mapPartitions { iterator =>
+          // Reads Orc schema in multi-threaded manner.
+          val partFiles = iterator.toSeq
+          val schemas = ThreadUtils.parmap(partFiles, "readingOrcSchemas", 8) 
{ currentFile =>
+            singleFileSchemaReader(currentFile, serializedConf.value, 
ignoreCorruptFiles)
+          }.flatten
+
+          if (schemas.isEmpty) {
+            Iterator.empty
+          } else {
+            var mergedSchema = schemas.head
+            schemas.tail.foreach { schema =>
+              try {
+                mergedSchema = mergedSchema.merge(schema)
+              } catch { case cause: SparkException =>
+                throw new SparkException(
+                  s"Failed merging schema:\n${schema.treeString}", cause)
+              }
+            }
+            Iterator.single(mergedSchema)
+          }
+        }.collect()
+
+    if (partiallyMergedSchemas.isEmpty) {
+      None
+    } else {
+      var finalSchema = partiallyMergedSchemas.head
+      partiallyMergedSchemas.tail.foreach { schema =>
+        try {
+          finalSchema = finalSchema.merge(schema)
+        } catch { case cause: SparkException =>
+          throw new SparkException(
+            s"Failed merging schema:\n${schema.treeString}", cause)
+        }
+      }
+      Some(finalSchema)
+    }
+  }
+
+  def inferSchema(sparkSession: SparkSession, files: Seq[FileStatus], options: 
Map[String, String])
+      : Option[StructType] = {
 
 Review comment:
   > So, this function is used in `native` ORC readers 
(OrcFileFormat/OrcTable), and `hive` OrcFileFormat has its own implementation 
of `inferSchema`, right?
   
   Yes. Do you think it's necessary to refactor this function?

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscr...@spark.apache.org
For additional commands, e-mail: reviews-h...@spark.apache.org

Reply via email to