【问题标题】:Is there a way to make Google Cloud Pub/Sub Schema fields optional?有没有办法让 Google Cloud Pub/Sub Schema 字段成为可选字段?
【发布时间】:2022-08-11 18:39:29
【问题描述】:

标题说明了一切,真的。我正在努力弄清楚如何制作具有可选字段的 Google Cloud Pub/Sub 架构。还是在 AVRO 模式中具有可选字段基本上直接与​​拥有模式的全部意义相矛盾?

我尝试的结构是这样的,但没有成功:

{
  \"type\": \"record\",
  \"name\": \"Avro\",
  \"fields\": [
    {
      \"name\": \"TestStringField\",
      \"type\": [\"null\", \"string\"],
      \"default\": \"\"
    },
    {
      \"name\": \"TestIntField\",
      \"type\": [\"null\", \"int\"],
      \"default\": 0
    }
  ]
}
  • 您能否提供一个示例,说明您尝试使用此模式传递的消息以及调用发布时产生的错误消息?
  • @KamalAboul-Hosn 我遇到了同样的问题,找不到解决方案。架构: { \"type\": \"record\", \"name\": \"Person\", \"fields\": [ { \"name\": \"name\", \"type \": [ \"null\", \"string\" ], \"default\": null } ] } 消息:{\"name\": \"john\"} 错误:无效的 JSON 编码消息针对Avro 架构。流中的令牌不正确。预期:对象开始,找到字符串

标签: python google-cloud-platform avro google-cloud-pubsub


【解决方案1】:

问题中提出的架构需要将空值设为默认值,因为 null 是联合中的第一种类型:

{
  "type": "record",
  "name": "Avro",
  "fields": [
    {
      "name": "TestStringField",
      "type": ["null", "string"],
      "default": null
    },
    {
      "name": "TestIntField",
      "type": ["null", "int"],
      "default": null
    }
  ]
}

想要具有非空字段的消息必须将它们放在对象中,例如:

{
  "TestStringField": {
    "string": "Hi"
  },
  "TestIntField": {
    "int": 7
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-05
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 2021-12-12
    相关资源
    最近更新 更多