如何使用 Python 将 Spark 列中包含的 StringType 形式的二进制文件转换为 UUID 字符串?

问题描述 投票:0回答:1

我们正在使用 AWS Glue 构建一个组件,它将 Aurora RDS 中的表卸载到 CSV 文件,稍后必须将其转换为 Parquet。

要卸载,我们使用 SELECT * FROM TableA INTO OUTFILE S3 's3_path' FORMAT CSV HEADER 根据以下文档:https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Integrating.SaveIntoS3.html

在将此 CSV 转换为 Parquet 之前,所有以“cod_idef_”开头的列始终为二进制,并且必须转换为 UUID。但是,当使用 Spark 读取 CSV 文件时,它会将列推断为 StringType。

如何将这些列转换为 UUID 字符串?

我已经尝试过:

def binary_to_uuid(binary_val):
    if binary_val:
        return str(uuid.UUID(bytes=bytearray(binary_val)))
    else:
        return None
columns_to_convert = [col_name for col_name in df.columns if col_name.startswith("cod_idef")]

# Apply the UDF to each column
for col_name in columns_to_convert:
    df = df.withColumn(col_name, udf(binary_to_uuid, StringType())(col(col_name)))

编辑1: 这是一个示例,根据 user238607 的要求 二进制:

结果应该是: 00000000-8a3a-46b2-84c2-a227836ea168

python amazon-web-services apache-spark pyspark aws-glue
1个回答
0
投票

CSV(逗号分隔值)是一种基于文本的格式,它不支持二进制数据的直接表示。因此,您的文件应该具有该列的 StringType。您需要检查二进制列在 S3 上导出的文件中的外观。如果它是二进制数据的十六进制表示(例如

000000008a3a46b284c2a227836ea168
),那么您只需将其从十六进制转换为UUID:

# Define a UDF to parse the UUIDs from the hexadecimal strings
@udf(returnType=StringType())
def parse_uuid(hex_string):
    return str(uuid.UUID(hex_string))

# Load the CSV file into a DataFrame
df = spark.read.csv(csv_file, header=True, inferSchema=True)

# Apply the UDF to the 'uuid_binary' column to parse the UUIDs
df = df.withColumn("uuid", parse_uuid(df["uuid_binary"]))
© www.soinside.com 2019 - 2024. All rights reserved.