1

我正在尝试将 CSV 文件转换为镶木地板,并且我正在使用 Spark 来完成此操作。

SparkSession spark = SparkSession
    .builder()
    .appName(appName)
    .config("spark.master", master)
    .getOrCreate();

Dataset<Row> logFile = spark.read().csv("log_file.csv");
logFile.write().parquet("log_file.parquet");

现在的问题是我没有定义模式并且列看起来像这样(在 spark 中使用 printSchema() 显示的输出)

root
 |-- _c0: string (nullable = true)
 |-- _c1: string (nullable = true)
 |-- _c2: string (nullable = true)
 ....

csv 在第一行有名称,但我猜它们被忽略了,问题是只有几列是字符串,我也有整数和日期。

使用 Spark,基本上没有使用 avro 或其他任何东西(从未使用过 avro)。

我有哪些选择来定义架构以及如何定义?如果我需要以另一种方式编写镶木地板文件,那么只要它是一个快速简单的解决方案就没有问题。

(我使用 spark 独立测试/不知道 scala)

4

1 回答 1

6

尝试使用 .option("inferschema","true") 提供的 Spark-csv包。这将自动从数据中推断出架构。

您还可以使用 struct 类型为您的数据定义自定义架构,并使用.schema(schema_name)来在自定义架构的基础上读取。

val sqlContext = new SQLContext(sc)
val customSchema = StructType(Array(
    StructField("year", IntegerType, true),
    StructField("make", StringType, true),
    StructField("model", StringType, true),
    StructField("comment", StringType, true),
    StructField("blank", StringType, true)))

val df = sqlContext.read
    .format("com.databricks.spark.csv")
    .option("header", "true") // Use first line of all files as header
    .schema(customSchema)
    .load("cars.csv")
于 2017-01-22T01:03:19.300 回答