spark-reviews mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From hvanhovell <...@git.apache.org>
Subject [GitHub] spark pull request: [SPARK-14480][SQL] Simplify CSV parsing proces...
Date Wed, 27 Apr 2016 13:56:45 GMT
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/12268#discussion_r61260986
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/csv/CSVRelation.scala
---
    @@ -17,152 +17,162 @@
     
     package org.apache.spark.sql.execution.datasources.csv
     
    -import scala.util.control.NonFatal
    -
    -import org.apache.hadoop.fs.Path
    -import org.apache.hadoop.io.{NullWritable, Text}
    -import org.apache.hadoop.mapreduce.RecordWriter
    -import org.apache.hadoop.mapreduce.TaskAttemptContext
    +import java.io.CharArrayWriter
    +import java.nio.charset.{Charset, StandardCharsets}
    +
    +import com.univocity.parsers.csv.CsvWriter
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs.{FileStatus, Path}
    +import org.apache.hadoop.io.{LongWritable, NullWritable, Text}
    +import org.apache.hadoop.mapred.TextInputFormat
    +import org.apache.hadoop.mapreduce.{Job, RecordWriter, TaskAttemptContext}
     import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat
     
     import org.apache.spark.internal.Logging
     import org.apache.spark.rdd.RDD
     import org.apache.spark.sql._
     import org.apache.spark.sql.catalyst.InternalRow
    -import org.apache.spark.sql.catalyst.expressions.GenericMutableRow
    -import org.apache.spark.sql.execution.datasources.{OutputWriter, OutputWriterFactory,
PartitionedFile}
    +import org.apache.spark.sql.catalyst.expressions.JoinedRow
    +import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
    +import org.apache.spark.sql.execution.datasources._
    +import org.apache.spark.sql.sources._
     import org.apache.spark.sql.types._
    +import org.apache.spark.util.SerializableConfiguration
     
    -object CSVRelation extends Logging {
    -
    -  def univocityTokenizer(
    -      file: RDD[String],
    -      header: Seq[String],
    -      firstLine: String,
    -      params: CSVOptions): RDD[Array[String]] = {
    -    // If header is set, make sure firstLine is materialized before sending to executors.
    -    file.mapPartitions { iter =>
    -      new BulkCsvReader(
    -        if (params.headerFlag) iter.filterNot(_ == firstLine) else iter,
    -        params,
    -        headers = header)
    -    }
    -  }
    +/**
    + * Provides access to CSV data from pure SQL statements.
    + */
    +class DefaultSource extends FileFormat with DataSourceRegister {
    +
    +  override def shortName(): String = "csv"
    +
    +  override def toString: String = "CSV"
    +
    +  override def hashCode(): Int = getClass.hashCode()
    +
    +  override def equals(other: Any): Boolean = other.isInstanceOf[DefaultSource]
     
    -  def csvParser(
    -      schema: StructType,
    -      requiredColumns: Array[String],
    -      params: CSVOptions): Array[String] => Option[InternalRow] = {
    -    val schemaFields = schema.fields
    -    val requiredFields = StructType(requiredColumns.map(schema(_))).fields
    -    val safeRequiredFields = if (params.dropMalformed) {
    -      // If `dropMalformed` is enabled, then it needs to parse all the values
    -      // so that we can decide which row is malformed.
    -      requiredFields ++ schemaFields.filterNot(requiredFields.contains(_))
    +  override def inferSchema(
    +      sparkSession: SparkSession,
    +      options: Map[String, String],
    +      files: Seq[FileStatus]): Option[StructType] = {
    +    val csvOptions = new CSVOptions(options)
    +
    +    // TODO: Move filtering.
    +    val paths = files.filterNot(_.getPath.getName startsWith "_").map(_.getPath.toString)
    +    val rdd = createBaseRdd(sparkSession, csvOptions, paths)
    +    val schema = if (csvOptions.inferSchemaFlag) {
    +      InferSchema.infer(rdd, csvOptions)
         } else {
    -      requiredFields
    -    }
    -    val safeRequiredIndices = new Array[Int](safeRequiredFields.length)
    -    schemaFields.zipWithIndex.filter {
    -      case (field, _) => safeRequiredFields.contains(field)
    -    }.foreach {
    -      case (field, index) => safeRequiredIndices(safeRequiredFields.indexOf(field))
= index
    -    }
    -    val requiredSize = requiredFields.length
    -    val row = new GenericMutableRow(requiredSize)
    -
    -    (tokens: Array[String]) => {
    -      if (params.dropMalformed && schemaFields.length != tokens.length) {
    -        logWarning(s"Dropping malformed line: ${tokens.mkString(params.delimiter.toString)}")
    -        None
    -      } else if (params.failFast && schemaFields.length != tokens.length) {
    -        throw new RuntimeException(s"Malformed line in FAILFAST mode: " +
    -          s"${tokens.mkString(params.delimiter.toString)}")
    +      // By default fields are assumed to be StringType
    +      val filteredRdd = rdd.mapPartitions(CSVUtils.filterCommentAndEmpty(_, csvOptions))
    +      val firstLine = filteredRdd.first()
    +      val firstRow = UnivocityParser.tokenizeLine(firstLine, csvOptions)
    +      val header = if (csvOptions.headerFlag) {
    +        firstRow
           } else {
    -        val indexSafeTokens = if (params.permissive && schemaFields.length >
tokens.length) {
    -          tokens ++ new Array[String](schemaFields.length - tokens.length)
    -        } else if (params.permissive && schemaFields.length < tokens.length)
{
    -          tokens.take(schemaFields.length)
    -        } else {
    -          tokens
    -        }
    -        try {
    -          var index: Int = 0
    -          var subIndex: Int = 0
    -          while (subIndex < safeRequiredIndices.length) {
    -            index = safeRequiredIndices(subIndex)
    -            val field = schemaFields(index)
    -            // It anyway needs to try to parse since it decides if this row is malformed
    -            // or not after trying to cast in `DROPMALFORMED` mode even if the casted
    -            // value is not stored in the row.
    -            val value = CSVTypeCast.castTo(
    -              indexSafeTokens(index),
    -              field.dataType,
    -              field.nullable,
    -              params.nullValue)
    -            if (subIndex < requiredSize) {
    -              row(subIndex) = value
    -            }
    -            subIndex = subIndex + 1
    -          }
    -          Some(row)
    -        } catch {
    -          case NonFatal(e) if params.dropMalformed =>
    -            logWarning("Parse exception. " +
    -              s"Dropping malformed line: ${tokens.mkString(params.delimiter.toString)}")
    -            None
    -        }
    +        firstRow.zipWithIndex.map { case (value, index) => s"C$index" }
    +      }
    +      val schemaFields = header.map { fieldName =>
    +        StructField(fieldName.toString, StringType, nullable = true)
           }
    +      StructType(schemaFields)
         }
    +    Some(schema)
       }
     
    -  def parseCsv(
    -      tokenizedRDD: RDD[Array[String]],
    -      schema: StructType,
    -      requiredColumns: Array[String],
    -      options: CSVOptions): RDD[InternalRow] = {
    -    val parser = csvParser(schema, requiredColumns, options)
    -    tokenizedRDD.flatMap(parser(_).toSeq)
    +  override def prepareWrite(
    +      sparkSession: SparkSession,
    +      job: Job,
    +      options: Map[String, String],
    +      dataSchema: StructType): OutputWriterFactory = {
    +    val conf = job.getConfiguration
    +    val csvOptions = new CSVOptions(options)
    +    csvOptions.compressionCodec.foreach { codec =>
    +      CompressionCodecs.setCodecConfiguration(conf, codec)
    --- End diff --
    
    Just out of curiosity can we also read compressed csv files?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


Mime
View raw message