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

Tho*_*mas 4 hive naming-conventions apache-spark pyspark amazon-athena

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

该网站似乎只建议使用小写名称:

Hive 将表、字段名称以小写形式存储在 Hive Metastore 中。Spark 保留了 Dataframe Parquet Files 中字段名称的大小写。当使用 Spark SQL 创建/访问表时,Spark 将详细信息存储在表属性中(在 hive 元存储中),从而保持区分大小写。当使用 Hive Metastore 通过 Spark SQL 访问镶木地板记录时,这会导致奇怪的行为。

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

...但 Spark 需要小写的表名和列名。

Athena 表、视图、数据库和列名称不能包含除下划线 (_) 之外的特殊字符。

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

我意识到在许多情况下,将所有列重命名为上述模式时我可能会过度使用它 - 但是,我宁愿避免在项目中间遇到与命名相关的问题,因为我发现这些错误有时难以调试。

Hoe*_*nie 5

When saving the file to Parquet format, you cannot use spaces and some specific characters. I ran into similar problems reading from CSV and writing to Parquet. The following code solved it for me:

# 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)
Run Code Online (Sandbox Code Playgroud)

So yes, if your goal is to ensure maximum cross compatibility, you should make sure your column names are all lowercase, with only _ as separator.