Using Maps

All map entries must be of the same type. Regardless of the type of the map's values, its keys are always strings.

When you declare a table field as a map, you use add-map-field. This puts you into a special submode where you add one and only one field. The name you give the field is unimportant and will be ignored. What you are really doing when you add this sub-field is declaring the type of the elements in the map.

To define a simple two-column table where the primary key is a UID and the second column contains a map of integers, 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 a map field. This puts us into a new submode.
add-map-field -name myMap
## Sets the type for the map. The name is required but ignored
add-field -type INTEGER -name mapField

### Exit array map creation mode

## 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 map, use Row.putMap(), which returns a MapValue class instance. You then use MapValue.put() to write elements to the map:

TableAPI tableH = kvstore.getTableAPI();

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

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

MapValue mv = row.putMap("myMap");
mv.put("field1", 1);
mv.put("field2", 2);
mv.put("field3", 3);

tableH.put(row, null, null); 

To read the map, use Row.get().asMap(). This returns a MapValue class instance. You can then use MapValue.get() to retrieve an map value. The retrieved value is returned as a FieldValue, which allows you to retrieve the encapsulated value using a cast method such as FieldValue.asInteger().

For example, to retrieve elements from the map created in the previous 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);

MapValue mv = row.get("testMap").asMap();
FieldValue fv = mv.get("field3");
System.out.println("fv: " + fv.asInteger().get());