将StructType转换为Avro架构,使用databricks spark-avro

时间:2018-12-04 12:12:11

标签: apache-spark-sql schema avro databricks spark-avro

我正在使用databricks spark-avro将数据框架构转换为avro架构。返回的avro架构无法使用默认值。当我尝试从架构中创建通用记录时,这会引起问题。任何人都能以正确的方式使用此功能吗?

Dataset<Row> sellableDs = sparkSession.sql("sql query");
SchemaBuilder.RecordBuilder<Schema> rb = SchemaBuilder.record("testrecord").namespace("test_namespace");
Schema sc = SchemaConverters.convertStructToAvro(sellableDs.schema(), rb, "test_namespace");
System.out.println(sc.toString());
System.out.println(sc.getFields().get(0).toString());
String schemaString = sc.toString();
sellableDs.foreach(
    (ForeachFunction<Row>) row -> {
        Schema scEx = new Schema.Parser().parse(schemaString);
        GenericRecord gr;
        gr = new GenericData.Record(scEx);
        System.out.println("Generic record Created");
        int fieldSize = scEx.getFields().size();
        for (int i = 0; i < fieldSize; i++ ) {
            // System.out.println( row.get(i).toString());
            System.out.println("field: " + scEx.getFields().get(i).toString() + "::" + "value:" + row.get(i));
            gr.put(scEx.getFields().get(i).toString(), row.get(i));
            //i++;
        }
    }
);

这是df模式:

StructType(StructField(key,IntegerType,true), StructField(value,DoubleType,true))

这是avro转换的架构:

{"type":"record","name":"testrecord","namespace":"test_namespace","fields":[{"name":"key","type":["int","null"]},{"name":"value","type":["double","null"]}]}

1 个答案:

答案 0 :(得分:0)

问题在于类SchemaConverters不包含默认值,这是架构创建的一部分。您有2个选项,可以在创建记录之前修改架构以添加默认值,或者在创建一些值之前填充记录(它实际上可能是您行中的值)。例如null。这是一个如何使用您的架构创建记录的示例

import org.apache.avro.generic.GenericRecordBuilder 
import org.apache.avro.Schema
var schema = new Schema.Parser().parse("{\"type\":\"record\",\"name\":\"testrecord\",\"namespace\":\"test_namespace\",\"fields\":[{\"name\":\"key\",\"type\":[\"int\",\"null\"]},{\"name\":\"value\",\"type\":[\"double\",\"null\"]}]}")


var  builder = new GenericRecordBuilder(schema);

for (i <- 0 to schema.getFields().size() - 1 ) {
  builder.set(schema.getFields().get(i).name(), null)
}

var record = builder.build();
print(record.toString())