apache-spark - 如何在配置单元表中插入具有地图列的数据框
问题描述
我有一个包含多列的数据框,其中一列是 map(string,string) 类型。我可以打印这个数据框,其列作为地图,将数据作为地图(“PUN”->“Pune”)。我想将此数据框写入配置单元表(存储为 avro),该表具有与类型映射相同的列。
Df.withcolumn("cname", lit("Pune"))
withcolumn("city_code_name", map(lit("PUN"), col("cname"))
Df.show(false)
//table - created external hive table..stored as avro..with avro schema
删除此地图类型列后,我可以将数据框保存到 hive avro 表。
保存到蜂巢表的方法:
- spark.save - 保存 avro 文件
- spark.sql - 使用 avro 文件位置在 hive 表上创建分区
解决方案
test("Insert MapType.valueContainsNull == false") {
val schema = StructType(Seq(
StructField("m", MapType(StringType, StringType, valueContainsNull = false))))
val rowRDD = spark.sparkContext.parallelize(
(1 to 100).map(i => Row(Map(s"key$i" -> s"value$i"))))
val df = spark.createDataFrame(rowRDD, schema)
df.createOrReplaceTempView("tableWithMapValue")
sql("CREATE TABLE hiveTableWithMapValue(m Map <STRING, STRING>)")
sql("INSERT OVERWRITE TABLE hiveTableWithMapValue SELECT m FROM tableWithMapValue")
checkAnswer(
sql("SELECT * FROM hiveTableWithMapValue"),
rowRDD.collect().toSeq)
sql("DROP TABLE hiveTableWithMapValue")
}
另外,如果您想要保存选项,那么您可以尝试使用 saveAsTable,如此处所示
Seq(9 -> "x").toDF("i", "j")
.write.format("hive").mode(SaveMode.Overwrite).option("fileFormat", "avro").saveAsTable("t")
yourdataframewithmapcolumn.write.partitionBy 是创建分区的方式。
推荐阅读
- sql - Sql - 非布尔表达式错误
- mysql - (1193,“未知系统变量'explicit_defaults_for_timestamp'”)[SQL:'SELECT @@explicit_defaults_for_timestamp']
- javascript - 如何在html表格中显示一个json数组
- java - Java 发送带有客户端身份验证的 HTTP Post
- excel - 无法将 Selenium 与公司修改的浏览器一起使用
- java - 尝试...catch 循环未捕获异常
- java - 替换 Anonymous new Runnable() 的 lambda 是如何工作的?
- arrays - 简单的 PowerShell 问题 - 如何将对象转换为数组列表
- google-drive-api - Google GDoc - 没有可用的预览
- node.js - 使用 querySelectorAll,在某些情况下如何捕获属性,在其他情况下如何捕获整个元素?