4

In my Avro schema, I have a field called myenum of type enum as follows:

{
"name": "myenum",
    "type": {
        "type": "enum",
        "name": "Suit",
        "symbols": ["SPADES", "HEARTS", "DIAMONDS", "CLUBS"]
    }
}

I also want null to be allowed. If I change the type to be a union with the default value as null (as suggested in this post), it looks like this:

{
"name": "myenum",
    "type": ["null", {
        "type": "enum",
        "name": "Suit",
        "symbols": ["SPADES", "HEARTS", "DIAMONDS", "CLUBS"]
    }]
}

When I test it with the following JSON object {"myenum":"HEARTS"}, I get an error - Expected start-union. Got VALUE_STRING.

If I test it with a null value {"myenum": null}, it works. How can I make an enum field optional?

Warren Crasta
  • 478
  • 8
  • 20

1 Answers1

0

For Avro's JSON encoding, you need to pass the intended type for every non-null union value.

{"myenum": {"string": "HEARTS"}}

should do the trick for you.

Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156
  • I tried that too, after reading [this post](https://stackoverflow.com/questions/27485580/how-to-fix-expected-start-union-got-value-number-int-when-converting-json-to-av). However, when I do this, I get an error: `Unknown union branch string`. – Warren Crasta Oct 08 '18 at 17:48
  • Did you include a namespace? – Giorgos Myrianthous Oct 08 '18 at 17:52
  • I did not, which I suspect is the issue. I'm trying to wrap my head around namespaces. If I have the schema defined like [this post](https://stackoverflow.com/a/50294844/7124380), to include a namespace as you've suggested, do I have to change the JSON encoding of the object or the schema itself? – Warren Crasta Oct 08 '18 at 18:02
  • @WarrenCrasta See my updated answer and let me know if this has worked for you. – Giorgos Myrianthous Oct 08 '18 at 18:09
  • Tried and I get an error: `org.apache.avro.SchemaParseException: "record" is not a defined name. The type of the "Test" field must be a defined name or a {"type": ...} expression.` – Warren Crasta Oct 08 '18 at 18:17
  • Could I change my JSON encoding to be this? `{ "com.abc.Suit": { "myenum": { "string": "HEARTS" } } }` – Warren Crasta Oct 08 '18 at 18:21
  • @WarrenCrasta Did you try it? It might work for your initial schema. – Giorgos Myrianthous Oct 08 '18 at 18:23
  • I tried changing the JSON encoding. I got the error `Expected start-union. Got END_OBJECT`. Oh well, thanks for your help. I guess I'll have to keep messing around with this more, but I also think it's a namespace issue. – Warren Crasta Oct 08 '18 at 18:25
  • If you have a namespace `com.abc` defined on your Schema, it should be more something like `{ "myenum": {"com.abc.Suit": "HEARTS" } }` – boumbh Oct 05 '21 at 16:20