Previous Next JavaScript must be enabled to correctly display this content

## Indexing Embedded Records

You can create an index on an embedded record field so long as the record field contains scalar data. To create the index, define the record as normal. To index the field, you specify the name of the embedded record and the name of the field using dot notation.

To create the index, first create the table:

    CREATE Table myRecordTable (
        uid INTEGER,
        myRecord RECORD (firstField STRING, secondField INTEGER),
        PRIMARY KEY (uid)
    )

Once the table has been added to the store, create the index:

    CREATE INDEX recordFieldIndex on myRecordTable (myRecord.secondField)

Data is retrieved if the table row contains the identified record field with the specified value. So, for example, if you create a series of table rows like this:

    TableAPI tableH = kvstore.getTableAPI();
    Table myTable = tableH.getTable("myRecordTable");

    Row row = myTable.createRow();
    row.put("uid", 12345);
    RecordValue rv = row.putRecord("myRecord");
    rv.put("firstField", "String field for 12345");
    rv.put("secondField", 3388);
    tableH.put(row, null, null);

    row = myTable.createRow();
    row.put("uid", 345);
    rv = row.putRecord("myRecord");
    rv.put("firstField", "String field for 345");
    rv.put("secondField", 3388);
    tableH.put(row, null, null);

    row = myTable.createRow();
    row.put("uid", 111);
    rv = row.putRecord("myRecord");
    rv.put("firstField", "String field for 111");
    rv.put("secondField", 12);
    tableH.put(row, null, null);

then you can retrieve any table rows that contain the embedded record where "secondField" is set to a specified value. (The embedded record index that we specified, above, indexed myRecord.secondField.)

To retrieve data using a record index, you first retrieve the index using its name, and create an instance of `IndexKey` that you will use to perform the index lookup:

    Index recordIndex = myTable.getIndex("recordFieldIndex");
    IndexKey indexKey = recordIndex.createIndexKey();
    indexKey.put(“myRecord.secondField", 3388);

When you perform the index lookup, the only records returned will be those which have an embedded record with the specified field and field value. You then retrieve the matching table rows, and iterate over them in the same way you would any other index type. For example:

    TableIterator<Row> iter = tableH.tableIterator(indexKey, null, null);
    System.out.println("Results for testRecord.secondField, value 3388: ");
    try {
        while (iter.hasNext()) {
            Row rowRet = iter.next();
            int uid = rowRet.get("uid").asInteger().get();
            System.out.println("uid: " + uid);
            RecordValue recordRet = rowRet.get("myRecord").asRecord();
            System.out.println("myRecord: " + recordRet.toString());
        }
    } finally {
        if (iter != null) {
            iter.close();
        }
    }