gpt4 book ai didi

java - 使用 GenericRecord 在 Avro 中用数组填充嵌套记录

转载 作者:行者123 更新时间:2023-12-01 16:46:08 28 4
gpt4 key购买 nike

我有以下架构:

{
"name": "AgentRecommendationList",
"type": "record",
"fields": [
{
"name": "userid",
"type": "string"
},
{
"name": "friends",
"type": {
"type": "array",
"items": {
"name": "SchoolFriends",
"type": "record",
"fields": [
{
"name": "Name",
"type": "string"
},
{
"name": "phoneNumber",
"type": "string"
},
{
"name": "email",
"type": "string"
}
]
}
}
}
]
}

我正在使用 GenericRecord,我想为 SchoolFriends 放入一个数组。

val avschema = new RestService(URL).getLatestVersion(name)
val schema = new Schema.Parser().parse(avschema.getSchema)
val record = new GenericData.Record(schema)

我想做一些类似 record.put(x) 的事情

最佳答案

对于该特定架构,您可以通过以下方式执行此操作。我建议将您的记录类型 SchoolFriends 放在不同的架构中,这样可以轻松获取集合元素的架构。

import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;

import java.util.ArrayList;
import java.util.List;

public class PopulateNestedAvroObjects {
public static void main(String [] args ){
String strSchema = "{\n" +
" \"name\": \"AgentRecommendationList\",\n" +
" \"type\": \"record\",\n" +
" \"fields\": [\n" +
" {\n" +
" \"name\": \"userid\",\n" +
" \"type\": \"string\"\n" +
" },\n" +
" {\n" +
" \"name\": \"friends\",\n" +
" \"type\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"name\": \"SchoolFriends\",\n" +
" \"type\": \"record\",\n" +
" \"fields\": [\n" +
" {\n" +
" \"name\": \"Name\",\n" +
" \"type\": \"string\"\n" +
" },\n" +
" {\n" +
" \"name\": \"phoneNumber\",\n" +
" \"type\": \"string\"\n" +
" },\n" +
" {\n" +
" \"name\": \"email\",\n" +
" \"type\": \"string\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" }\n" +
" ]\n" +
"}";

Schema schema = new Schema.Parser().parse(strSchema);
GenericRecord record = new GenericData.Record(schema);
record.put("userid", "test user");
Schema childSchema = record.getSchema().getField("friends").schema().getElementType();
List<GenericRecord> friendList = new ArrayList();
GenericRecord friend1 = new GenericData.Record(childSchema);
friend1.put("Name", "1");
friend1.put("phoneNumber", "2");
friend1.put("email", "3");
friendList.add(friend1);
record.put("friends", friendList);
System.out.println(record);


}
}

关于java - 使用 GenericRecord 在 Avro 中用数组填充嵌套记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50278222/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com