如何将数据添加到avro架构中的可重复字段?

时间:2015-07-07 16:03:56

标签: serialization schema deserialization file-format avro

我试图在没有代码生成的情况下测试avro serde和deserde(我使用代码生成完成了这项任务)。架构如下

{
"type": "record",
"name" : "person",
"namespace" : "avro",
"fields": [
    { "name" : "personname", "type": ["null","string"] },
    { "name" : "personId", "type": ["null","string"] },
    {  "name" : "Addresses", "type": {
        "type": "array",
        "items": [  {
          "type" : "record",
          "name" : "Address",
          "fields" : [
            { "name" : "addressLine1", "type": ["null", "string"] },
            { "name" : "addressLine2", "type": ["null", "string"] },
            { "name" : "city", "type": ["null", "string"] },
            { "name" : "state", "type": ["null", "string"] },
            { "name" : "zipcode", "type": ["null", "string"] }
            ]
        }]
        }
    },
    { "name" : "contact", "type" : ["null", "string"]}
]
}

我理解这是将数据添加到架构的方式。

Schema schema = new Schema.Parser().parse(new File("src/person.avsc.txt"));
GenericRecord person1 = new GenericData.Record(schema);
person1.put("personname", "goud");

但是如何添加城市,州等地址然后将其添加到地址?

GenericRecord address1 = new GenericData.Record(schema);
address1.put("city", "SanJose");

以上代码段不起作用。我试着调查GenericArray,但我无法理解它。

1 个答案:

答案 0 :(得分:0)

您需要在单独的模式中描述内部复杂类型("类型":"记录","名称":"地址") ,像这样:

e.keyCode

然后你可以创建一个内部对象:

if (+e.which >= 48 && +e.which <=90){ ... }

然后将您创建的内部对象添加到ArrayList。

最后,创建主对象并在其中添加所有这些人员。

以下是java中的完整示例:

{
  "type" : "record",
  "name" : "Address",
  "fields" : [
    { "name" : "addressLine1", "type": ["null", "string"] },
    { "name" : "addressLine2", "type": ["null", "string"] },
    { "name" : "city", "type": ["null", "string"] },
    { "name" : "state", "type": ["null", "string"] },
    { "name" : "zipcode", "type": ["null", "string"] }
  ]
}

结果:

Schema innerSchema = new Schema.Parser().parse(new File("person_address.avsc"));
GenericRecord address = new GenericData.Record(innerSchema);
address.put("addressLine1", "adr_1");
address.put("addressLine2", "adr_2");
address.put("city", "test_city");
address.put("state", "test_state");
address.put("zipcode", "zipcode_00000");