表および索引の作成

表および索引の作成方法について学習します。

表の作成は、アプリケーション開発の最初のステップです。TableRequestクラスおよびメソッドを使用して、表の作成、変更、削除など、すべてのDDL文を実行します。

TableRequestクラスを使用すると、DDL文をTableRequest.setStatementメソッドに渡すことができます。DDL文の例を次に示します。

/* Create a new table called users */
CREATE IF NOT EXISTS users(id INTEGER,
 name STRING,
 PRIMARY KEY(id));

/* Create a new table called users and set the TTL value to 4 days */
CREATE IF NOT EXISTS users(id INTEGER,
 name STRING,
 PRIMARY KEY(id))
USING TTL 4 days;

/* Create a new multi-region table called users with two regions, and set the TTL value to 4 days */
CREATE TABLE users(
 id INTEGER,
 name STRING,
 team STRING,
 primary key(id))
USING TTL 4 DAYS IN REGIONS fra, lnd;

/* Create a new index called nameIdx on the name field in the users table */
CREATE INDEX IF NOT EXISTS nameIdx ON users(name);

TableRequestとそのメソッドを使用して表と索引を作成するには、次のようにします。

/* Create a simple table with an integer key and a single json data
 * field  and set your desired table capacity.
 * Set the table TTL value to 3 days.
 */
String createTableDDL = "CREATE TABLE IF NOT EXISTS users " +
 "(id INTEGER, name STRING, " +
 "PRIMARY KEY(id)) USING TTL 3 days";


TableRequest treq = new TableRequest().setStatement(createTableDDL);
// start the asynchronous operation
TableResult tres = handle.tableRequest(treq);


// The table request is asynchronous, so wait for the table to become active.
TableResult.waitForState(handle, tres.getTableName(),
 TableResult.State.ACTIVE,
 60000, // wait for 60 sec
 1000); // delay in ms for poll 

// Create an index called nameIdx on the name field in the users table.
treq = new TableRequest().setStatement("CREATE INDEX 
  IF NOT EXISTS nameIdx ON users(name)
  ");

// start the asynchronous operation
  handle.tableRequest(treq);