protocols - 递归数据类型(如 Avro 架构中的树)

标签 protocols avro recursive-datastructures

阅读https://avro.apache.org/docs/current/spec.html它说模式必须是以下之一:

  • 一个 JSON 字符串,命名已定义的类型。
  • 一个 JSON 对象,其形式为: {"type": "typeName"...attributes...} 其中 typeName 是 原始或派生类型名称,如下定义。属性不 本文档中定义的内容允许作为元数据,但不得 影响序列化数据的格式。
  • 一个 JSON 数组,代表一个 嵌入式类型的联合。

我想要一个描述树的模式,使用树的递归定义:

  • 具有值(例如整数)的节点和树列表(子节点)
  • 一片有值(value)的叶子

我最初的尝试如下:

{
  "name": "Tree",
  "type": [
    {
      "name": "Node",
      "type": "record",
      "fields": [
        {
          "name": "value",
          "type": "long"
        },
        {
          "name": "children",
          "type": { "type": "array", "items": "Tree" }
        }
      ]
    },
    {
      "name": "Leaf",
      "type": "record",
      "fields": [
        {
          "name": "value",
          "type": "long"
        }
      ]
    }
  ]
}

但是 Avro 编译器拒绝了这一点,提示没有 {"name":"Tree","type":[{"name":"Node"... 类型。看来 Avro 不喜欢顶层的联合类型。我猜这属于上述规则“模式必须是…一个 JSON 对象…其中 typeName 是原始类型名称或派生类型名称”之一。我不确定“派生类型名称”是什么。起初我认为它与“复杂类型”相同,但包括联合类型..

无论如何,将其更改为更复杂的定义:

{
  "name": "Tree",
  "type": "record",
  "fields": [{
    "name": "ctors",
    "type": [
      {
        "name": "Node",
        "type": "record",
        "fields": [
          {
            "name": "value",
            "type": "long"
          },
          {
            "name": "children",
            "type": { "type": "array", "items": "Tree" }
          }
        ]
      },
      {
        "name": "Leaf",
        "type": "record",
        "fields": [
          {
            "name": "value",
            "type": "long"
          }
        ]
      }
    ]
  }]
}

有效,但现在我有这个奇怪的记录,只有一个字段,其唯一目的是让我定义我想要的顶级联合类型。

这是在 Avro 中获得我想要的东西的唯一方法还是有更好的方法?

谢谢!

最佳答案

虽然这不是关于表示递归命名联合的实际问题的答案(这在 2022 年末是不可能的),但可以针对树状数据结构解决这个问题。

如果将 Tree 表示为节点,将 Leaf 表示为具有空子列表的节点,则一种递归类型就足够了:

{
  "type": "record",
  "name": "TreeNode",
  "fields": [
    {
      "name": "value",
      "type": "long"
    },
    {
      "name": "children",
      "type": { "type": "array", "items": "TreeNode" }
    }
  ]
}

现在,您的三种类型 TreeNodeLeaf 被统一为一种类型 TreeNode,并且不需要 NodeLeaf 的并集。

关于protocols - 递归数据类型(如 Avro 架构中的树),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46839454/

相关文章:

protocols - 协议(protocol)/数据包设计问题

ios - 协议(protocol)方法/函数中的 Swift 默认参数和忽略参数

hadoop - CDH 5 中的 AvroRecord 类发生了什么变化?

apache-kafka - 使用 MassTransit 和 Kafka 配置 Avro

f# - 如何在F#中初始化相互递归记录

powershell - 如果文件不存在,则使用PowerShell将文件移动到上一级的远程位置

java - SSLv3 和 TLS(v1、v1.1 或 v1.2)能否协同工作

swift - NSObject 类符合 Swift 中 NSArray 中包含的协议(protocol)

json - 创建方案 .avsc Avro 的问题

haskell - haskell中的递归数据结构: prolog-like terms