首页 > 解决方案 > 获取 Spark 写入 Hive Metastore 的所有新分区

问题描述

我有一个数据框,我使用 spark sql(使用动态分区)将其插入到现有的分区配置单元表中。写入数据框后,我想知道我的数据框刚刚在 hive 中创建的分区是什么。

我可以查询不同分区的数据帧,但它需要很长时间,因为它必须启动数据帧的整个沿袭。

我可以在写入配置单元之前保留数据帧,这样,写入操作和不同的 partition_column 操作发生在缓存的数据帧之上。但是我的数据框非常大,不想花更多的时间来坚持。

我知道所有分区信息都存储在 Hive Metastore 中。spark中是否有任何metastore api可以帮助仅检索创建的新分区?

标签: apache-sparkhiveapache-spark-sql

解决方案


您可以使用HiveMetastoreClient检索表的分区数据:

import org.apache.hadoop.hive.conf.HiveConf
import scala.collection.JavaConverters._
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient

val hiveConf = new HiveConf(spark.sparkContext.hadoopConfiguration, classOf[HiveConf])
val cli = new HiveMetaStoreClient(hiveConf)

/* Get list of partition values prior to DF insert */
val existingPartitions = cli.listPartitions("<db_name>", "<tbl_name>", Short.MaxValue).asScala.map(_.getValues.asScala.mkString(","))
/* Insert DF contents to table */
df.write.insertInto("<db_name>.<tbl_name>")
/* Fetch list of partition values again, and diff with previous list */
val newPartitions = cli.listPartitions("<db_name>", "<tbl_name>", Short.MaxValue).asScala.map(_.getValues.asScala.mkString(","))
val deltaPartitions = newPartitions.diff(existingPartitions)

推荐阅读