![](/img/trans.png)
[英]How do you update an existing avro schema using apache avro SchemaBuilder?
[英]Recursive schema with avro (SchemaBuilder)
有可能制作一个递归的avro架构,比如
Schema schema = SchemaBuilder
.record("RecursiveItem")
.namespace("com.example")
.fields()
.name("subItem")
.type("RecursiveItem")
.withDefault(null) // not sure about that too...
.endRecord();
我这样使用它时得到一个StackOverflowError:
static class RecursiveItem {
RecursiveItem subItem;
}
RecursiveItem item1 = new RecursiveItem();
RecursiveItem item2 = new RecursiveItem();
item1.subItem = item2;
final DatumWriter<RecursiveItem> writer = new SpecificDatumWriter<>(schema);
// note: I actually want a binary output, but I started with some json code I found
ByteArrayOutputStream stream = new ByteArrayOutputStream();
final JsonEncoder encoder = EncoderFactory.get().jsonEncoder(schema, stream);
writer.write(rec1, encoder);
String json = stream.toString();
注意:如果我使用以下模式,我也会得到StackOverflowError:
Schema schema = ReflectData.get().getSchema(RecursiveItem.class);
警告:我找到了一个写的解决方案,但无法读取它晒太阳: - \\
我不确定是否理解,但我设法让它适用于:
应该使用ReflectDatumWriter
而不是SpecificDatumWriter
由于在编码时自动查找模式,我仍然遇到未找到模式的问题。 它查找具有自动派生名称空间+名称的模式。 在我的情况下,类是静态子类,应使用以下内容:
String cls = RecursiveItem.class.getSimpleName(); String pck = RecursiveItem.class.getPackage().getName(); if (RecursiveItem.class.getEnclosingClass() != null) // nested class pck = RecursiveItem.class.getEnclosingClass().getName() + "$";
要管理null,应使用以下模式
Schema schema0 = SchemaBuilder .record(cls) .namespace(pck) .fields() .name("subItem") .type().unionOf().nullType().and().type("RecursiveItem").endUnion() .nullDefault() .endRecord();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.