相关的资源文件地址
链接:https://pan.baidu.com/s/1QGQIrVwg56g9eF16ERSLwQ
提取码:7v8n
spark.read().table() 可以操作内存中的某张表,也可以操作hive中的某张表,
如果sparksession开启了hive支持,就操作的是hive中的表
代码示例
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SaveMode;
import org.apache.spark.sql.SparkSession;
public class test12 {
public static void main(String[] args) {
SparkSession spark = SparkSession
.builder()
.config("spark.driver.host", "localhost")
.appName("TableDatasourceTest")
.master("local")
//开启hive支持
.enableHiveSupport()
.getOrCreate();
spark.sparkContext().setLogLevel("ERROR");
//1: 将json文件数据保存到spark的table中
Dataset<Row> df = spark.read().json(Utils.BASE_PATH + "/people.json");
df.show();
//设置当前要操作的数据库 dict,没有指定的话,默认操作的default数据库
spark.catalog().setCurrentDatabase("dict");
//显示 dict库的所有表
spark.catalog().listTables().show();
//保存到hive中
df.write().mode(SaveMode.Append).saveAsTable("person");
//显示 dict库的所有表
spark.catalog().listTables().show();
// +-----------+--------+-----------+---------+-----------+
// | name|database|description|tableType|isTemporary|
// +-----------+--------+-----------+---------+-----------+
// | person| dict| null| MANAGED| false|
// +-----------+--------+-----------+---------+-----------+
//读取hive中的某张表
Dataset<Row> tableDF = spark.read().table("person");
tableDF.show();
//从临时视图中读取
df.createOrReplaceTempView("person_2");
Dataset<Row> viewDF = spark.read().table("person_2");
viewDF.show();
// +---+-------+
// |age| name|
// +---+-------+
// | 29|Michael|
// | 30| Andy|
// | 19| Justin|
// +---+-------+
spark.stop();
}
}
如果保存到hive时,如果出现以下错误
The format of the existing table dict.person_3 is `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
df.write.format("Hive").mode(SaveMode.Append).saveAsTable("person")
将format设置为Hive以后,无论hive建表的时候,使用的fileformat使用的是哪一种,都是没有关系的
方法2
df.createOrReplaceTempView("temp_tab")
spark.sql("insert into person select * from temp_tab")