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.
When you declare a table field as a record, you use
add-record-field
. This puts you into a
special submode that allows you to identify the record's
various fields.
To define a simple two-column table where the primary key is a UID and the second column contains a record, 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 record field. This puts us into a new submode. add-record-field -name myRecord add-field -type STRING -name firstField add-field -type INTEGER -name secondField ### Exit array record creation mode exit ## 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 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); 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());