Using Fixed Binary

You can declare a field as FIXED_BINARY using add-field -type FIXED_BINARY. When you do this, you must also specify the field's size using the -size parameter. You then read and write the field value using Java byte arrays. However, if the byte array does not equal the specified size, then IllegalArgumentException is thrown when you attempt to write the field. Write the field value using a Java byte array.

If you want to store a large binary object, then you should use the LOB APIs rather than a BINARY field. For information on using the LOB APIs, see the Oracle NoSQL API Large Object API introduction.

FIXED_BINARY should be used over the BINARY datatype any time you know that all the field values will be of the same size. FIXED_BINARY is a more compact storage format because it does not need to store the size of the array. See Using Binary for information on the BINARY datatype.

To define a simple two-column table where the primary key is a UID and the second column contains a fixed binary field, you use the following script:

## Enter into table creation mode
table create -name myTable
## Now add the fields
add-field -type INTEGER -name uid

## Create an enum field
add-field -type FIXED_BINARY -size 20 -name myBinary

## A primary key must be defined for every table
primary-key -field uid

## Exit table creation mode
exit

## Add the table to the store.
plan add-table -name myTable -wait 

To write the byte array, use Row.putFixed(). Again, if the byte array does not match the size defined for this field, then IllegalArgumentException is thrown.

TableAPI tableH = kvstore.getTableAPI();

Table myTable = tableH.getTable("myTable");

Row row = myTable.createRow();
row.put("uid", 12345);

String aString = "The quick brown fox.";
try {
    row.putFixed("myByteArray", aString.getBytes("UTF-8"));
} catch (UnsupportedEncodingException uee) {
    uee.printStackTrace();
}

tableH.put(row, null, null); 

To read the fixed binary field, use Row.get().asFixedBinary(). This returns a FixedBinaryValue class instance. You can then use FixedBinaryValue.get() to retrieve the stored byte array.

For example:

TableAPI tableH = kvstore.getTableAPI();

Table myTable = tableH.getTable("myTable");

/* Create a primary key for user id 12345 and get a row */
PrimaryKey key = myTable.createPrimaryKey();
key.put("uid", 12345);
Row row = tableH.get(key, null);

byte[] b = row.get("myByteArray").asFixedBinary().get();
String aString = new String(b);
System.out.println("aString: " + aString);