【问题标题】:Avro Schema. How to set type to "record" and "null" at onceAvro 架构。如何一次将类型设置为“记录”和“空”
【发布时间】:2016-07-19 05:04:09
【问题描述】:

我需要在 Schema 中混合“记录”类型和空类型。

"name":"specShape",
         "type":{
            "type":"record",
            "name":"noSpecShape",
            "fields":[
               {
                  "name":"bpSsc",
                  "type":"null",
                  "default":null,
                  "doc":"SampleValue: null"
               },...

例如,对于某些数据,specShape 可能为空。

所以如果我将类型设置为

"name":"specShape",
         "type":{
            **"type":["record", "null"],**
            "name":"noSpecShape",
            "fields":[
               {
                  "name":"bpSsc",
                  "type":"null",
                  "default":null,
                  "doc":"SampleValue: null"
               },...

它说

No type: {"type":["record","null"]...

但是如果我将整体类型设置为

"name":"specShape",
         **"type":[{
            "type":"record",
            "name":"noSpecShape",
            "fields":[
               {
                  "name":"bpSsc",
                  "type":"null",
                  "default":null,
                  "doc":"SampleValue: null"
               }, "null"]**,...

它说

Not in union [{"type":"record"

如何联合这两种类型?

【问题讨论】:

    标签: null schema union record avro


    【解决方案1】:

    您的想法是对的,您只需将"null" 包含在更高级别的"type" 数组中,而不是包含在"fields" 数组中(如您的第三个示例中所示)。这是可为空记录的架构:

    [
      "null",
      {
        "type": "record",
        "name": "NoSpecShape",
        "fields": [
          {
            "type": "null",
            "name": "bpSsc",
            "default": null
          }
        ]
      }
    ]
    

    您也可以将它嵌套在任何需要类型声明的地方,例如在另一条记录中:

    {
      "type": "record",
      "name": "SpecShape",
      "fields": [
        {
          "type": [
            "null",
            {
              "type": "record",
              "name": "NoSpecShape",
              "fields": [
                {
                  "type": "null",
                  "name": "bpSsc",
                  "default": null
                }
              ]
            }
          ],
          "name": "shape"
        }
      ]
    }
    

    最后一个模式的 JSON 编码实例如下所示:

    • {"shape": null}
    • {"shape": {"NoSpecShape": {"bpSsc": null}}}

    【讨论】:

    • 但是现在我在添加记录时遇到了“Not in union”异常,你能帮忙吗?
    • 在答案中添加了一些示例记录,希望能有所帮助。 (不要忘记,在 JSON 编码时,联合实例必须被“包装”。)
    猜你喜欢
    • 2020-06-24
    • 1970-01-01
    • 2018-02-17
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    相关资源
    最近更新 更多