本文介紹如何通過Node.js SDK建立Table Store的資料表。
注意事項
建立資料表後,請等待資料表載入完成後再進行資料操作,否則資料操作會失敗,這個過程通常需要幾秒鐘。
前提條件
方法說明
createTable: function createTable(params, callback)
範例程式碼
建立資料表
以下範例程式碼建立了一張test_table表,該表包含1個 String類型的主鍵。
var params = {
// 資料表的結構資訊
tableMeta: {
tableName: 'test_table',
// 建立資料表至少需要添加一個主鍵
primaryKey: [
{
name: 'id',
type: 'STRING'
}
],
// (可選)添加預定義列
definedColumn: [
{
name: 'name',
type: TableStore.DefinedColumnType.DCT_STRING
}
]
},
// 資料表的配置資訊
tableOptions: {
// 建立資料表時必須指定資料生命週期,-1表示資料永不到期
timeToLive: -1,
// 建立資料表時必須指定最大版本數
maxVersions: 1,
// (可選)設定有效版本偏差
maxTimeDeviation: 86400,
// (可選)設定是否允許更新
allowUpdate: true
},
// 建立資料表時必須設定預留讀寫輸送量(僅CU模式高效能執行個體支援設定資料表的預留讀寫輸送量為非零值)
reservedThroughput: {
capacityUnit: {
read: 0,
write: 0
}
},
// (可選)設定Stream資訊
streamSpecification: {
enableStream: true,
expirationTime: 168
}
};
client.createTable(params, function (err, data) {
if (err) {
console.error('error:', err);
return;
}
console.log('success:', data);
});
建立資料表時配置二級索引
以下範例程式碼建立資料表並配置二級索引。
var params = {
// 資料表結構資訊
tableMeta: {
tableName: 'test_table',
// 主鍵
primaryKey: [
{
name: 'id',
type: 'STRING'
}
],
// 預定義列
definedColumn: [
{
name: 'name',
type: TableStore.DefinedColumnType.DCT_STRING
}
]
},
// 資料表配置資訊
tableOptions: {
// 資料生命週期
timeToLive: -1,
// 最大版本數
maxVersions: 1
},
// 預留讀寫輸送量(僅CU模式高效能執行個體支援設定資料表的預留讀寫輸送量為非零值)
reservedThroughput: {
capacityUnit: {
read: 0,
write: 0
}
},
// 二級索引資訊
indexMetas: [
{
name: 'test_table_index',
// 索引主鍵
primaryKey: ['id'],
// 索引預定義列
definedColumn: ['name'],
//索引類型
indexType: TableStore.IndexType.IT_LOCAL_INDEX,
//索引更新模式
indexUpdateMode: TableStore.IndexUpdateMode.IUM_SYNC_INDEX
}
]
};
client.createTable(params, function (err, data) {
if (err) {
console.error('error:', err);
return;
}
console.log('success:', data);
});