【问题标题】:AVRO schema with default array of objects具有默认对象数组的 AVRO 模式
【发布时间】:2020-10-19 15:42:19
【问题描述】:

我有一个带有数组字段的 AVRO 模式。该数组字段的项目是另一个 AVRO 模式的对象。下面是我现在的代码。

{
  "name": "bars",
  "type": ["null", {
    "type": "array",
    "items": "com.example.Bar"
  }],
  "default": null
}

这段代码是“bars”的字段定义,它是一个包含“com.example.Bar”对象的数组。

我现在将默认值设置为“null”,但是我想明确地将默认值设置为 3 个 Bar 对象的数组。

想象一下我的 Bar 有以下字段定义

{
  "name": "name",
  "type": [
    "null",
    "string"
  ],
  "default": null
},
{
  "name": "number",
  "type": [
    "null",
    "int"
  ],
  "default": null
}

我想将“bars”默认设置为

{
  "name": "bars",
  "type": ["null", {
    "type": "array",
    "items": "com.example.Bar"
  }],
  "default": [{"name": "bar1", "number":1}, {"name": "bar2", "number":2}, {"name": "bar3", "number":3}]
}

但是这段代码不起作用。我应该如何设置对象的默认值?

【问题讨论】:

    标签: avro


    【解决方案1】:

    联合字段的默认值对应于first schema in the union。如果默认值是一个数组,那么数组架构应该是联合中的第一个架构。

    "type": [
      {
        "type": "array",
        "items": "com.example.Bar"
      },
      "null"
    ],
    

    【讨论】:

    • 从类型中删除“null”后它可以工作。我想如果我允许数组字段为空,那么我不能用空以外的值预先填充默认字段。
    【解决方案2】:

    问题是我允许“null”作为数组字段的类型。我想如果我想用我不能允许 null 的值预填充默认字段。

    所以下面的代码解决了这个问题。

    {
      "name": "bars",
      "type": {
        "type": "array",
        "items": "com.example.Bar"
      },
      "default": [{"name": "bar1", "number":1}, {"name": "bar2", "number":2}, {"name": "bar3", "number":3}]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      相关资源
      最近更新 更多