arrays - avro 模式中的 optional 数组

标签 arrays null optional avro

我想知道是否可以有一个 optional 数组。
让我们假设这样的模式:

{ 
    "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"
      }
    }
  ]
}

尝试在没有“simple_array”的情况下写入 avro 记录会导致数据文件写入器中出现 NPE。
对于子记录,它很好,但是当我尝试将数组定义为 optional 时:
{"name": "simple_array",
 "type":[{
   "type": "array",
   "items": "string"
   }, "null"]

它不会导致 NPE 而是运行时异常:
AvroRuntimeException: Not an array schema: [{"type":"array","items":"string"},"null"]

谢谢。

最佳答案

我认为你想要的是 null 和 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
        }
    ]
}

当我在 Python 中使用带有示例数据的上述模式时,结果如下(schema_string 是上面的 json 字符串):
>>> 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}

关于arrays - avro 模式中的 optional 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9417732/

相关文章:

arrays - 列出三维数组

javascript - 关于垃圾回收的 Null 和 delete()

regex - 使用 REGEX 在 Hive Create 和 Load Query 中获取空值

Scala Option(null) 预期为 None 但我得到了 Some(0)

rust - 理解 rust Option as_mut 方法

delphi - 何时销毁选项类型内的对象?

java - 如何让代码将数组中小于 10 的值 (x * 2) 加倍? ( java )

python - 用零填充 numpy 数组,并使用另一个数组作为 1 的索引

javascript - 使用 new Array().fill(0) 创建二维数组错误?

java - 在 Java8 中使用 lambda 仅在不为空时过滤值