使用 API 创建单例表

该表是保存用户数据的基本结构。可以使用 SQL 命令(CREATE TABLE 语句)或 TableRequest API 命令创建新表。

您还可以使用 Oracle NoSQL Cloud Infrastructure (OCI) 控制台或 OCI 命令行界面 (OCI-cli) 在 NDCS 中创建表。

创建表的准则:
  • 表定义必须至少包括一个字段定义和一个主键定义。有关主键定义的更多信息,请参阅创建表
  • 字段定义指定列的名称、其数据类型、列是否可为空、可选默认值以及列是否为 IDENTITY 列和可选注释。默认情况下,所有字段(PRIMARY KEY 除外)均可为空。
  • 主键规范 (key_definition) 的语法将表的主键列指定为字段名的有序列表。
  • 生存时间 (TTL) 值用于计算行的失效时间。查询结果中不包括失效行,Oracle NoSQL Database 最终会自动从表中删除失效行。如果在创建表时指定 TTL 值,则该值将作为插入到此表中的每一行的默认 TTL 应用。

使用 SQL 命令

可以在 SQL 中使用 CREATE TABLE 命令创建 NoSQL 表。

示例 1:以下 CREATE TABLE 语句定义了一个 BaggageInfo 表,用于保存航空公司系统中乘客的行李信息。
CREATE TABLE BaggageInfo (
ticketNo LONG,
fullName STRING,
gender STRING,
contactPhone STRING,
confNo STRING,
bagInfo JSON,
PRIMARY KEY (ticketNo)
)
示例 2:以下 CREATE TABLE 语句定义了一个 stream_acct 表,用于保存来自电视流应用程序的数据。
CREATE TABLE stream_acct(
acct_id INTEGER,
profile_name STRING,
account_expiry TIMESTAMP(1),
acct_data JSON, 
PRIMARY KEY(acct_id)
)
示例 3:以下 CREATE TABLE 语句定义了一个 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

使用 TableRequest API

可以使用 TableRequest API 创建 NoSQL 表。

TableRequest 类用于创建表。执行此请求指定的操作是异步的。这些可能是长时间运行的操作。TableResultTableRequest 操作返回,它封装表的状态。有关 TableRequest 类及其方法的更多详细信息,请参阅 Oracle NoSQL Java SDK API Reference

Download the full code CreateTable.java from the examples here.
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);
}

注意:

表限制仅适用于 Oracle NoSQL Database Cloud Service。如果为内部部署 NoSQL 数据库设置了限制,则会无提示地忽略这些限制。

创建子表:可以使用相同的 TableRequest 类和方法执行 DDL 语句来创建子表。

创建子表时:
  • 您需要指定表的全名 (name_parent_table.name_child_table)
  • 不需要显式设置表限制,因为子表会继承父表的限制。

从示例下载完整代码 TableJoins.java,以了解如何在此处创建父子表。

borneo.TableRequest 类用于创建表。对 borneo.NoSQLHandle.table_request() 的所有调用都是异步的,因此需要检查结果并调用 borneo.TableResult.wait_for_completion() 等待操作完成。有关 table_request 及其方法的更多详细信息,请参阅 Oracle NoSQL Python SDK API Reference

Download the full code CreateTable.py from the examples here.
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()))

注意:

表限制仅适用于 Oracle NoSQL Database Cloud Service。如果为内部部署 NoSQL 数据库设置了限制,则会无提示地忽略这些限制。

创建子表:可以使用相同的 TableRequest 类和方法执行 DDL 语句来创建子表。

创建子表时:
  • 您需要指定表的全名 (name_parent_table.name_child_table)。
  • 不需要显式设置表限制,因为子表会继承父表的限制。

Download the full code TableJoins.py from the examples here.

The TableRequest class is used to create a table. Execution of operations specified by TableRequest is asynchronous. These are potentially long-running operations. This request is used as the input of a Client.DoTableRequest() operation, which returns a TableResult that can be used to poll until the table reaches the desired state. See Oracle NoSQL Go SDK API Reference for more details on the various methods of the TableRequest class.

Download the full code CreateTable.go from the examples here.
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
}

注意:

表限制仅适用于 Oracle NoSQL Database Cloud Service。如果为内部部署 NoSQL 数据库设置了限制,则会无提示地忽略这些限制。

创建子表:可以使用相同的 TableRequest 类和方法执行 DDL 语句来创建子表。

创建子表时:
  • 您需要指定表的全名 (name_parent_table.name_child_table)。
  • 不需要显式设置表限制,因为子表会继承父表的限制。

Download the full code TableJoins.go from the examples here.

可以使用 tableDDL 方法创建表。此方法为异步方法,返回 Promise TableResultTableResult 是一个纯 JavaScript 对象,它包含 DDL 操作的状态,例如其 TableState、名称、方案及其 TableLimits。有关方法详细信息,请参见 NoSQLClient 类。

tableDDL 方法将 TableDDLOpt 对象作为第二个可选参数。创建表时,必须将其 TableLimits 指定为 opt 参数的一部分。TableLimits 将表的最大吞吐量和存储容量指定为读取单位数、写入单位数和存储量 (GB)。

Download the full JavaScript code CreateTable.js from the examples here and the full TypeScript code CreateTable.ts from the examples here.

import {NoSQLClient, TableState } from 'oracle-nosqldb';
const client = new NoSQLClient('config.json');
const TABLE_NAME = 'stream_acct;
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))`;
   /* For Provisioned Capacity specify read units, write units, and storage limit as shown below*/
   /* For On-demand Capacity - set only the storage limit and specify the mode as shown here.
    * { storageGB: 25, mode: CapacityMode.ON_DEMAND }; 
    */
  let res =  await handle.tableDDL(createDDL, {
             complete: true,
             tableLimits: {
              readUnits: 20,
              writeUnits: 20,
              storageGB: 1
             }
  });
  console.log('Created table: ' + TABLE_NAME);
}
在上述调用返回之后,结果将反映操作的最终状态。或者,要使用完整选项,请使用以下代码示例替换上面的 try-catch 块中的代码。
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 client.tableDDL(createDDL, {complete: true,});
console.log('Created table: ' + TABLE_NAME);

创建子表:可以使用相同的 TableRequest 类和方法执行 DDL 语句来创建子表。

创建子表时:
  • 您需要指定表的全名 (name_parent_table.name_child_table)
  • 不需要显式设置表限制,因为子表会继承父表的限制。

Download the full JavaScript code TableJoins.js from the examples here and the full TypeScript code TableJoins.ts from the examples here.

要创建表,请使用方法 ExecuteTableDDLAsyncExecuteTableDDLWithCompletionAsync。这两种方法均返回 Task<TableResult>TableResult 实例包含 DDL 操作的状态,例如 TableState 和表方案。有关这些方法的更多详细信息,请参阅 Oracle NoSQL Dotnet SDK API Reference

Download the full code CreateTable.cs from the examples here.
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 Cloud Service。如果为内部部署 NoSQL 数据库设置了限制,则会无提示地忽略这些限制。

创建子表:可以使用相同的 TableRequest 类和方法执行 DDL 语句来创建子表。

创建子表时:
  • 您需要指定表的全名 (name_parent_table.name_child_table)
  • 不需要显式设置表限制,因为子表会继承父表的限制。

Download the full code TableJoins.cs from the examples here.