簡體   English   中英

使用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);

警告:我找到了一個寫的解決方案,但無法讀取它曬太陽: - \\

我不確定是否理解,但我設法讓它適用於:

  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(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM