Using Embedded Records

A record entry can contain fields of differing types. However, embedded records should be used only when the data is relatively static. In general, child tables provide a better solution over embedded records, especially if the child dataset is large or is likely to change in size.

Use the RECORD() statement to declare a table field as a record.

To define a simple two-field table where the primary key is a UID and the second field contains a record, you use the following DDL statement:

CREATE TABLE myTable (
    uid INTEGER,
    myRecord RECORD(firstField STRING, secondField INTEGER),
    PRIMARY KEY (uid)
) 

DEFAULT and NOT NULL constraints are not supported for embedded record fields. However, these constraints can be applied to the individual fields in an embedded record. See Field Constraints for more information.

To write the record, use Row.putRecord(), which returns a RecordValue class instance. You then use RecordValue.put() to write fields to the record:

TableAPI tableH = kvstore.getTableAPI();

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

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

RecordValue rv = row.putRecord("myRecord");
rv.put("firstField", "An embedded record STRING field");
rv.put("secondField", 3388);

tableH.put(row, null, null); 

To read the record, use Row.get().asRecord(). This returns a RecordValue class instance. You can then use RecordValue.get() to retrieve a field from the record. 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 field values from the embedded record 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);

RecordValue rv = row.get("myRecord").asRecord();
FieldValue fv = rv.get("firstField");
System.out.println("firstField: " + fv.asString().get());
fv = rv.get("secondField");
System.out.println("secondField: " + fv.asInteger().get());