【问题标题】:Nullable Array Fields in AvroAvro 中的可空数组字段
【发布时间】:2015-08-06 19:43:05
【问题描述】:

我有以下 JSON 数据集:

{  
   "hashtags":null
}
{  
   "hashtags":[  
      "value1",
      "value2"
   ]
}

以及从 Kite SDK 生成的以下 Avro 架构(看起来是正确的 - 空值或字符串数​​组的联合):

{
  "type" : "record",
  "name" : "tweet",
  "fields" : [ {
    "name" : "hashtags",
    "type" : [ "null", {
      "type" : "array",
      "items" : "string"
    } ],
    "doc" : "Type inferred from 'null'"
  } ]
}

当我尝试使用

隐藏数据时
avro-tools fromjson --schema-file tweet.avsc twitter.json > twitter.avro

我收到以下错误(为简洁起见):

Exception in thread "main" org.apache.avro.AvroTypeException: Expected start-union. Got START_ARRAY

将 null 大小写更改为空数组:

{  "hashtags":null   } to {  "hashtags":[] }

将架构更改为允许在项目字段中使用字符串或 null

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

一旦输入 JSON 中的字符串被限定为“字符串”,就可以正常工作。

因此,是否可以有一个可为空的数组字段,或者,从 Avro 的角度来看,是否可以使用空数组来处理可空性?

【问题讨论】:

    标签: arrays null avro


    【解决方案1】:

    每当您的架构中有联合时,您必须明确告诉 Avro 将数据解释为什么类型。或者像你一样预处理你的数据,这样你就不需要联合了。你现在拥有它的方式,你会发现使用

    "type" : {
      "type" : "array",
      "items" : "string"
    }
    

    也有效,因为您已将所有数据强制转换为数组类型。 null 是不需要的。

    【讨论】:

    • 感谢 Keegan - 你上面的例子,在取消联合的情况下,在填充数组和空数组上都可以正常工作。但是,从正确性的角度来看,我宁愿能够表达 { "hashtags":null } 而不是 { "hashtags":[] }。有没有办法在模式中表达这一点?在这种情况下,将数组成员提示为 {"string": "xxxx"} 并没有帮助(尽管我在其他地方使用它)。
    • 啊哈!知道了。我需要将数组本身提示为数组,而不仅仅是其中的项目,如下所示: { "hashtags":{"array":["dog", "cat"]} }
    • 没错。我不确定 Avro 是否可以设计为使 null 更易于使用,但这就是你今天必须这样做的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 2012-03-14
    • 2020-10-28
    • 2015-06-23
    • 2022-01-02
    • 1970-01-01
    相关资源
    最近更新 更多