データベース・オブジェクトの作成
ネームスペースの作成
ネームスペースは表のグループを定義するもので、その中ですべての表名を一意に識別する必要があります。ネームスペースを使用すると、表権限の管理をグループ操作として実行できます。ネームスペースに認可権限を付与すると、ネームスペースとネームスペース内の表の両方にアクセスできるユーザーを決定できます。ネームスペースを使用すると、データベース・ストアに同じ名前の表を存在させることができます。このような表にアクセスするには、完全修飾の表名を使用します。完全修飾の表名では、表名の前にネームスペースがあり、その後にコロン(:)があります(ns1:table1
など)。
すべての表は、ネームスペースの一部です。sysdefault
というデフォルトのOracle NoSQL Databaseネームスペースがあります。すべての表は、他のネームスペースを作成し、そこに新しいテーブルを作成するまで、デフォルトのsysdefault
ネームスペースに割り当てられます。既存の表のネームスペースは変更できません。sysdefault
ネームスペースの表は、完全修飾名を必要とせず、表名のみで操作できます。
CREATE NAMESPACE
文を使用して、新しいネームスペースを追加できます。CREATE NAMESPACE [IF NOT EXISTS] namespace_name
ノート:
sys
で始まるネームスペース名は予約されています。接頭辞sys
は、どのネームスペースにも使用できません。
ns1
という名前のネームスペースを定義します。CREATE NAMESPACE IF NOT EXISTS ns1
APIの使用によるネームスペースの作成:
private static void createNS(NoSQLHandle handle) throws Exception {
String createNSDDL = "CREATE NAMESPACE IF NOT EXISTS ns1";
SystemRequest sysreq = new SystemRequest();
sysreq.setStatement(createNSDDL.toCharArray());
SystemResult sysres = handle.systemRequest(sysreq);
sysres.waitForCompletion(handle, 60000,1000);
System.out.println("Namespace " + nsName + " is created");
}
def create_ns(handle):
statement = '''CREATE NAMESPACE IF NOT EXISTS ns1'''
sysreq = SystemRequest().set_statement(statement)
sys_result = handle.system_request(sysreq)
sys_result.wait_for_completion(handle, 40000, 3000)
print('Created namespace: ns1')
func createNS(client *nosqldb.Client, err error)(){
stmt := fmt.Sprintf("CREATE NAMESPACE IF NOT EXISTS ns1")
sysReq := &nosqldb.SystemRequest{
Statement: stmt,
}
sysRes, err := client.DoSystemRequest(sysReq)
_, err = sysRes.WaitForCompletion(client, 60*time.Second, time.Second)
if err != nil {
fmt.Printf("Error finishing CREATE NAMESPACE request: %v\n", err)
return
}
fmt.Println("Created Namespace ns1 ")
return
}
async function createNS(handle) {
const createNS = `CREATE NAMESPACE IF NOT EXISTS ns1`;
let res = await handle.adminDDL(createNS);
console.log('Namespace created: ns1' );
}
private static async Task createNS(NoSQLClient client){
var sql =
$@"CREATE NAMESPACE IF NOT EXISTS ns1";
var adminResult = await client.ExecuteAdminAsync(sql);
// Wait for the operation completion
await adminResult.WaitForCompletionAsync();
Console.WriteLine(" Created namespace ns1");
}
表の作成
表は、ユーザー・データを保持するための基本構造です。CREATE TABLE文を使用して、Oracle NoSQL Databaseで新しい表を作成します。
- 表定義には、少なくとも1つのフィールド定義と、主キー定義を1つのみ含める必要があります。
- フィールド定義は、列の名前、データ型、列がNULL値可能かどうか、オプションのデフォルト値、または列がIDENTITY列かどうか、およびオプションのコメントを指定します。デフォルトでは、すべてのフィールド(PRIMARY KEY以外)はNULL値可能です。
- 主キー仕様の構文(key_definition)は、表の主キー列をフィールド名の順序付きリストとして指定します。
- 存続時間(TTL)値は、行の有効期限を計算するために使用されます。期限切れになった行は問合せ結果に含まれず、最終的にOracle NoSQL Databaseによって表から自動的に削除されます。表の作成時にTTL値を指定すると、この表に挿入されるすべての行のデフォルトのTTLとして適用されます。
- 作成する表がマルチリージョン表の場合は、REGIONS句を指定します。REGIONS句は、表がまたがるすべてのリージョンをリストします。
BaggageInfo
表を定義します。CREATE TABLE BaggageInfo (
ticketNo LONG,
fullName STRING,
gender STRING,
contactPhone STRING,
confNo STRING,
bagInfo JSON,
PRIMARY KEY (ticketNo)
)
stream_acct
表を定義します。CREATE TABLE stream_acct(
acct_id INTEGER,
profile_name STRING,
account_expiry TIMESTAMP(1),
acct_data JSON,
PRIMARY KEY(acct_id)
)
stream_acct_new
表を定義します。表の行は2日で失効します。CREATE TABLE stream_acct_new(
acct_id INTEGER,
profile_name STRING,
account_expiry TIMESTAMP(1),
acct_data JSON,
PRIMARY KEY(acct_id)) USING TTL 2 days
APIの使用による表の作成:
private static void createTab(NoSQLHandle handle) throws Exception {
String createTableDDL =
"CREATE TABLE IF NOT EXISTS " + tableName +
"(acct_Id INTEGER," +
"profile_name STRING," +
"account_expiry TIMESTAMP(1) ," +
"acct_data JSON, " +
"PRIMARY KEY(acct_Id))";
TableLimits limits = new TableLimits(20, 20, 1);
TableRequest treq = new TableRequest()
.setStatement(createTableDDL)
.setTableLimits(limits);
TableResult tres = handle.tableRequest(treq);
/* The request is async,
* so wait for the table to become active.
*/
tres.waitForCompletion(handle, 60000,1000);
System.out.println("Created Table: " + tableName);
}
def create_table(handle):
statement = '''create table if not exists
stream_acct (acct_Id INTEGER,
profile_name STRING,
account_expiry TIMESTAMP(1),
acct_data JSON,
primary key(acct_Id))'''
request = TableRequest().set_statement(statement)
.set_table_limits(TableLimits(20, 10, 1))
table_result = handle.do_table_request(request, 40000, 3000)
table_result.wait_for_completion(handle, 40000, 3000)
if (table_result.get_state() == State.ACTIVE):
print('Created table: stream_acct')
else:
raise NameError('Table stream_acct is in an unexpected state ' +
str(table_result.get_state()))
func createTable(client *nosqldb.Client, err error, tableName string)(){
// Creates a table
stmt := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s ("+
"acct_Id INTEGER," +
"profile_name STRING," +
"account_expiry TIMESTAMP(1) ," +
"acct_data JSON, " +
"PRIMARY KEY(acct_Id))",tableName)
tableReq := &nosqldb.TableRequest{
Statement: stmt,
TableLimits: &nosqldb.TableLimits{
ReadUnits: 20,
WriteUnits: 20,
StorageGB: 1,
},
}
tableRes, err := client.DoTableRequest(tableReq)
if err != nil {
fmt.Printf("cannot initiate CREATE TABLE request: %v\n", err)
return
}
// The create table request is asynchronous,
// wait for table creation to complete.
_, 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)
return
}
async function createTable(handle) {
const createDDL = `CREATE TABLE IF NOT EXISTS
${TABLE_NAME} (acct_Id INTEGER,
profile_name STRING,
account_expiry TIMESTAMP(1),
acct_data JSON,
primary key(acct_Id))`;
let res = await handle.tableDDL(createDDL, {
complete: true,
tableLimits: {
readUnits: 20,
writeUnits: 20,
storageGB: 1
}
});
console.log('Created table: ' + TABLE_NAME);
}
private static async Task createTable(NoSQLClient client){
// Create a table
var sql =
$@"CREATE TABLE IF NOT EXISTS
{TableName}(acct_Id INTEGER,
profile_name STRING,
account_expiry TIMESTAMP(1),
acct_data JSON,
primary key(acct_Id))";
var tableResult = await client.ExecuteTableDDLAsync(sql,
new TableDDLOptions{TableLimits = new TableLimits(20, 20, 1)});
// Wait for the operation completion
await tableResult.WaitForCompletionAsync();
Console.WriteLine(" Created table: ",tableResult.TableName);
}
リージョンの作成
Oracle NoSQL Databaseでは複数のKVStoreに表を作成できるマルチリージョン・アーキテクチャがサポートされ、表がまたがるすべてのリージョンにわたり、挿入、更新および削除が、Oracle NoSQL Databaseによって複数方向に自動的にレプリケートされます。マルチリージョンのNoSQL Database設定においては、各KVStoreクラスタがリージョンと呼ばれます。
my_region1
という名前のリモート・リージョンを作成します。
CREATE REGION my_region1
マルチリージョンのOracle NoSQL Database設定では、各ローカル・リージョンに対してすべてのリモート・リージョンを定義する必要があります。たとえば、マルチリージョン設定に3つのリージョンがある場合、それぞれの参加リージョンで他の2つのリージョンを定義する必要があります。CREATE REGION文を使用して、マルチリージョンのOracle NoSQL Databaseでリモート・リージョンを定義します。
例2: リージョンに表を作成します。
CREATE TABLE stream_acct_region(acct_id INTEGER,
acct_data JSON,
PRIMARY KEY(acct_id)) IN REGIONS my_region1
ノート:
表を作成する前に、リージョンmy_region1
をローカル・リージョンとして設定する必要があります。
APIの使用によるリージョンの作成:
/* Create a remote region and a local region*/
private static void crtRegion(NoSQLHandle handle) throws Exception {
// Create a remote region
String createRemRegDDL = "CREATE REGION "+ remRegName;
SystemRequest sysreq1 = new SystemRequest();
sysreq1.setStatement(createRemRegDDL.toCharArray());
SystemResult sysres1 = handle.systemRequest(sysreq1);
sysres1.waitForCompletion(handle, 60000,1000);
System.out.println(" Remote Region " + remRegName + " is created");
// Create a local region
String createLocRegDDL = "SET LOCAL REGION "+ localRegName;
SystemRequest sysreq2 = new SystemRequest();
sysreq2.setStatement(createLocRegDDL.toCharArray());
SystemResult sysres2 = handle.systemRequest(sysreq2);
sysres2.waitForCompletion(handle, 60000,1000);
System.out.println(" Local Region " + localRegName + " is created");
}
/**
* Create a table and add the table in a region
*/
private static void crtTabInRegion(NoSQLHandle handle) throws Exception {
String createTableDDL = "CREATE TABLE IF NOT EXISTS " + tableName +
"(acct_Id INTEGER," +
"profile_name STRING," +
"account_expiry TIMESTAMP(1) ," +
"acct_data JSON, " +
"PRIMARY KEY(acct_Id)) IN REGIONS FRA";
TableLimits limits = new TableLimits(20, 20, 1);
TableRequest treq = new TableRequest()
.setStatement(createTableDDL).setTableLimits(limits);
TableResult tres = handle.tableRequest(treq);
/* The request is async,
* so wait for the table to become active.
*/
System.out.println("Table " + tableName + " is active");
}
# create a remote and local region
def create_region(handle):
#Create a remote region
statement = '''CREATE REGION LON'''
sysreq = SystemRequest().set_statement(statement)
sys_result = handle.system_request(sysreq)
sys_result.wait_for_completion(handle, 40000, 3000)
print('Remote region LON is created')
#Create a local region
statement1 = '''SET LOCAL REGION FRA'''
sysreq1 = SystemRequest().set_statement(statement1)
sys_result1 = handle.system_request(sysreq1)
sys_result1.wait_for_completion(handle, 40000, 3000)
print('Local region FRA is created')
#Create a table in the local region
def create_tab_region(handle):
statement = '''create table if not exists stream_acct (acct_Id INTEGER,
profile_name STRING,
account_expiry TIMESTAMP(1),
acct_data JSON,
primary key(acct_Id)) IN REGIONS FRA'''
request = TableRequest().set_statement(statement).set_table_limits(TableLimits(20, 10, 1))
# Ask the cloud service to create the table, waiting for a total of 40000 milliseconds
# and polling the service every 3000 milliseconds to see if the table is active
table_result = handle.do_table_request(request, 40000, 3000)
table_result.wait_for_completion(handle, 40000, 3000)
if (table_result.get_state() == State.ACTIVE):
print('Created table: stream_acct')
else:
raise NameError('Table stream_acct is in an unexpected state ' + str(table_result.get_state()))
//Creates a remote and a local region
func crtRegion(client *nosqldb.Client, err error)(){
// Create a remote region
stmt := fmt.Sprintf("CREATE REGION LON")
sysReq := &nosqldb.SystemRequest{
Statement: stmt,
}
sysRes, err := client.DoSystemRequest(sysReq)
_, err = sysRes.WaitForCompletion(client, 60*time.Second, time.Second)
if err != nil {
fmt.Printf("Error finishing CREATE REGION request: %v\n", err)
return
}
fmt.Println("Created REGION LON ")
// Create a local region
stmt1 := fmt.Sprintf("SET LOCAL REGION FRA")
sysReq1 := &nosqldb.SystemRequest{
Statement: stmt1,
}
sysRes1, err1 := client.DoSystemRequest(sysReq1)
_, err1 = sysRes1.WaitForCompletion(client, 60*time.Second, time.Second)
if err1 != nil {
fmt.Printf("Error finishing CREATE REGION request: %v\n", err)
return
}
fmt.Println("Created REGION FRA ")
return
}
//creates a table in a specific region
func crtTabInRegion(client *nosqldb.Client, err error, tableName string)(){
stmt := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s ("+
"acct_Id INTEGER," +
"profile_name STRING," +
"account_expiry TIMESTAMP(1) ," +
"acct_data JSON, " +
"PRIMARY KEY(acct_Id)) IN REGIONS FRA",tableName)
tableReq := &nosqldb.TableRequest{
Statement: stmt,
TableLimits: &nosqldb.TableLimits{
ReadUnits: 20,
WriteUnits: 20,
StorageGB: 1,
},
}
tableRes, err := client.DoTableRequest(tableReq)
if err != nil {
fmt.Printf("cannot initiate CREATE TABLE request: %v\n", err)
return
}
// The create table request is asynchronous, wait for table creation to complete.
_, 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)
return
}
//creates a remote and a local region
async function createRegion(handle) {
// Create a remote region
const crtRemReg = `CREATE REGION LON`;
let res = await handle.adminDDL(crtRemReg);
console.log('Remote region created: LON' );
// Create a local region
const crtLocalReg = `SET LOCAL REGION FRA`;
let res1 = await handle.adminDDL(crtLocalReg);
console.log('Local region created: FRA' );
}
//creates a table in a given region
async function crtTabInRegion(handle) {
const createDDL = `CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (acct_Id INTEGER,
profile_name STRING,
account_expiry TIMESTAMP(1),
acct_data JSON,
primary key(acct_Id)) IN REGIONS FRA`;
let res = await handle.tableDDL(createDDL, {
complete: true,
tableLimits: {
readUnits: 20,
writeUnits: 20,
storageGB: 1
}
});
console.log('Table created: ' + TABLE_NAME);
}
private static async Task createRegion(NoSQLClient client){
// Create a remote region
var sql = $@"CREATE REGION LON";
var adminResult = await client.ExecuteAdminAsync(sql);
// Wait for the operation completion
await adminResult.WaitForCompletionAsync();
Console.WriteLine(" Created remote REGION LON");
// Create a local region
var sql1 = $@"SET LOCAL REGION FRA";
var adminResult1 = await client.ExecuteAdminAsync(sql1);
// Wait for the operation completion
await adminResult1.WaitForCompletionAsync();
Console.WriteLine(" Created local REGION FRA");
}
private static async Task createTabInRegion(NoSQLClient client){
// Create a table
var sql =
$@"CREATE TABLE IF NOT EXISTS {TableName}(acct_Id INTEGER,
profile_name STRING,
account_expiry TIMESTAMP(1),
acct_data JSON,
primary key(acct_Id)) IN REGIONS FRA";
Console.WriteLine("\nCreate table {0}", TableName);
var tableResult = await client.ExecuteTableDDLAsync(sql,
new TableDDLOptions{
TableLimits = new TableLimits(20, 20, 1)
});
// Wait for the operation completion
await tableResult.WaitForCompletionAsync();
Console.WriteLine(" Table {0} is created",tableResult.TableName);
Console.WriteLine(" Table state: {0}", tableResult.TableState);
}