如何使用sparksql识别配置单元表中的分区列

6yjfywim  于 2021-06-27  发布在  Hive
关注(0)|答案(1)|浏览(574)

我正在尝试使用spark识别配置单元表中的分区列名。我可以使用show partitions然后解析resultset来提取分区列。但是,缺点是,如果某些故事中没有分区,show分区失败了。有没有更有机的方法来标识配置单元表中的分区列名。任何帮助都将不胜感激

  1. v_query="show partitions {}".format(table_name)
  2. a=self.spark.sql(v_query)
  3. val=a.rdd.map(list).first()
  4. val1=''.join(val)
  5. partition_list=[l.split('=')[0] for l in val1.split('/')]
9gm1akwq

9gm1akwq1#

如果表未分区,上述代码将失败。它会给你一个错误信息,如 "pyspark.sql.utils.AnalysisException: u'SHOW PARTITIONS is not allowed on a table that is not partitioned" 您可以在上使用Map操作 desc 命令获取分区列信息。

  1. >>> spark.sql("""desc db.newpartitiontable""").show(truncate=False)
  2. +-----------------------+---------+-------+
  3. |col_name |data_type|comment|
  4. +-----------------------+---------+-------+
  5. |city |string |null |
  6. |state |string |null |
  7. |country |string |null |
  8. |tran_date |string |null |
  9. |# Partition Information| | |
  10. |# col_name |data_type|comment|
  11. |tran_date |string |null |
  12. +-----------------------+---------+-------+
  13. partition_exists=spark.sql("""desc db.newpartitiontable""").rdd.map(lambda x:x[0]).filter(lambda x: x.startswith("# col_name")).collect()
  14. if len(partition_exists)>0:
  15. print("table is partitioned")
  16. partition_col=spark.sql("""show partitions test_dev_db.newpartitiontable""").rdd.map(lambda x:x[0]).map(lambda x : [l.split('=')[0] for l in x.split('/')]).first()
  17. print("Partition column is:",partition_col)
  18. else:
  19. print("table is not partitioned")
展开查看全部

相关问题