java—在avro模式的嵌套字段中设置值

cqoc49vn  于 2021-06-07  发布在  Kafka
关注(0)|答案(1)|浏览(463)

我正在尝试使用genericdata.record将avro数据生成到kafka中,但遇到以下异常:
线程“main”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记录中放入嵌套值吗?

k4aesqcs

k4aesqcs1#

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

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);

相关问题