指定分区时,Spark SQL saveAsTable与Hive不兼容

dun*_*98k 10 hive partitioning parquet apache-spark-sql

一种边缘情况,在Spark SQL中使用分区保存镶木桌时,

#schema definitioin
final StructType schema = DataTypes.createStructType(Arrays.asList(
    DataTypes.createStructField("time", DataTypes.StringType, true),
    DataTypes.createStructField("accountId", DataTypes.StringType, true),
    ...

DataFrame df = hiveContext.read().schema(schema).json(stringJavaRDD);

df.coalesce(1)
    .write()
    .mode(SaveMode.Append)
    .format("parquet")
    .partitionBy("year")
    .saveAsTable("tblclick8partitioned");
Run Code Online (Sandbox Code Playgroud)

Spark警告:

将分区数据源关系保存为Spark SQL特定格式的Hive Metastore,与Hive不兼容

在Hive中:

hive> describe tblclick8partitioned;
OK
col                     array<string>           from deserializer
Time taken: 0.04 seconds, Fetched: 1 row(s)
Run Code Online (Sandbox Code Playgroud)

显然模式不正确 - 但是如果我saveAsTable在没有分区的Spark SQL中使用,则可以毫无问题地查询表.

问题是如何在Spark SQL中使用分区信息与Hive兼容的镶木桌?

rys*_*rys 10

这是因为DataFrame.saveAsTable创建了RDD分区而不是Hive分区,解决方法是在调用DataFrame.saveAsTable之前通过hql创建表.SPARK-14927的一个例子如下:

hc.sql("create external table tmp.partitiontest1(val string) partitioned by (year int)")

Seq(2012 -> "a", 2013 -> "b", 2014 -> "c").toDF("year", "val")
  .write
  .partitionBy("year")
  .mode(SaveMode.Append)
  .saveAsTable("tmp.partitiontest1")
Run Code Online (Sandbox Code Playgroud)