Spark 数据框列命名约定/限制

Spark dataframe column naming conventions / restrictions

我 运行 现在多次遇到我的 (Py)Spark 列名称的默认命名问题(从收到的 .csv 文件导入)。似乎与 Spark 混淆的是 MixedCase 之类的东西。或 - 在列名中。所以我决定找出实际保存的列名,并找到以下内容:

This website 似乎建议仅使用小写名称:

Hive stores the table, field names in lowercase in Hive Metastore. Spark preserves the case of the field name in Dataframe, Parquet Files. When a table is created/accessed using Spark SQL, Case Sensitivity is preserved by Spark storing the details in Table Properties (in hive metastore). This results in a weird behavior when parquet records are accessed thru Spark SQL using Hive Metastore.

Amazon Athena 似乎证实了这一点,并补充说“_”是唯一保存的特殊字符:

... but Spark requires lowercase table and column names.

Athena table, view, database, and column names cannot contain special characters, other than underscore (_).

我从中得到的是,如果可能的话,我应该尝试只使用小写的列名,并使用 _ 作为单词之间的分隔符,以确保最大的交叉兼容性可能出现在我的 Spark 工作流中的工具。 这是否正确?是否有理由更喜欢 space 而不是下划线,还有什么要考虑的吗?

我意识到在很多情况下,我 可能 在将所有列重命名为以上模式时做得太过头了 - 但是,我宁愿避免 运行 命名- 在我的项目中间出现相关问题,因为我发现这些错误有时很难调试。

将文件保存为Parquet格式时,不能使用空格和一些特定字符。我 运行 遇到类似的从 CSV 读取和写入 Parquet 的问题。以下代码为我解决了这个问题:

# Column headers: lower case + remove spaces and the following characters: ,;{}()=  
newColumns = []
problematic_chars = ',;{}()='
for column in df.columns:
    column = column.lower()
    column = column.replace(' ', '_')
    for c in problematic_chars:
        column = column.replace(c, '')
    newColumns.append(column)
df = df.toDF(*newColumns)

所以是的,如果您的目标是确保最大的交叉兼容性,您应该确保您的列名全部小写,仅以 _ 作为分隔符。