【问题标题】:PySpark how to get the partition name on query results?PySpark 如何在查询结果中获取分区名称?
【发布时间】:2020-04-01 08:45:08
【问题描述】:

我想检索查询结果中的分区名称。

所以如果我有这样的分区:

dataset/foo/
        ├─ key=value1
        ├─ key=value2
        └─ key=value3

我可以做这个查询

results = session.read.parquet('dataset/foo/key=value[12]') \
                      .select(['BAR']) \
                      .where('BAZ < 10')

一旦我这样做了,如何知道每个结果的分区来源?

确实,我只能从BAR 列中获取值。

感谢您的帮助

【问题讨论】:

    标签: pyspark pyspark-sql parquet


    【解决方案1】:

    在您的选择语句中包含key 列!

    #read foo directory as it is partiitoned so we can filter on the key
    results = session.read.parquet('foo/') \
                          .select(['BAR','key']) \
                          .filter((col("key") == "value1") & (col("BAZ") < '10')) 
    

    如果您想将来源 filename 添加到所有记录,请使用 input_file_name()

    from pyspark.sql.functions import *
    results = session.read.parquet('foo/') \
                          .select(['BAR','key'])\
                          .withColumn("input_file", input_file_name()) \
                          .filter((col("key") == "value1") & (col("BAZ") < '10'))
    

    【讨论】:

    • 如果我包含 key 列,我得到一个错误:cannot resolve «key» given input columns: [BAR, BAZ]
    • @bioinfornatics,请查看已编辑的答案!
    • 谢谢@shu。在这种情况下,spark 只读取必要的镶木地板文件或扫描给定根路径中的所有文件?
    • @bioinfornatics,spark 将只读取目录value[12] 文件,因为这是分区目录,如果未分区,则将读取所有文件!
    • 我发现rlike表达式允许使用"value[12]"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    相关资源
    最近更新 更多