Using Enums

When you declare a table field as an enum, you use add-field -type ENUM. You must also use the -enum-values parameter to declare the acceptable enumeration values.

To define a simple two-column table where the primary key is a UID and the second column contains an enum, 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 ENUM -name myEnum -enum-values Apple,Pears,Oranges

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

## Exit table creation mode

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

To write the enum, use Row.putEnum(). If the enumeration value that you use with this method does not match a value defined on the -enum-values parameter during table definition, an IllegalArgumentException is thrown.

TableAPI tableH = kvstore.getTableAPI();

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

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

row.putEnum("myEnum", "Pears");

tableH.put(row, null, null); 

To read the enum, use Row.get().asEnum(). This returns a EnumValue class instance. You can then use EnumValue.get() to retrieve the stored enum value's name as a string. Alternatively, you can use EnumValue.getIndex() to retrieve the stored value's index position.

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);

EnumValue ev = row.get("testEnum").asEnum();
System.out.println("enum as string: " + 
                ev.get()); // returns "Pears"
System.out.println("enum index: " + 
                ev.getIndex()); // returns '1'