1.将DataFrame数据如何写入到Hive表中?
2.通过那个API实现创建spark临时表?
3.如何将DataFrame数据写入hive指定数据表的分区中?


下面语句是向指定数据库数据表中写入数据:

  1. case class Person(name:String,col1:Int,col2:String)
  2. val sc = new org.apache.spark.SparkContext   
  3. val hiveContext = new org.apache.spark.sql.hive.HiveContext(sc)
  4. import hiveContext.implicits._
  5. hiveContext.sql("use DataBaseName")
  6. val data = sc.textFile("path").map(x=>x.split("\\s+")).map(x=>Person(x(0),x(1).toInt,x(2)))
  7. 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分区表中。具体操作如下:

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


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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-08-14
  • 2021-11-28
  • 2021-05-18
  • 2022-12-23
  • 2021-04-20
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-05-17
  • 2021-06-16
  • 2022-12-23
  • 2021-09-05
  • 2022-12-23
相关资源
相似解决方案