【问题标题】:How to add data to a topic using AvroProducer如何使用 AvroProducer 向主题添加数据
【发布时间】:2020-07-13 07:38:37
【问题描述】:

我有一个具有以下架构的主题。有人可以帮助我了解如何将数据添加到不同的字段。

{
  "name": "Project",
  "type": "record",
  "namespace": "abcdefg",
  "fields": [   
    {
      "name": "Object",
      "type": {
        "name": "Object",
        "type": "record",
        "fields": [
          {
            "name": "Number_ID",
            "type": "int"
          },
          {
            "name": "Accept",
            "type": "boolean"
          }
        ]
      }
    },
    {
      "name": "DataStructureType",
      "type": "string"
    },
    {
      "name": "ProjectID",
      "type": "string"
    }
  ]
}

我尝试了以下代码。我得到列表不可迭代或列表超出范围。

from confluent_kafka import avro
from confluent_kafka.avro import AvroProducer


AvroProducerConf = {'bootstrap.servers': 'localhost:9092','schema.registry.url': 'http://localhost:8081'}
value_schema = avro.load('project.avsc')

avroProducer = AvroProducer(AvroProducerConf, default_value_schema = value_schema)

while True:
    avroProducer.produce(topic = 'my_topic', value = {['Object'][0] : "value", ['Object'] [1] : "true", ['DataStructureType'] : "testvalue", ['ProjectID'] : "123"})

    avroProducer.flush()

【问题讨论】:

    标签: python apache-kafka avro kafka-producer-api


    【解决方案1】:

    不清楚你期望这样的事情做什么......['Object'][0] 和字典的键不能是列表。

    尝试发送与您的 Avro 架构匹配的此内容

    value = {
        'Object': {
           "Number_ID", 1, 
           "Accept": true
        }, 
        'DataStructureType' : "testvalue", 
        'ProjectID' : "123"
    }
    

    【讨论】:

    • 谢谢。这行得通。但是当我使用带有浮点字段的架构时,我收到错误TypeError: argument of type 'float' is not iterable
    • 假设您将NumberId 类型更改为double。上述值仍然有效。
    猜你喜欢
    • 2017-05-21
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多