1.将DataFrame数据如何写入到Hive表中?
2.通过那个API实现创建spark临时表?
3.如何将DataFrame数据写入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()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分区表了