Home | About | Sematext search-lucene.com search-hadoop.com
 Search Hadoop and all its subprojects:

Switch to Threaded View
Avro >> mail # user >> issue with default values in avro


Copy link to this message
-
Re: issue with default values in avro
Serge,

Default field values are primarily used when reading records that don't
have those fields, typically an older version of the record.

GenericData.Record's constructor does not use default values to populate
fields.  All fields in an instance created by 'new
GenericData.Record(<schema>)' are initially null, not set to the default
value of the schema.

However the GenericRecordBuilder API does use default values to populate
instances.  The value of 'new GenericRecordBuilder(<schema>).set("SSN",
"XXX").build()' should contain what you want.

Doug

On 02/08/2012 03:35 PM, Serge Blazhievsky wrote:
>       Hi all,
>
>
>
> I am trying to utilize default setting for values in avro schema,
> however, it does not seems to be set.
>
>
> My code is below.
>
>
>       List<Schema.Field> fields2 = new ArrayList<Schema.Field>();
>
>        org.codehaus.jackson.JsonNode defaultValue2
> =TextNode.valueOf("default2");
>        
>        fields2.add(new Schema.Field("SSN", Schema.create(Type.STRING),
> "Second schema", defaultValue2));
>        
>        fields2.add(new Schema.Field("LastName",
> Schema.create(Type.STRING), "Second schema", defaultValue2));
>        
>        Schema schema2 = Schema.createRecord("blah", "blah",
> "merced.ssn", false);
>
>        schema2.setFields(fields2);
>      
>        
>        System.out.println(schema2.toString(true));
>      
>         GenericRecord r=new GenericData.Record(schema2);
>        
>        
>         r.put("SSN", "12345");
>        
>         System.out.println(r.get("LastName"));
>        
>        
>         System.out.println(r.toString());
>
>
>>>>>>>>>>>>>>>>>>>>>>>>>>>
>
> {
>   "type" : "record",
>   "name" : "blah",
>   "namespace" : "merced.ssn",
>   "doc" : "blah",
>   "fields" : [ {
>     "name" : "SSN",
>     "type" : "string",
>     "doc" : "Second schema",
>     "default" : "default2"
>   }, {
>     "name" : "LastName",
>     "type" : "string",
>     "doc" : "Second schema",
>     "default" : "default2"
>   } ]
> }
> null
> {"SSN": "12345", "LastName": null}
>
>
> I expect LastName to be set to default2
>
>
> Thank you for your help.
>
> Serge
>