首页 > 解决方案 > 如何在配置单元表中插入具有地图列的数据框

问题描述

我有一个包含多列的数据框,其中一列是 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 表。

保存到蜂巢表的方法:

  1. spark.save - 保存 avro 文件
  2. spark.sql - 使用 avro 文件位置在 hive 表上创建分区

标签: apache-sparkhadoophiveapache-spark-sqlcomplextype

解决方案


将此测试用例视为火花测试的示例

  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 是创建分区的方式。


推荐阅读