How to convert from ByteBuffer to Avro bytes?

I have an avro scheme that includes the following as one of the fields

{
  "name" : "currency",
  "type" : ["null","bytes"],
  "logicalType": "decimal",
  "precision": 9,
  "scale": 4
},

I launched the avro-tools jar to create a java file to represent the schema. This created a property that looks like this:public java.nio.ByteBuffer currency;

Elsewhere in my code, I will work with currency values ​​in types BigDecimal.

How to convert a value BigDecimalto expected ByteBufferas I create an instance of this class? Can I just use it ByteBuffer.toByteArray()or do I need to do something special to make sure it is compatible with avro (and other tools like Impala that can read data)?

+4
source share
1 answer

. " " 2014 , Avro Java.

, , Avro Java ( , , ).

BigDecimal ByteBuffer

:

Avro . - two -s-complement . .

Java (, Avro 1.8.0-rc2):

public ByteBuffer toBytes(BigDecimal value, Schema schema, LogicalType type)
{
    int scale = ((LogicalTypes.Decimal) type).getScale();
    if (scale != value.scale()) {
        throw new AvroTypeException("Cannot encode decimal with scale " +
          value.scale() + " as scale " + scale);
    }

    return ByteBuffer.wrap(value.unscaledValue().toByteArray());
}

BigDecimal BigInteger Javadoc, , value.unscaledValue().toByteArray() .

, : return new BigDecimal(new BigInteger(bytes), scale);

?

, Avro 1.7, . () , . - , Avro .

Avro 1.8.0-rc2 . , (de) (. Conversion Conversions) GenericData. , BigDecimal, . ReflectData , ( AFAIK ).

, avro-/codegen .

+4

Source: https://habr.com/ru/post/1624880/


All Articles