如何使用它的模式从Spark数据框创建配置单元表? [英] How to create hive table from Spark data frame, using its schema?

查看:115
本文介绍了如何使用它的模式从Spark数据框创建配置单元表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Spark数据框架构创建一个配置表格。我可以怎么做?



对于固定列,我可以使用:

  val CreateTable_query =Create Table my table(a string,b string,c double)
sparksession.sql(CreateTable_query)

但是我的数据框中有很多列,所以有自动生成这样的查询的方法吗?

解决方案<假设您正在使用Spark 2.1.0或更高版本,并且my_DF是您的数据框,

  // get将模式拆分为以逗号分隔的字段 - 数据类型对的字符串
StructType my_schema = my_DF.schema();
StructField [] fields = my_schema.fields();
String fieldStr =;
for(StructField f:fields){
fieldStr + = f.name()++ f.dataType()。typeName()+,;


//如果已经创建了表,则删除表
spark.sql(drop table if exists my_table);
//使用dataframe模式创建表
spark.sql(create table my_table(+ fieldStr.subString(0,fieldStr.length() - 1)+
)row以'|'location'/ my / hdfs / location'结尾的格式定界字段);
//将数据帧数据写入创建的Hive表的$ hdfs位置
my_DF.write()
.format(com.databricks.spark.csv)
。选项(分隔符,|)
.mode(覆盖)
.save(/ my / hdfs / location);

另一种使用临时表的方法

  my_DF.createOrReplaceTempView( my_temp_table); 
spark.sql(drop drop if exists my_table);
spark.sql(create table my_table as select * from my_temp_table);


I want to create a hive table using my Spark dataframe's schema. How can I do that?

For fixed columns, I can use:

val CreateTable_query = "Create Table my table(a string, b string, c double)"
sparksession.sql(CreateTable_query) 

But I have many columns in my dataframe, so is there a way to automatically generate such query?

解决方案

Assuming, you are using Spark 2.1.0 or later and my_DF is your dataframe,

//get the schema split as string with comma-separated field-datatype pairs
StructType my_schema = my_DF.schema();
StructField[] fields = my_schema.fields();
String fieldStr = "";
for (StructField f : fields) {
fieldStr += f.name() + " " + f.dataType().typeName() + ",";
}

//drop the table if already created
spark.sql("drop table if exists my_table");
//create the table using the dataframe schema
spark.sql("create table my_table(" + fieldStr.subString(0,fieldStr.length()-1)+
") row format delimited fields terminated by '|' location '/my/hdfs/location'");
    //write the dataframe data to the hdfs location for the created Hive table
    my_DF.write()
    .format("com.databricks.spark.csv")
    .option("delimiter","|")
    .mode("overwrite")
    .save("/my/hdfs/location");

The other method using temp table

my_DF.createOrReplaceTempView("my_temp_table");
spark.sql("drop table if exists my_table");
spark.sql("create table my_table as select * from my_temp_table");

这篇关于如何使用它的模式从Spark数据框创建配置单元表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆