【问题标题】:Identify Partition Key Column from a table using PySpark使用 PySpark 从表中识别分区键列
【发布时间】:2019-11-22 11:02:03
【问题描述】:

我需要帮助来使用 PySpark 查找 Hive 表的唯一分区列名。该表可能有多个分区列,最好输出应该返回 Hive 表的分区列列表。

如果结果还包括分区列的数据类型,那就太好了。

任何建议都会有所帮助。

【问题讨论】:

    标签: python-2.7 pyspark pyspark-sql


    【解决方案1】:

    通过pyspark脚本的另一种简单方法。

    from pyspark.sql.types import *
    import pyspark.sql.functions as f
    from pyspark.sql import functions as F
    from pyspark.sql.functions import col, concat, lit
    
    descschema = StructType([ StructField("col_name", StringType())
                           ,StructField("data_type", StringType())
                           ,StructField("comment", StringType())])                  
    df = spark.sql(f"describe formatted serve.cust_transactions" )
    df2=df.where((f.col("col_name")== 'Part 0') | (f.col("col_name")== 'Part 2') | (f.col("col_name")== 'Name')).select(f.col('data_type'))
    df3 =df2.toPandas().transpose()
    display(df3)
    

    结果是:

    【讨论】:

      【解决方案2】:

      可以使用如下所示的desc来完成:

      df=spark.sql("""desc test_dev_db.partition_date_table""")
      >>> df.show(truncate=False)
      +-----------------------+---------+-------+
      |col_name               |data_type|comment|
      +-----------------------+---------+-------+
      |emp_id                 |int      |null   |
      |emp_name               |string   |null   |
      |emp_salary             |int      |null   |
      |emp_date               |date     |null   |
      |year                   |string   |null   |
      |month                  |string   |null   |
      |day                    |string   |null   |
      |# Partition Information|         |       |
      |# col_name             |data_type|comment|
      |year                   |string   |null   |
      |month                  |string   |null   |
      |day                    |string   |null   |
      +-----------------------+---------+-------+
      

      由于这张表是分区的,所以在这里你可以看到分区列信息以及它们的数据类型。

      您似乎只对分区列名及其各自的数据类型感兴趣。因此,我正在创建一个元组列表。

      partition_list=df.select(df.col_name,df.data_type).rdd.map(lambda x:(x[0],x[1])).collect()
      
      >>> print partition_list
      [(u'emp_id', u'int'), (u'emp_name', u'string'), (u'emp_salary', u'int'), (u'emp_date', u'date'), (u'year', u'string'), (u'month', u'string'), (u'day', u'string'), (u'# Partition Information', u''), (u'# col_name', u'data_type'), (u'year', u'string'), (u'month', u'string'), (u'day', u'string')]
      
      partition_details = [partition_list[index+1:] for index,item in enumerate(partition_list) if item[0]=='# col_name']
      
      >>> print partition_details
      [[(u'year', u'string'), (u'month', u'string'), (u'day', u'string')]]
      

      如果表未分区,它将返回空列表。希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-23
        • 2021-04-25
        • 2019-08-28
        • 1970-01-01
        • 2019-03-30
        • 1970-01-01
        • 1970-01-01
        • 2019-07-29
        相关资源
        最近更新 更多