All map entries must be of the same type. Regardless of the type of the map's values, its keys are always strings.
The string "[]" is reserved and must not be used for key names.
When you declare a table field as a map, you use
the MAP() statement. You must also declare
the map element's data types.
To define a simple two-field table where the primary key is a UID and the second field contains a map of integers, you use the following script:
CREATE TABLE myTable (
uid INTEGER,
myMap MAP(INTEGER),
PRIMARY KEY (uid)
)
CHECK constraints are supported for map
fields. See CHECK
for more information.
DEFAULT and NOT NULL
constraints are not supported for map fields.
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());