avro-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Check Peck <comptechge...@gmail.com>
Subject How to change a particular field value after decoding the original byte array?
Date Mon, 12 Jan 2015 23:42:33 GMT
I have an Avro Schema which is like this -

    {
       "type":"record",
       "name":"new_user",
       "namespace":"com.hello",
       "fields":[
          {
             "name":"user_id",
             "type":[
                "long",
                "null"
             ]
          },
          {
             "name":"segment",
             "type":[
                "string",
                "null"
             ]
          }
       ]
    }

I am using my above Avro Schema like this to serialize the data and which
gives me a Byte Array and works fine -

    public static void main(String[] args) throws IOException {
        Schema schema = new Parser()
                .parse("{ \"type\":\"record\", \"name\":\"new_user\",
\"namespace\":\"com.hello\", \"fields\":[ { \"name\":\"user_id\",
\"type\":[ \"long\", \"null\" ] }, { \"name\":\"segment\", \"type\":[
\"string\", \"null\" ] } ] }");

        byte[] originalAvrodata = getAvroBinaryData(schema);

        // how to get newAvroData byte array in which user_id
        // is change to some other random long number?
    }

    private static byte[] getAvroBinaryData(Schema schema) throws
IOException {
        GenericRecord record = new GenericData.Record(schema);
        record.put("user_id", 123456L);
        record.put("segment", "hello");

        GenericDatumWriter<GenericRecord> writer = new
GenericDatumWriter<GenericRecord>(schema);
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        Encoder e = EncoderFactory.get().binaryEncoder(os, null);

        writer.write(record, e);
        e.flush();
        byte[] byteData = os.toByteArray();
        return byteData;
    }



I need to decode the `originalAvrodata` byte array and then change the
`user_id` field value to some other `long` number and then construct a
`newAvroData` byte array using the same schema which should have `user_id`
field value to some random `long` number. Is this possible to do by any
chance using Avro?

Mime
View raw message