optional array in avro schema

Philipp Pahl picture Philipp Pahl · Feb 23, 2012 · Viewed 23.5k times · Source

I'm wondering whether or not it is possible to have an optional array. Let's assume a schema like this:

{ 
    "type": "record",
    "name": "test_avro",
    "fields" : [
        {"name": "test_field_1", "type": "long"},
        {"name": "subrecord", "type": [{
         "type": "record",
         "name": "subrecord_type",
           "fields":[{"name":"field_1", "type":"long"}]
          },"null"]
    },
    {"name": "simple_array",
    "type":{
        "type": "array",
        "items": "string"
      }
    }
  ]
}

Trying to write an avro record without "simple_array" would result in a NPE in the datafilewriter. For subrecord it's just fine, but when I try to define the array as optional:

{"name": "simple_array",
 "type":[{
   "type": "array",
   "items": "string"
   }, "null"]

It does not result in a NPE but a runtime exception:

AvroRuntimeException: Not an array schema: [{"type":"array","items":"string"},"null"]

Thanks.

Answer

kojiro picture kojiro · Mar 31, 2012

I think what you want here is a union of null and array:

{
    "type":"record",
    "name":"test_avro",
    "fields":[{
            "name":"test_field_1",
            "type":"long"
        },
        {
            "name":"subrecord",
            "type":[{
                    "type":"record",
                    "name":"subrecord_type",
                    "fields":[{
                            "name":"field_1",
                            "type":"long"
                        }
                    ]
                },
                "null"
            ]
        },
        {
            "name":"simple_array",
            "type":["null",
                {
                    "type":"array",
                    "items":"string"
                }
            ],
            "default":null
        }
    ]
}

When I use the above schema with sample data in Python, here's the result (schema_string is the above json string):

>>> from avro import io, datafile, schema
>>> from json import dumps
>>> 
>>> sample_data = {'test_field_1':12L}
>>> rec_schema = schema.parse(schema_string)
>>> rec_writer = io.DatumWriter(rec_schema)
>>> rec_reader = io.DatumReader()
>>> 
>>> # write avro file
... df_writer = datafile.DataFileWriter(open("/tmp/foo", 'wb'), rec_writer, writers_schema=rec_schema)
>>> df_writer.append(sample_data)
>>> df_writer.close()
>>> 
>>> # read avro file
... df_reader = datafile.DataFileReader(open('/tmp/foo', 'rb'), rec_reader)
>>> print dumps(df_reader.next())
{"simple_array": null, "test_field_1": 12, "subrecord": null}