from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, LongType, TimestampType
from pyspark.sql import functions as F
import datetime
import re # Import the re module for regular expressions
def normalize_column_names(df):
"""
Normalizes column names in a PySpark DataFrame, including nested struct types.
Normalization rules:
- All letters are converted to lowercase.
- Spaces (" ") are replaced with underscores ("_").
- Hyphens ("-") are replaced with underscores ("_").
- CamelCase (e.g., "HereIsCamelCase") is converted to snake_case (e.g., "here_is_camel_case").
Args:
df (DataFrame): The input PySpark DataFrame.
Returns:
DataFrame: A new PySpark DataFrame with normalized column names.
"""
def _normalize_name(name):
"""Applies the naming rules to a single string."""
# 1. Replace spaces and hyphens with underscores
name = name.replace(" ", "_").replace("-", "_")
# 2. Convert camelCase to snake_case
# This regex looks for a lowercase letter or digit followed by an uppercase letter.
# It then inserts an underscore between them.
# Example: "someFunction" -> "some_Function"
name = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', name)
# 3. Convert the entire string to lowercase
name = name.lower()
return name
def _build_select_expressions(schema, prefix=""):
"""
Recursively builds a list of select expressions for column renaming.
Args:
schema (StructType): The current schema (or sub-schema) to process.
prefix (str): The current path prefix for nested columns (e.g., "element.tags.").
Returns:
list: A list of PySpark Column expressions.
"""
select_cols = []
for field in schema.fields:
original_field_name = field.name
normalized_field_name = _normalize_name(original_field_name)
# Construct the full path to the current column, using the original names
# because F.col() needs the original path to locate the column.
current_original_path = f"{prefix}{original_field_name}"
if isinstance(field.dataType, StructType):
# If it's a struct, recursively get expressions for its children
nested_expressions = _build_select_expressions(
field.dataType,
f"{current_original_path}." # Append original name for nested path
)
# Create a new struct with normalized child names and alias the struct itself
select_cols.append(F.struct(*nested_expressions).alias(normalized_field_name))
else:
# For non-struct types, just select and alias
select_cols.append(F.col(current_original_path).alias(normalized_field_name))
return select_cols
# Get the select expressions starting from the top-level schema
normalized_expressions = _build_select_expressions(df.schema)
# Select the columns with their new names to create the new DataFrame
return df.select(*normalized_expressions)
# --- Example Usage ---
if __name__ == "__main__":
spark = SparkSession.builder \
.appName("ColumnNameNormalizationCamelCase") \
.getOrCreate()
# 1. Define the original schema matching your example, plus some camelCase ones
original_schema = StructType([
StructField("id", StringType(), True),
StructField("authorizationSource", StringType(), True),
StructField("managedByTenants", ArrayType(StringType()), True),
StructField("element", StructType([
StructField("tenantId", StringType(), True),
StructField("tags", StructType([
StructField("KM-InternalCostCenter", StringType(), True),
StructField("KM-CostCenter", StringType(), True),
StructField("KM-CostCenterOwner", StringType(), True),
StructField("KM-OwnerEmail", StringType(), True),
StructField("KM-TechnicalEmail", StringType(), True),
StructField("KM-UsageDescription", StringType(), True),
StructField("KM-TicketID", StringType(), True),
StructField("KM-SupportContract", StringType(), True),
StructField("HereIsCamelCase", StringType(), True), # Added for test
StructField("SomeOtherColumn", StringType(), True), # Added for test
]), True),
StructField("anotherCamelCaseField", StringType(), True) # Added for test
]), True),
StructField("subscriptionId", StringType(), True),
StructField("tenantId", StringType(), True),
StructField("displayName", StringType(), True),
StructField("state", StringType(), True),
StructField("subscriptionPolicies", StructType([
StructField("locationPlacementId", StringType(), True),
StructField("quotaId", StringType(), True),
StructField("spendingLimit", StringType(), True),
StructField("SomeFunction", StringType(), True), # Added for test
]), True),
StructField("full_path", StringType(), True),
StructField("file_name", StringType(), True),
StructField("source_system", StringType(), True),
StructField("inserted_at", TimestampType(), True),
StructField("_metadata", StructType([
StructField("file_path", StringType(), True),
StructField("file_name", StringType(), True),
StructField("file_size", LongType(), True),
StructField("file_block_start", LongType(), True),
StructField("file_block_length", LongType(), True),
StructField("file_modification_time", TimestampType(), True),
StructField("metaDataField", StringType(), True), # Added for test
]), True),
])
# 2. Create sample data matching the schema
sample_data = [(
"ABC-123", "Source A", ["t1", "t2"],
("tenant_val1", {
"KM-InternalCostCenter": "CC1",
"KM-CostCenter": "Dept-X",
"KM-CostCenterOwner": "John Doe",
"KM-OwnerEmail": "john.doe@example.com",
"KM-TechnicalEmail": "tech@example.com",
"KM-UsageDescription": "Cloud Usage",
"KM-TicketID": "TICKET-001",
"KM-SupportContract": "Premium Plan",
"HereIsCamelCase": "camelValue1",
"SomeOtherColumn": "otherValue"
}, "anotherCamelValue"),
"sub-xyz", "global_tenant_id", "My Display Name", "Active",
("us-east-1", "high-quota", "unlimited", "func_output"),
"/data/raw/file-1.json", "file-1.json", "datalake", datetime.datetime.now(),
("/data/raw/file-1.json", "file-1.json", 1024, 0, 1024, datetime.datetime.now(), "metaValue")
)]
# 3. Create the DataFrame
df_original = spark.createDataFrame(sample_data, schema=original_schema)
print("--- Original DataFrame Schema ---")
df_original.printSchema()
df_original.show(truncate=False)
# 4. Apply the normalization function
df_normalized = normalize_column_names(df_original)
print("\n--- Normalized DataFrame Schema ---")
df_normalized.printSchema()
df_normalized.show(truncate=False)
# Stop SparkSession
spark.stop()