本文介绍了使用GenericRecord在Avro中用数组填充嵌套记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下架构:
{
"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放入一个数组数组.
I'm using GenericRecord, and I want to put in an array of arrays for the 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)
I would like to do something like record.put(x)
推荐答案
,您可以通过以下方式进行.我建议将您的记录类型 SchoolFriends
放在不同的架构中,这将使获取集合元素的架构变得容易.
for that particular schema, you can do it in the following way. I would recommend put your record type SchoolFriends
in a different schema, it would make easy to get the schema for the collection elements.
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);
}
}
这篇关于使用GenericRecord在Avro中用数组填充嵌套记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!