埋込みレコードの索引付け
レコード・フィールドにスカラー・データが含まれている場合には、埋込みレコードに索引を作成できます。索引を作成するには、通常のレコードとして定義します。フィールドを索引付けするには、埋込みレコードの名前を指定し、さらに、ドット表記法を使用してフィールドの名前を指定します。
索引を作成するには、まず表を作成します。
CREATE Table myRecordTable (
uid INTEGER,
myRecord RECORD (firstField STRING, secondField INTEGER),
PRIMARY KEY (uid)
)
表がストアに追加された後、索引を作成します。
CREATE INDEX recordFieldIndex on myRecordTable (myRecord.secondField)
表の行に指定した値が付いた指定したレコード・フィールドが含まれている場合、データが取得されます。つまり、たとえば、次のような一連の表の行を作成する場合、
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);
指定した値に「secondField」が設定されている埋込みレコードを含む任意の表の行を取得できます。(前述の指定した埋込みレコード索引、索引付けされたmyRecord.secondField。)
レコード索引を使用してデータを取得するには、まず名前を使用して索引を取得し、索引参照の実行に使用するIndexKey
のインスタンスを作成します。
Index recordIndex = myTable.getIndex("recordFieldIndex");
IndexKey indexKey = recordIndex.createIndexKey();
indexKey.put(“myRecord.secondField", 3388);
索引参照を実行するとき、返されるレコードは指定したフィールドおよびフィールド値付きの埋込みレコードがあるレコードのみです。その後、一致する表の行を取得し、別の索引タイプと同じ方法で繰り返します。次に例を示します。
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();
}
}