Question
How to convert binary to string (UUID) without UDF in Apache Spark (PySpark)?
I can't find a way to convert a binary to a string representation without using a UDF. Is there a way with native PySpark functions and not a UDF?
from pyspark.sql import DataFrame, SparkSession
import pyspark.sql.functions as F
import uuid
from pyspark.sql.types import Row, StringType
spark_test_instance = (SparkSession
.builder
.master('local')
.getOrCreate())
df: DataFrame = spark_test_instance.createDataFrame([Row()])
df = df.withColumn("id", F.lit(uuid.uuid4().bytes))
df = df.withColumn("length", F.length(df["id"]))
uuidbytes_to_str = F.udf(lambda x: str(uuid.UUID(bytes=bytes(x), version=4)), StringType())
df = df.withColumn("id_str", uuidbytes_to_str(df["id"]))
df = df.withColumn("length_str", F.length(df["id_str"]))
df.printSchema()
df.show(1, truncate=False)
gives:
root
|-- id: binary (nullable = false)
|-- length: integer (nullable = false)
|-- id_str: string (nullable = true)
|-- length_str: integer (nullable = false)
+-------------------------------------------------+------+------------------------------------+----------+
|id |length|id_str |length_str|
+-------------------------------------------------+------+------------------------------------+----------+
|[0A 35 DC 67 13 C8 47 7E B0 80 9F AB 98 CA FA 89]|16 |0a35dc67-13c8-477e-b080-9fab98cafa89|36 |
+-------------------------------------------------+------+------------------------------------+----------+
3 72
3