表および索引の作成
表および索引の作成方法について学習します。
APIクラスおよびメソッドを使用して、表の作成、変更、削除など、すべてのDDL文を実行します。APIメソッドを使用して表の制限を設定することもできます。
DDL文の例を次に示します。
/* Create a new table called users */
CREATE TABLE 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 TABLE 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";
/* Call the appropriate constructor for
* 1) Provisioned Capacity
* TableLimits limits = new TableLimits(200, 100, 5);
* 2) On-demand Capacity - only set storage limit
* TableLimits limits = new TableLimits( 5 );
* In this example, we will use Provisioned Capacity
*/
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);
borneo.TableRequest
クラスを使用して実行されます。borneo.NoSQLHandle.table_request()
へのすべてのコールは非同期であるため、結果を確認し、borneo.TableResult.wait_for_completion()
をコールして操作が完了するまで待機する必要があります。
#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.
from borneo import TableLimits,
TableRequest statement = 'create table if not exists users(id integer,
name string,
' + 'primary key(id)
USING TTL 3 DAYS'
# In the Cloud Service TableLimits is a required object for table
#creation. It specifies the throughput and capacity for the table in
#ReadUnits, WriteUnits, GB
# Call the appropriate constructor for
# 1) Provisioned Capacity
# TableLimits(50, 50, 25);
# 2) On-demand Capacity - only set storage limit
# TableLimits( 25 );
# In this example, we will use Provisioned Capacity
request = TableRequest().set_statement(statement).
set_table_limits( TableLimits(50, 50, 25))
# assume that a handle has been created, as handle, make the request
#wait for 60 seconds, polling every 1 seconds
result = handle.do_table_request(request, 60000, 1000)
# the above call to do_table_request is equivalent to
# result = handle.table_request(request)
result.wait_for_completion(handle, 60000, 1000)
#Create an index called nameIdx on the name field in the users table.
request = TableRequest().set_statement("CREATE INDEX IF NOT EXISTS nameIdx
ON users(name)")
# assume that a handle has been created, as handle, make the request
#wait for 60 seconds, polling every 1 seconds
result = handle.do_table_request(request, 60000, 1000)
# the above call to do_table_request is equivalent to
# result = handle.table_request(request)
result.wait_for_completion(handle, 60000, 1000)
// 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.
tableName := "users"
stmt := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s "+
"(id integer, name STRING, PRIMARY KEY(id) "+
"USING TTL 3 DAYS)", tableName)
// Call the appropriate constructor for
// 1) Provisioned Capacity
// &nosqldb.TableLimits(ReadUnits: 50, WriteUnits: 50, StorageGB: 25);
// 2) On-demand Capacity - only set storage limit
// &nosqldb.TableLimits(StorageGB: 25 );
// In this example, we will use Provisioned Capacity
tableReq := &nosqldb.TableRequest{
Statement: stmt,
TableLimits: &nosqldb.TableLimits{
ReadUnits: 50,
WriteUnits: 50,
StorageGB: 25,
},
}
tableRes, err := client.DoTableRequest(tableReq)
if err != nil {
fmt.Printf("cannot initiate CREATE TABLE request: %v\n", err)
return
}
_, err = tableRes.WaitForCompletion(client, 60*time.Second, time.Second)
if err != nil {
fmt.Printf("Error finishing CREATE TABLE request: %v\n", err)
return
}
fmt.Println("Created table ", tableName)
//Create an index called nameIdx on the name field in the users table
stmt_ind := fmt.Sprintf("CREATE INDEX IF NOT EXISTS nameIdx ON users(name)")
tableReq := &nosqldb.TableRequest{Statement: stmt_ind}
tableRes, err := client.DoTableRequest(tableReq)
if err != nil {
fmt.Printf("cannot initiate CREATE INDEX request: %v\n", err)
return
}
_, err = tableRes.WaitForCompletion(client, 60*time.Second, time.Second)
if err != nil {
fmt.Printf("Error finishing CREATE INDEX request: %v\n", err)
return
}
fmt.Println("Created index nameIdx ")
表DDL文は、tableDDL
メソッドによって実行されます。NoSQLClient
クラスの他のほとんどのメソッドと同様に、このメソッドは非同期で、TableResult
のPromiseを返します。TableResult
は、DDL操作のステータス(TableState、名前、スキーマ、TableLimitなど)を含むプレーンJavaScriptオブジェクトです。
tableDDL
メソッドは、2番目のオプション引数としてoptオブジェクトを使用します。表を作成する場合は、opt引数の一部としてTableLimitsを指定する必要があります。TableLimitsでは、読取りユニット、書込みユニットおよびストレージのギガバイトの量として、表の最大スループットおよびストレージ容量を指定します。
tableDDL
メソッドは、指定されたDDL操作のみを基礎となるストアで起動し、完了を待機しないことに注意してください。結果のTableResult
は、通常、TableState.CREATING
、TableState.DROPPING
、TableState.UPDATING
などの中間表の状態の1つを持ちます(後者は、表がALTER TABLE文によって変更されるプロセス中であるか、表の制限が変更されているか、その索引のいずれかが作成または削除されている場合に発生します)。
TableState.ACTIVE
またはTableState.DROPPED
に変更されます(DDL操作がDROP TABLEだった場合は後者)。const NoSQLClient = require('oracle-nosqldb').NoSQLClient;
const TableState = require('oracle-nosqldb').TableState;
const client = new NoSQLClient('config.json');
async function createUsersTable() {
try {
const statement = 'CREATE TABLE IF NOT EXISTS users(id INTEGER, ' +
'name STRING, PRIMARY KEY(id))';
// Call the appropriate constructor for
// 1) Provisioned Capacity
// tableLimits: {readUnits: 20, writeUnits: 10, storageGB: 5);
// 2) On-demand Capacity - only set storage limit
// tableLimits: {storageGB: 5 );
// In this example, we will use Provisioned Capacity
let result = await client.tableDDL(statement, {
tableLimits: {
readUnits: 20,
writeUnits: 10,
storageGB: 5
}
});
result = await client.forCompletion(result);
console.log('Table users created');
} catch(error) {
//handle errors
}
}
const statement = 'CREATE TABLE IF NOT EXISTS users(id INTEGER, ' +
'name STRING, PRIMARY KEY(id))';
// Call the appropriate constructor for
// 1) Provisioned Capacity
// tableLimits: {readUnits: 20, writeUnits: 10, storageGB: 5);
// 2) On-demand Capacity - only set storage limit
// tableLimits: {storageGB: 5 );
// In this example, we will use Provisioned Capacity
let result = await client.tableDDL(statement, {
tableLimits: {
readUnits: 20,
writeUnits: 10,
storageGB: 5
},
complete: true
});
console.log('Table users created');
CREATE TABLE以外のDDL操作にTableLimits
を指定する必要はありません。setTableLimits
メソッドをコールして表を作成した後に、表の表制限を変更することもできます。これは、tableDDL
によって開始された操作の完了を待機するのと同じ方法で、操作の完了を待機することが必要になる場合もあります。
// Create an index called nameIdx on the name field in the users table.
try {
const statement = 'CREATE INDEX IF NOT EXISTS nameIdx ON users(name))';
let result = await client.tableDDL(statement);
result = await client.forCompletion(result);
console.log('Index nameIdx created');
} catch(error){
//handle errors
}
表を作成し、他のデータ定義言語(DDL)文(表の作成、変更および削除、索引の作成および削除など)を実行するには、ExecuteTableDDLAsync
およびExecuteTableDDLWithCompletionAsync
メソッドを使用します。メソッドExecuteTableDDLAsync
およびExecuteTableDDLWithCompletionAsync
は、Task<TableResult>
を返します。TableResultインスタンスには、TableState、表スキーマ、TableLimitsなどのDDL操作のステータスが含まれています。これらの各メソッドには、複数のオーバーロードがあります。特に、DDL操作のオプションをTableDDLOptions
として渡すことができます。
TableDDLOptions
のTableLimits
プロパティとして表制限を渡すことができます。これらは長時間実行される可能性があることに注意してください。メソッドExecuteTableDDLAsync
は、サービスによって指定されたDDL操作のみを起動し、その完了を待機しません。返されるTableResultインスタンスでWaitForCompletionAsync
をコールすることで、表DDL操作の完了を非同期で待機できます。var client = new NoSQLClient("config.json");
try {
var statement = "CREATE TABLE IF NOT EXISTS users(id INTEGER,"
+ "name STRING, PRIMARY KEY(id))";
// Call the appropriate constructor for
// 1) Provisioned Capacity
// new TableLimits(20, 10, 5);
// 2) On-demand Capacity - only set storage limit
// new TableLimits( 5 );
// In this example, we will use Provisioned Capacity
var result = await client.ExecuteTableDDLAsync(statement, new
TableLimits(20, 10, 5));
await result.WaitForCompletionAsync();
Console.WriteLine("Table users created.");
} catch(Exception ex) {
// handle exceptions
}
WaitForCompletionAsync
は、操作の完了を反映するようにコール元のTableResultインスタンスを変更することに注意してください。
ExecuteTableDDLWithCompletionAsync
を使用することもできます。try-catchブロックの文を次のように置き換えます。var statement = "CREATE TABLE IF NOT EXISTS users(id INTEGER,"
+ "name STRING, PRIMARY KEY(id))";
// Call the appropriate constructor for
// 1) Provisioned Capacity
// new TableLimits(20, 10, 5);
// 2) On-demand Capacity - only set storage limit
// new TableLimits( 5 );
// In this example, we will use Provisioned Capacity
await client.ExecuteTableDDLWithCompletionAsync(statement,
new TableLimits(20, 10, 5));
Console.WriteLine("Table users created.");
CREATE TABLE以外のDDL操作にTableLimitsを指定する必要はありません。SetTableLimitsAsync
またはSetTableLimitsWithCompletionAsync
メソッドをコールして、既存の表の表制限を変更することもできます。