14

I am trying to create Union field in Avro schema and send corresponding JSON message with it but to have one of the fields - null.

https://avro.apache.org/docs/1.8.2/spec.html#Unions

What is example of simplest UNION type (avro schema) with corresponding JSON data? (trying to make example without null/empty data and one with null/empty data).

user9750148
  • 375
  • 3
  • 5
  • 14

1 Answers1

23

Here you have an example.

Null enum

{"name": "Stephanie", "age": 30, "sex": "female", "myenum": null}

Not null enum

{"name": "Stephanie", "age": 30, "sex": "female", "myenum": "HEARTS"}

Schema

{
    "type": "record",
    "name": "Test",
    "namespace": "com.acme",
    "fields": [{
            "name": "name",
            "type": "string"
        }, {
            "name": "age",
            "type": "int"
        }, {
            "name": "sex",
            "type": "string"
        }, {
            "name": "myenum",
            "type": ["null", {
                    "type": "enum",
                    "name": "Suit",
                    "symbols": ["SPADES", "HEARTS", "DIAMONDS", "CLUBS"]
                }
            ]
        }
    ]
}
hlagos
  • 7,690
  • 3
  • 23
  • 41
  • 3
    This doesn't work for me. I have this error: "Failed to convert JSON to Avro: Expected start-union. Got VALUE_STRING" Avro version 1.9.2 – vanillaSugar May 12 '20 at 10:16
  • 1
    @vanillaSugar, ask in a different question adding details and code – hlagos May 12 '20 at 13:55
  • 2
    I guess this example does not work because of the namespace that is defined in the Schema... The "not null" message should be something like : `{"name": "Stephanie", "age": 30, "sex": "female", "myenum": {"com.acme.Suit": "HEARTS" }}` – boumbh Oct 05 '21 at 16:12
  • Yeah, I got the same issue. if I put "com.acme.Suit" it will work, but doesn't work for "myenum": "HEARTS". Do you know why? – Zichen Ma Apr 24 '23 at 17:30