【问题标题】:Recursive schema with avro (SchemaBuilder)带有 avro 的递归模式 (SchemaBuilder)
【发布时间】:2019-06-20 07:56:51
【问题描述】:

是否可以制作一个递归的 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);

【问题讨论】:

    标签: java avro recursive-datastructures


    【解决方案1】:

    警告:我找到了可以写的解决方案,但无法阅读:-\

    我不确定是否真的理解,但我设法使它适用于:

    1. 应使用ReflectDatumWriter 而不是SpecificDatumWriter

    2. 由于在编码时自动查找架构,我仍然遇到架构未找到的问题。它查找具有自动派生的命名空间+名称的模式。在我的类是静态子类的情况下,应该使用以下内容:

      String cls = RecursiveItem.class.getSimpleName();
      String pck = RecursiveItem.class.getPackage().getName();
      if (RecursiveItem.class.getEnclosingClass() != null) // nested class
        pck = RecursiveItem.class.getEnclosingClass().getName() + "$";
      
    3. 要管理 null,应使用以下架构

      Schema schema0 = SchemaBuilder
        .record(cls)
        .namespace(pck)
        .fields()
        .name("subItem")
        .type().unionOf().nullType().and().type("RecursiveItem").endUnion()
        .nullDefault()
        .endRecord();
      

    【讨论】:

      猜你喜欢
      • 2021-10-04
      • 1970-01-01
      • 2019-06-09
      • 2021-12-19
      • 2018-04-01
      • 1970-01-01
      • 2020-07-20
      • 2016-10-23
      • 2018-10-25
      相关资源
      最近更新 更多