我使用 Scala 的 Avro 的 Java API,想知道是否有一种简单的编程方法可以使用 Avro GenericRecord / SchemaBuilder API 将字段添加到现有记录模式?
没有简单的方法 - 但我确切地知道你想做什么。
下面是动态扩展现有架构(例如 SchemaBuilder)的示例。
Schema schema = SchemaBuilder
.record("schema_base").namespace("com.namespace.test")
.fields()
.name("longField").type().longType().noDefault()
.name("stringField").type().stringType().noDefault()
.name("booleanField").type().booleanType().noDefault()
.name("optionalStringColumn").type().optional().stringType()
.endRecord();
List<Schema.Field> field_list = schema.getFields();
ArrayList<Schema.Field> new_list = new ArrayList();
//create a new "empty" schema
//public static Schema createRecord(String name, String doc, String namespace, boolean isError) {
Schema s2 = Schema.createRecord("new_schema", "info", "com.namespace.test", false);
//add existing fields
for(Schema.Field f : field_list) {
//f.schema() here is really type "schema" like long or string, not a link back to a custom schema
Schema.Field ff = new Schema.Field(f.name(), f.schema(), f.doc(), f.defaultVal());
new_list.add(ff);
}
//this here is just to show how to create an optional string, its a union of null and string types
ArrayList<Schema> optionalString = new ArrayList<>();
optionalString.add(Schema.create(Schema.Type.NULL));
optionalString.add(Schema.create(Schema.Type.STRING));
//add the new 3 test fields in as optional string types
//default value here appears arbitrary, when you write the record if its not optional it doesn't //pick up default value
String[] sArray = {"test", "test2", "test3"};
for(String s : sArray) {
Schema.Field f = new Schema.Field( s, Schema.createUnion(optionalString), s, "null");
new_list.add(f);
}
s2.setFields(new_list);
Run Code Online (Sandbox Code Playgroud)
您不能只在现有架构上设置字段,因为一旦它们存在,架构就会被锁定。
注意:请小心默认值 - 如果类型不匹配,所有内容都会正常写入,但您将无法读取 avro 文件!
| 归档时间: |
|
| 查看次数: |
4447 次 |
| 最近记录: |