如何在spark-csv中写入“DATE”数据类型

时间:2016-11-01 08:01:41

标签: apache-spark spark-dataframe spark-csv databricks

我有类似的数据。

no,full_name,Ocupation,DOB
1,Eugene Perry,Physical Therapy Assistant,11/22/1972
2,Scott Evans,Account Executive,8/25/1961
3,Harold Porter,Community Outreach Specialist,4/5/1986
4,Roger Turner,Account Coordinator,12/24/1989
5,Patrick Freeman,Geological Engineer,2/11/1990
6,Jonathan Hart,Safety Technician I,7/24/1963
7,Susan Jenkins,Nurse,4/17/1967
8,Jason Graham,Internal Auditor,10/18/1966
9,Mark Wells,VP Marketing,2/20/1990

我的代码与此相似:(Java)

 SparkSession spark = SparkSession
                .builder()
                .appName("Java Spark SQL Example")
                .config("spark.some.config.option", "some-value")
                .config("spark.sql.warehouse.dir", "file:///C:/tmp/") 
                .getOrCreate();

       StructType Const = new StructType(new StructField[] {
            new StructField("no", DataTypes.IntegerType, true, Metadata.empty()),
            new StructField("full_name", DataTypes.StringType, true, Metadata.empty()),
            new StructField("Ocupation", DataTypes.StringType, true, Metadata.empty()),
            new StructField("DOB", DataTypes.DateType, true, Metadata.empty())
        });
                Dataset<Row> Tem  =  spark.read().format("com.databricks.spark.csv")
                        .schema(Const).option("header", "true").option("delimiter", ",").option("dateFormat", "MM/DD/YYYY")
                        .load("E:\\Datasets\\people.csv");

                Tem.show();
                Tem.printSchema();
                Tem.coalesce(1).write()
                    .format("com.databricks.spark.csv")
                    .option("header", "true").option("dateFormat", "MM/DD/YYYY")
                    .save("E:\\Datasets\\output");

上面的代码工作正常,没有错误,但DATE数据类型(“DOB”)列未正确打印在平面文件中。

我的实际结果是:

no,full_name,Ocupation,DOB
1,Eugene Perry,Physical Therapy Assistant,724
2,Scott Evans,Account Executive,-3287
3,Harold Porter,Community Outreach Specialist,5841
4,Roger Turner,Account Coordinator,6940
5,Patrick Freeman,Geological Engineer,7304
6,Jonathan Hart,Safety Technician I,-2559

即使我正在使用.option("dateFormat", "MM/DD/YYYY")

请参阅上一栏,“DATE”格式在.csv文件中无效。 我不确定我错过了什么。

1 个答案:

答案 0 :(得分:0)

此问题与spark版本2.0.0有关。

升级到spark 2.0.1并使用内置的spark CSV格式解决了这个问题。

参考link