其他分享
首页 > 其他分享> > spark 将dataframe数据写入Hive分区表

spark 将dataframe数据写入Hive分区表

作者:互联网

1、将DataFrame数据写入到Hive表中

从DataFrame类中可以看到与hive表有关的写入Api有以下几个:

registerTempTable(tableName: String): Unit,
insertInto(tableName: String): Unit
insertInto(tableName: String, overwrite: Boolean): Unit
saveAsTable(tableName: String, source: String, mode: SaveMode, options: Map[String, String]): Unit

有很多重载函数,不一一列举
registerTempTable函数是创建spark临时表
insertInto函数是向表中写入数据,可以看出此函数不能指定数据库和分区等信息,不可以直接进行写入。
向hive数据仓库写入数据必须指定数据库,hive数据表建立可以在hive上建立,或者使用hiveContext.sql(“create table ....")
下面语句是向指定数据库数据表中写入数据:

case class Person(name:String,col1:Int,col2:String)
val sc = new org.apache.spark.SparkContext  
val hiveContext = new org.apache.spark.sql.hive.HiveContext(sc)
import hiveContext.implicits._
hiveContext.sql("use DataBaseName")
val data = sc.textFile("path").map(x=>x.split("\\s+")).map(x=>Person(x(0),x(1).toInt,x(2)))
data.toDF().insertInto("tableName")

创建一个case类将RDD中数据类型转为case类类型,然后通过toDF转换为DataFrame,调用insertInto函数时,首先指定数据库,使用的是hiveContext.sql("use DataBaseName")语句,就可以将DataFrame数据写入hive数据表中了

2、将DataFrame数据写入hive指定数据表的分区中

hive数据表建立可以在hive上建立,或者使用hiveContext.sql(“create table ...."),使用saveAsTable时数据存储格式有限,默认格式为parquet,可以指定为json,如果有其他格式指定,尽量使用语句来建立hive表。
将数据写入分区表的思路是:首先将DataFrame数据写入临时表,之后是由hiveContext.sql语句将数据写入hive分区表中。具体操作如下:

case class Person(name:String,col1:Int,col2:String)
val sc = new org.apache.spark.SparkContext  
val hiveContext = new org.apache.spark.sql.hive.HiveContext(sc)
import hiveContext.implicits._
hiveContext.sql("use DataBaseName")
val data = sc.textFile("path").map(x=>x.split("\\s+")).map(x=>Person(x(0),x(1).toInt,x(2)))
data.toDF().registerTempTable("table1")
hiveContext.sql("insert into table2 partition(date='2015-04-02') " +
"select name,col1,col2 from table1")

使用以上方式就可以将dataframe数据写入hive分区表了

标签:String,hiveContext,写入,hive,分区表,dataframe,sql,Hive,spark
来源: https://blog.51cto.com/u_15278282/2931946