使用null默认值编码avro枚举时遇到问题

时间:2015-05-27 23:41:31

标签: java avro

org.apache.avro.UnresolvedUnionException: Not in union ["null",{"type":"enum","name":"document_change_type","namespace":"document","symbols":["create","update","delete"]}]: create

我正在为此字段传递字符串create,并且它抛出了上述异常。

create是枚举的3个可接受值之一,是什么导致异常?

1 个答案:

答案 0 :(得分:6)

假设您的avro架构看起来像这样:

{
  "type" : "record",
  "namespace" : "document",
  "name" : "document_details",
  "fields" : [
              { "name" : "documentName" , "type" : "string" },
              {"name" : "documentChange" , 
                        "type" : ["null", 
                                  {"type" : "enum",
                                  "namespace" : "document",
                                   "name" : "documentChangeType",                                
                                   "symbols" :["create","update","delete"]
                                   }]
               }            
             ]
}

您可以在代码中为此架构创建记录:

  GenericRecord documentDetailsRecord = new GenericData.Record(schema);
  GenericEnumSymbol enumSymbol = new GenericData.EnumSymbol(schema.getField("documentChange").schema().getTypes().get(1), "create");
  e2.put("documentName", "someDocumentName");
  e2.put("documentChange",enumSymbol);

您可以按如下方式获取所有联合字段的架构列表:

schema.getField(<unionFieldName>).schema().getTypes()