首页 > 解决方案 > 数组中的 AVRO ENUM:不是联合运行时异常

问题描述

我正在尝试在 JAVA 的 AVRO 记录中填充枚举。Maven 插件的使用导致了其他问题,所以我决定使用 GenericRecordBuilder。有问题的 AVRO 记录(仅显示导致我出现问题的部分架构):

        {
            "name": "allocs",
            "type": {
                "type": "array",
                "items": {
                    "type": "record",
                    "name": "Allocs",
                    "fields": [
                        {
                            "name": "allocAmt",
                            "type": "double"
                        },
                        {
                            "name": "allocType",
                            "type": {
                                "type": "enum",
                                "name": "AllocationType",
                                "symbols": [
                                    "STANDARD",
                                    "OTHER"
                                ]
                            },
                            "doc": "Contains allowed payment allocation types."
                        }
                    ]
                }
            },
            "doc": "Payment allocation array contains allocation type and amount"
        }

allocAmt这是允许我添加但创建的最新迭代会allocType引发错误:

org.apache.avro.AvroRuntimeException: Not a union: {"type":"enum","name":"AllocationType","symbols":["STANDARD","OTHER"]}

这是我尝试过的:

//payLoadSchema is the entire schema within which allocs resides
Schema paymentAllocationsSchema = payLoadSchema.getField("allocs").schema().getElementType();
List<GenericRecord> allocations = new ArrayList<>();
GenericRecord allocation = new GenericData.Record(paymentAllocationsSchema);
allocation.put("allocAmt", 100.01);

// **LINE THROWING THE ERROR I PASTED ABOVE**:
GenericData.EnumSymbol paymentAllocEnum = new GenericData.EnumSymbol(paymentAllocationsSchema.getField("allocType").schema().getTypes().get(1),"STANDARD"); 

//Adding enum to record
allocation.put("allocType", paymentAllocEnum);
//Adding record to list
allocations.add(allocation);

我知道异常清楚地表明我正在尝试将 ENUM 添加为 UNION,但我不确定如何正确创建 ENUM。任何指针将不胜感激。

标签: javaenumsavro

解决方案


我能够弄清楚并在这里发布以防其他人发现这很有用。而不是使用

// **LINE THROWING THE ERROR I PASTED ABOVE**:
GenericData.EnumSymbol paymentAllocEnum = new GenericData.EnumSymbol(paymentAllocationsSchema.getField("allocType").schema().getTypes().get(1),"STANDARD"); 
//Adding enum to record
allocation.put("allocType", paymentAllocEnum);

首先从模式中获取 allocationEnum:

Schema allocationEnum = paymentAllocationsSchema.getField("allocType").schema();

接下来,将所需的 ENUM 值添加到分配记录中:

allocation.put("allocType", new GenericData.EnumSymbol(allocationEnum,"STANDARD"));

推荐阅读