2

我正在尝试使用 GenericData.Record 将 avro 数据生成到 kafka 中,但出现以下异常:

线程“主”org.apache.avro.AvroRuntimeException 中的异常:不是有效的架构字段:emailAddresses.email

这是我的架构:

{
 "namespace": "com.cloudurable.User",

 "type": "record",

 "name": "User",

 "fields": [

     {"name": "id", "type": "int", "default" : 0},
     {"name": "fname",  "type": "string", "default" : "EMPTY"},
     {"name": "lname",  "type": "string", "default" : "EMPTY"},
     {"name": "phone_number",  "type": "string", "default" : "EMPTY"},
     {"name": "age",  "type": "int", "default" : 0},

     {
      "name": "emailAddresses",
      "type": {
          "type": "record",
          "name": "EmailAddress",
          "fields": [
            {
              "name": "email",
              "type": "string",
              "default" : "EMPTY"
            },
            {
              "name": "address",
              "type": "boolean",
              "default": false
            }
          ]
        }
    }
 ]
}

我的Java代码如下:

GenericData.Record avroRecord = new GenericData.Record(SchemaRegstryClient.getLatestSchema("test2"));
        System.out.println(avroRecord.getSchema().getFields());
        avroRecord.put("id", i);
        avroRecord.put("fName", "Sumit" + i);
        avroRecord.put("lName", "Gupta " +i);
        avroRecord.put("phone_number", "98911 " +i);
        avroRecord.put("age", i);
        avroRecord.put("emailAddresses.email", "sumit@gmail.com");
        avroRecord.put("emailAddresses.address", true);

任何人都知道如何将嵌套值放入 avro 记录中?

4

1 回答 1

5

您不能使用“.”设置内部值。因此,您必须手动创建内部对象(电子邮件地址)并将其设置为顶级记录的字段。

final GenericData.Record emailAddresses = new GenericData.Record(schema.getField("emailAddresses").schema());
emailAddresses.put("email", "sumit@gmail.com");
emailAddresses.put("address", true);
avroRecord.put("emailAddresses", emailAddresses);
于 2018-02-06T15:24:53.307 回答