Вопрос о заполнении вложенных записей в Avro с использованием GenericRecord - PullRequest
7 голосов
/ 30 марта 2011

Предположим, у меня есть следующая схема:

{
 "name" : "Profile",
 "type" : "record",
 "fields" : [
  { "name" : "firstName", "type" : "string" },
  { "name" : "address" , "type" : {
   "type" : "record",
   "name" : "AddressUSRecord",
   "fields" : [
    { "name" : "address1" , "type" : "string" },
    { "name" : "address2" , "type" : "string" },
    { "name" : "city" , "type" : "string" },
    { "name" : "state" , "type" : "string" },
    { "name" : "zip" , "type" : "int" },
    { "name" : "zip4", "type": "int" }
   ]
  }
 }
]
}

Я использую GenericRecord для представления каждого создаваемого профиля. Чтобы добавить firstName, легко сделать следующее:

Schema  sch =  Schema.parse(schemaFile);
DataFileWriter<GenericRecord> fw = new DataFileWriter<GenericRecord>(new GenericDatumWriter<GenericRecord>()).create(sch, new File(outFile));
GenericRecord r = new GenericData.Record(sch);
r.put(“firstName”, “John”);
fw.append(r);

Но как бы я установил город, например? Как мне представить ключ как строку, которую может понять метод r.put?

Спасибо

1 Ответ

15 голосов
/ 31 марта 2011

Для схемы выше:

GenericRecord t = new GenericData.Record(sch.getField("address").schema());
t.put("city","beijing");
r.put("address",t);
...