You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@avro.apache.org by Vivek Hungund <Vi...@Incentica.net> on 2011/03/29 02:31:29 UTC
Populating nested records using GenericRecord
Hi,
I¹ve got the following schema:
{
"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" }
]
}
}
]
}
I¹m using a GenericRecord to represent each Profile that gets created. To
add a firstName, it¹s easy to do the following:
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);
But how would I set the city, for example? How do I represent the key as a
string that the r.put method can understand?
Thanks
Re: Populating nested records using GenericRecord
Posted by Felix Xu <yg...@gmail.com>.
Hi,I have met this problem too,it seems that we have to do like this:
GenericRecord t = new GenericData.Record(sch.getField("address"));
t.put("city","beijing");
r.put("address",t);
2011/3/29 Vivek Hungund <Vi...@incentica.net>
> Hi,
>
> I’ve got the following schema:
> {
> "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" }
> ]
> }
> }
> ]
> }
>
> I’m using a GenericRecord to represent each Profile that gets created. To
> add a firstName, it’s easy to do the following:
>
> Schema sch = Schema.parse(schemaFile);
> DataFileWriter<GenericRecord> fw = new DataFileWriter<GenericRecord>(newGenericDatumWriter<GenericRecord>()).create(sch,
> new File(outFile));
> GenericRecord r = new GenericData.Record(sch);
> r.put(“firstName”, “John”);
> fw.append(r);
>
> But how would I set the city, for example? How do I represent the key as a
> string that the r.put method can understand?
>
> Thanks
>