Spark2 Can't write dataframe to parquet hive table : HiveFileFormat`. It doesn't match the specified format `ParquetFileFormat`.

一、概述

  出现该问题的原因是因为 如果用命令行创建的hive表,会根据hive的hive.default.fileformat,这个配置来规定hive文件的格式,其中fileformat一般有4中,分别是TextFile、SequenceFile、RCFile、ORC。默认情况下,不指定的话,是TextFile。那么如何在hive建表的时候指定呢? 就在建表语句最后加上stored as TextFile 或者stored as RCFile等等就可以了。

    但是df.write默认的format是parquet + snappy。如果表是用hive命令行创建的,就不符合格式,所以就会报错。如果表是提前不存在的,那么就不会有什么问题。

二、解决方法

 1、将parquet换成hive

.toDF()
.repartition($"col", $"col2", $"col3", $"col4")
.write
.format("parquet")
.mode(saveMode)
.partitionBy("col", "col2", "col3", "col4")
.saveAsTable("db.demo")

 2、方法二

  其实,还可以一种方式,就是使用insertInto,但是不太建议。因为在insertInto源码中,这样写道:

  insertInto插入的时候,是根据列的位置插入,而不是根据列的名字。表的format和设置的options也会被忽略。所以不是很推荐,但是也能达到目标。

df.write.insertInto("db.demo")
posted @ 2020-08-07 18:43  虎啸千峰  阅读(503)  评论(0编辑  收藏  举报