簡體   English   中英

有沒有辦法讓 Google Cloud Pub/Sub Schema 字段成為可選字段?

[英]Is there a way to make Google Cloud Pub/Sub Schema fields optional?

標題說明了一切,真的。 我正在努力弄清楚如何制作具有可選字段的 Google Cloud Pub/Sub 架構。 或者在 AVRO 模式中有可選字段基本上直接與擁有模式的全部要點相矛盾嗎?

我試過的結構是這樣的,但沒有成功:

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

問題中提出的模式需要將 null 值作為默認值,因為null是聯合中的第一種類型:

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

想要包含非空字段的消息必須將它們放在 object 中,例如:

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

目前存在支持 Avro 模式可為空字段的問題: https://issuetracker.google.com/issues/242757468

將模式轉換為 protobuf (proto2) 模式對我有用。 消息本身可以保留為 JSON 格式。

您的 protobuf 架構可能如下所示:

syntax = "proto2";

message ProtocolBuffer {
  optional string TestStringField = 1;
  optional int32 TestIntField = 2;
}

如果您使用 GCP 控制台,請確保為 Schema 類型勾選ProtoBuf 另請注意,ProtoBuf 版本 3 對我不起作用。 留在第 2 版。

gcloud pubsub 模式創建密鑰模式 --definition='{ "type": "record", "namespace": "my.ns", "name": "KeyMsg", "fields": [ { "name": " key", "type": "string" } ] }' --type=AVRO

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM