2011-03-29 69 views
5

假設我有以下模式填充在Avro中嵌套的記錄:問題使用GenericRecord

{ 
"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來表示被創建的每個配置文件。要添加名字,很容易做到以下幾點:

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方法可以理解的字符串?

由於

回答

10

對於上面的架構:

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