Is it possible to assign default Value null to union{null, int} avro schema?

2k Views Asked by At

I'm trying to put default value as integer for coming values from kafka it could be any integer or null. I was trying like this:

union {null, int} field = 2; (in avdl file)

but I'm getting error Error: Exception in thread "main" org.apache.avro.AvroTypeException: Invalid default for field field: 2 not a ["null","int"]

1

There are 1 best solutions below

3
Haoliang On

According to avro documentation:

when a default value is specified for a record field whose type is a union, the type of the default value must match the first element of the union. Thus, for unions containing “null”, the “null” is usually listed first, since the default value of such unions is typically null.

Since null is the first element of the union, and 2 is not null, avro is complaining about the invalid default value.

If you want to set 2 as the default value, you could declare the union as union {int, null}.