如何将Avro Schema对象转换为spark中的StructType

Dus*_*ngh 4 schema avro apache-spark rdd

我有一个类型为Row的RDD,即RDD [Row]和avro架构对象.我需要使用此信息创建一个数据帧.

我需要将avro架构对象转换为StructType以创建DataFrame.

你能帮忙吗?

Kra*_*tam 5

com.databricks.spark.avro有一个类来帮助你解决这个问题

 StructType requiredType = (StructType) SchemaConverters.toSqlType(AvroClass.getClassSchema()).dataType();
Run Code Online (Sandbox Code Playgroud)

请通过以下具体示例:http://bytepadding.com/big-data/spark/read-write-parquet-files-using-spark/


小智 5

在 pyspark 2.4.7 中,我的解决方案是使用 avroschema 创建一个空数据帧,然后从此空数据帧中获取 StructType 对象。

with open('/path/to/some.avsc','r') as avro_file:
    avro_scheme = avro_file.read()

df = spark\
    .read\
    .format("avro")\
    .option("avroSchema", avro_scheme)\
    .load()

struct_type = df.schema

Run Code Online (Sandbox Code Playgroud)


cha*_*has 5

Wisnia 的答案有效,但仅供参考,我和我的同事想出的另一个解决方案如下:

avro_schema = "..."

java_schema_type = spark._jvm.org.apache.spark.sql.avro.SchemaConverters.toSqlType(
    spark._jvm.org.apache.avro.Schema.Parser().parse(avro_schema)
)

java_struct_schema = java_schema_type.dataType()
struct_json_schema = java_struct_schema.json()
json_schema_obj = json.loads(struct_json_schema)
schema = StructType.fromJson(json_schema_obj)
Run Code Online (Sandbox Code Playgroud)