【发布时间】:2020-12-21 01:43:53
【问题描述】:
我正在尝试将 AVRO 模式转换为 ElasticSearch 索引模板。两者都是 JSON 结构,在转换时需要检查一些内容。我尝试使用递归来取出所有嵌套元素,然后将它们与它们的父元素配对,但是在使用递归进行深度解析时写入字典迫使我提出这个问题。
所以基本上我有这个 AVRO 架构文件:
{
"name": "animal",
"type": [
"null",
{
"type": "record",
"name": "zooAnimals",
"fields": [{
"name": "color",
"type": ["null", "string"],
"default": null
},
{
"name": "skinType",
"type": ["null", "string"],
"default": null
},
{
"name": "species",
"type": {
"type": "record",
"name": "AnimalSpecies",
"fields": [{
"name": "terrestrial",
"type": "string"
},
{
"name": "aquatic",
"type": "string"
}
]
}
},
{
"name": "behavior",
"type": [
"null",
{
"type": "record",
"name": "AnimalBehaviors",
"fields": [{
"name": "sound",
"type": ["null", "string"],
"default": null
},
{
"name": "hunt",
"type": ["null", "string"],
"default": null
}
]
}
],
"default": null
}
]
}
]
}
我希望它转换成这个(Elasticsearch 索引模板格式):
{
"properties": {
"color" :{
"type" : "keyword"
},
"skinType" :{
"type" : "keyword"
},
"species" :{
"properties" : {
"terrestrial" : {
"type" : "keyword"
},
"aquatic" : {
"type" : "keyword"
},
}
},
"behavior" : {
"properties" : {
"sound" : {
"type" : "keyword"
},
"hunt" : {
"type" : "keyword"
}
}
}
}
}
重要提示:AVRO 模式上的嵌套可以进一步嵌套,这就是我考虑使用递归解决的原因。此外,type 字段的类型可以是Array 或Map,如behavior 与species 所示,其中行为有一个数组,物种有一个映射。
如果你必须看到我做了我的试验和错误,这是我的代码,没有让我到任何地方:
const checkDataTypeFromObject = function (obj) {
if (Object.prototype.toString.call(obj) === "[object Array]") {
obj.map(function (item) {
if (Object.prototype.toString.call(item) === "[object Object]") {
// so this is an object that could contain further nested fields
dataType = item;
mappings.properties[item.name] = { "type" : item.type}
if (item.hasOwnProperty("fields")) {
checkDataTypeFromObject(item.fields);
} else if (item.hasOwnProperty("type")) {
checkDataTypeFromObject(item.type);
}
} else if (item === null) {
// discard the nulls, nothing to do here
} else {
// if not dict or null, this is the dataType we are looking for
dataType = item;
}
return item.name
});
【问题讨论】:
-
输入 JSON 与有效的 AVRO 模式不对应。看看 {"name":"animal","type":["null",{.... 字段 "type" 中没有对象。类型是字符串或字符串数组,字符串值为以下之一:null、int、long、float、double、bytes、string、record、enum、array、map 或 fixed。
标签: javascript node.js json recursion transformation