### Build Tablestore SDK for Browser Source: https://github.com/aliyun/aliyun-tablestore-nodejs-sdk/blob/master/browser.md Use browserify to bundle the SDK and then uglifyjs to minify it for browser deployment. Ensure you have installed the necessary tools like browserify and uglifyjs globally. ```sh browserify browser.js > tablestore-js-sdk.js ``` ```sh uglifyjs tablestore-js-sdk.js -o tablestore-js-sdk.min.js ``` -------------------------------- ### KnowledgeBase API Operations Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Provides full lifecycle management for Knowledge Bases, including creation, description, listing, deletion, and managing documents (adding, getting, listing, deleting). It also supports semantic retrieval (Retrieve) for AI applications like RAG. ```APIDOC ## 知识库操作(KnowledgeBase API) 知识库 API 使用 JSON 协议(而非 Protobuf),提供完整的知识库生命周期管理:创建、描述、列出、删除知识库,以及添加/获取/列出/删除文档,并支持语义检索(Retrieve)。适用于 RAG(检索增强生成)等 AI 应用场景。 ```javascript // 创建知识库 await client.createKnowledgeBase({ instanceName: 'my-instance', knowledgeBaseName: 'my-kb', description: '产品手册知识库' }); // 添加文档到知识库 await client.addDocuments({ instanceName: 'my-instance', knowledgeBaseName: 'my-kb', documents: [ { documentId: 'doc-001', title: '使用指南', content: '表格存储是一款...' } ] }); // 语义检索 client.retrieve({ instanceName: 'my-instance', knowledgeBaseName: 'my-kb', query: '如何创建表格存储实例', topK: 5 }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('检索结果:', JSON.stringify(data, null, 2)); }); // 列出文档 client.listDocuments({ instanceName: 'my-instance', knowledgeBaseName: 'my-kb' }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('文档列表:', data); }); ``` ``` -------------------------------- ### Batch Get Row in Tablestore Node.js SDK Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Use batchGetRow to fetch multiple rows from one or more tables in a single request. Includes automatic retry logic for failed requests. Define table names and primary keys for the rows to retrieve. ```javascript var TableStore = require('tablestore'); var Long = TableStore.Long; var maxRetryTimes = 3; var retryCount = 0; function batchGetRow(params) { client.batchGetRow(params, function(err, data) { if (err) { console.log('error:', err); return; } var retryRequest = { tables: [] }; var isAllSuccess = true; for (var i = 0; i < data.tables.length; i++) { var failedRequest = { tableName: data.tables[i][0].tableName, primaryKey: [] }; for (var j = 0; j < data.tables[i].length; j++) { if (!data.tables[i][j].isOk && data.tables[i][j].primaryKey != null) { isAllSuccess = false; var pks = data.tables[i][j].primaryKey.map(function(pk) { var kp = {}; kp[pk.name] = pk.value; return kp; }); failedRequest.primaryKey.push(pks); } } if (failedRequest.primaryKey.length > 0) retryRequest.tables.push(failedRequest); } if (!isAllSuccess && retryCount++ < maxRetryTimes) { batchGetRow(retryRequest); // 重试失败的行 } console.log('结果:', JSON.stringify(data, null, 2)); }); } batchGetRow({ tables: [{ tableName: 'sampleTable', primaryKey: [ [{ 'gid': Long.fromNumber(20013) }, { 'uid': Long.fromNumber(20013) }], [{ 'gid': Long.fromNumber(20015) }, { 'uid': Long.fromNumber(20015) }] ], startColumn: 'col2', endColumn: 'col4' }] }); ``` -------------------------------- ### getRow Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Reads a single row of data based on the provided primary key. Supports specifying columns to get, max versions, and column filters. ```APIDOC ## getRow — Read Single Row Data Reads a single row of data based on the given primary key. Supports specifying columns to retrieve (columnsToGet), number of versions (maxVersions), and column filters (columnFilter). ```javascript var TableStore = require('tablestore'); var Long = TableStore.Long; // Example: Read row with composite filter conditions var condition = new TableStore.CompositeCondition(TableStore.LogicalOperator.AND); condition.addSubCondition( new TableStore.SingleColumnCondition('col1', '表格存储', TableStore.ComparatorType.EQUAL) ); condition.addSubCondition( new TableStore.SingleColumnCondition('col5', Long.fromNumber(123456789), TableStore.ComparatorType.EQUAL) ); client.getRow({ tableName: 'sampleTable', primaryKey: [ { 'gid': Long.fromNumber(20013) }, { 'uid': Long.fromNumber(20013) } ], maxVersions: 1, columnsToGet: ['col1', 'col2', 'col5'], columnFilter: condition }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('Row data:', JSON.stringify(data.row, null, 2)); }); ``` ``` -------------------------------- ### Create a Knowledge Base Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Creates a new knowledge base with a specified name and description. This is the first step in managing knowledge base content for AI applications. ```javascript await client.createKnowledgeBase({ instanceName: 'my-instance', knowledgeBaseName: 'my-kb', description: '产品手册知识库' }); ``` -------------------------------- ### Create Table with Configuration Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Create a new table with specified schema, primary keys, reserved throughput, TTL, max versions, and stream settings. Ensure parameters match TableStore requirements. ```javascript var params = { tableMeta: { tableName: 'sampleTable', primaryKey: [ { name: 'gid', type: 'INTEGER' }, { name: 'uid', type: 'INTEGER' } ] }, reservedThroughput: { capacityUnit: { read: 0, write: 0 } }, tableOptions: { timeToLive: -1, // -1 means never expire, unit: seconds maxVersions: 1 // Maximum versions per column }, streamSpecification: { enableStream: true, // Enable Stream expirationTime: 24 // Stream expiration time (hours), max 168 } }; client.createTable(params, function(err, data) { if (err) { console.log('error:', err); return; } console.log('success:', data); }); ``` -------------------------------- ### Initialize TableStore Client Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Instantiate the TableStore client using AccessKey, endpoint, and instance name. Supports environment variable injection for credentials. Use Promise for asynchronous operations. ```javascript var TableStore = require('tablestore'); // Create client (credentials can also be injected via environment variables) var client = new TableStore.Client({ accessKeyId: process.env.accessKeyId, // Aliyun AccessKey ID secretAccessKey: process.env.secretAccessKey, // Aliyun AccessKey Secret endpoint: 'https://your-instance.cn-hangzhou.ots.aliyuncs.com', // Server endpoint instancename: 'your-instance-name' // Instance name }); // Promise style call example client.listTable({}).then(function(data) { console.log('Table list:', data); }).catch(function(err) { console.error('Error:', err); }); ``` -------------------------------- ### Client Initialization Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Initializes the TableStore client with access key, endpoint, and instance name. Supports both Callback and Promise patterns. ```APIDOC ## Client Initialization Through `new TableStore.Client(config)`, you can create a client instance. You need to provide Alibaba Cloud AccessKey, Server Endpoint, and Instance Name. The client supports both callback and Promise asynchronous programming modes. ```javascript var TableStore = require('tablestore'); // Create client (credentials can also be injected via environment variables) var client = new TableStore.Client({ accessKeyId: process.env.accessKeyId, // Alibaba Cloud AccessKey ID secretAccessKey: process.env.secretAccessKey, // Alibaba Cloud AccessKey Secret endpoint: 'https://your-instance.cn-hangzhou.ots.aliyuncs.com', // Server endpoint instancename: 'your-instance-name' // Instance name }); // Promise style call example client.listTable({}).then(function(data) { console.log('Table list:', data); }).catch(function(err) { console.error('Error:', err); }); ``` ``` -------------------------------- ### Initialize TableStore Client with STS Token Source: https://github.com/aliyun/aliyun-tablestore-nodejs-sdk/blob/master/browser.md Initialize the TableStore client using STS token credentials for secure access. Replace placeholder values with your actual STS token details and endpoint information. ```javascript var stsTokenClient = new TableStore.Client({ accessKeyId: "sts token 中的 accessKeyId", secretAccessKey: "sts token 中的 secretAccessKey", stsToken: "sts token 中的 securityToken", endpoint: ' ', instancename: '' }); ``` -------------------------------- ### Create a Memory Store Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Creates a new Memory Store instance, which is a persistent storage for AI Agent memories. It includes a name and description. ```javascript await client.createMemoryStore({ instanceName: 'my-instance', memoryStoreName: 'agent-memory', description: 'AI Agent 长期记忆' }); ``` -------------------------------- ### List All Tables Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Retrieve a list of all table names within the current instance. This is useful for inventory or dynamic operations. ```javascript client.listTable({}, function(err, data) { if (err) { console.log('error:', err); return; } // data.tableNames: ['sampleTable', 'orderHistory', ...] console.log('All table names:', data.tableNames); }); ``` -------------------------------- ### Parallel Full Export using computeSplits and parallelScan Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Obtain index split information and sessionId using computeSplits, then use parallelScan to export full data in parallel based on splits. This is suitable for large-scale offline export scenarios and uses nextToken for iterative pagination until all data is read. ```javascript var TableStore = require('tablestore'); (async () => { const tableName = 'sampleTable'; const indexName = 'sampleIndex'; // 1. 获取 sessionId 和分片数 const splits = await new Promise((resolve, reject) => { client.computeSplits({ tableName, searchIndexSplitsOptions: { indexName } }, (err, data) => err ? reject(err) : resolve(data)); }); console.log('分片数:', splits.splits.length, 'sessionId:', splits.sessionId); // 2. 构造扫描请求 const scanQuery = { query: { queryType: TableStore.QueryType.MATCH_ALL_QUERY }, limit: 1000, aliveTime: 60, currentParallelId: 0, maxParallel: splits.splits.length }; // 3. 迭代翻页直至读完所有数据 let totalRows = 0; const scan = () => new Promise((resolve, reject) => { client.parallelScan({ tableName, indexName, sessionId: splits.sessionId, scanQuery, columnToGet: { returnType: TableStore.ColumnReturnType.RETURN_ALL_FROM_INDEX } }, (err, data) => err ? reject(err) : resolve(data)); }); let resp = await scan(); totalRows += resp.rows.length; while (resp.nextToken && resp.nextToken.length > 0) { scanQuery.token = resp.nextToken; resp = await scan(); totalRows += resp.rows.length; } console.log('导出总行数:', totalRows); })(); ``` -------------------------------- ### createTable Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Creates a new table with specified schema, including primary key, reserved throughput, TTL, max versions, and stream functionality. ```APIDOC ## createTable — Create Table Creates a new table based on the given table schema information. Supports setting primary key, reserved throughput, data expiration time, maximum versions, and Stream functionality. ```javascript var params = { tableMeta: { tableName: 'sampleTable', primaryKey: [ { name: 'gid', type: 'INTEGER' }, { name: 'uid', type: 'INTEGER' } ] }, reservedThroughput: { capacityUnit: { read: 0, write: 0 } }, tableOptions: { timeToLive: -1, // -1 means never expire, unit: seconds maxVersions: 1 // Maximum number of versions to keep per column }, streamSpecification: { enableStream: true, // Enable Stream expirationTime: 24 // Stream expiration time (hours), maximum 168 } }; client.createTable(params, function(err, data) { if (err) { console.log('error:', err); return; } console.log('success:', data); }); ``` ``` -------------------------------- ### List Documents in a Knowledge Base Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Lists all documents within a specified knowledge base. This can be used to manage or review the content of the knowledge base. ```javascript client.listDocuments({ instanceName: 'my-instance', knowledgeBaseName: 'my-kb' }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('文档列表:', data); }); ``` -------------------------------- ### Describe Table Schema Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Query and retrieve the schema information for a specific table, including primary key, throughput, TTL, versions, and stream configuration. ```javascript client.describeTable({ tableName: 'sampleTable' }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('Table schema:', JSON.stringify(data, null, 2)); // data.tableOptions.timeToLive, data.tableMeta.primaryKey, ... }); ``` -------------------------------- ### Add Documents to a Knowledge Base Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Adds documents to an existing knowledge base. Each document can have an ID, title, and content. This is used to populate the knowledge base for retrieval. ```javascript await client.addDocuments({ instanceName: 'my-instance', knowledgeBaseName: 'my-kb', documents: [ { documentId: 'doc-001', title: '使用指南', content: '表格存储是一款...' } ] }); ``` -------------------------------- ### listTable Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Retrieves a list of all table names within the current instance. ```APIDOC ## listTable — List All Tables Retrieves a list of table names for all tables created in the current instance. ```javascript client.listTable({}, function(err, data) { if (err) { console.log('error:', err); return; } // data.tableNames: ['sampleTable', 'orderHistory', ...] console.log('All table names:', data.tableNames); }); ``` ``` -------------------------------- ### getRange Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Reads data within a specified primary key range. Supports forward/backward scanning and pagination using `nextStartPrimaryKey`. ```APIDOC ## getRange ### Description Reads data within a specified primary key range. Supports forward/backward scanning and pagination using `nextStartPrimaryKey`. ### Method ```javascript var params = { tableName: 'sampleTable', direction: TableStore.Direction.FORWARD, maxVersions: 1, inclusiveStartPrimaryKey: [{ 'gid': TableStore.INF_MIN }, { 'uid': TableStore.INF_MIN }], exclusiveEndPrimaryKey: [{ 'gid': TableStore.INF_MAX }, { 'uid': TableStore.INF_MAX }], limit: 100 }; var allRows = []; function getRange() { client.getRange(params, function(err, data) { if (err) { console.log('error:', err); return; } allRows = allRows.concat(data.rows); // If nextStartPrimaryKey is not empty, continue pagination if (data.nextStartPrimaryKey) { params.inclusiveStartPrimaryKey = [ { 'gid': data.nextStartPrimaryKey[0].value }, { 'uid': data.nextStartPrimaryKey[1].value } ]; getRange(); } else { console.log('All data, total', allRows.length, 'rows'); } }); } getRange(); ``` ``` -------------------------------- ### Perform Semantic Search on Knowledge Base Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Retrieves documents from a knowledge base based on a semantic query. Specify the number of top results to return (topK). Useful for RAG applications. ```javascript client.retrieve({ instanceName: 'my-instance', knowledgeBaseName: 'my-kb', query: '如何创建表格存储实例', topK: 5 }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('检索结果:', JSON.stringify(data, null, 2)); }); ``` -------------------------------- ### Memory Store API Operations Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Offers persistent memory storage for AI Agents, including lifecycle management (create/get/update/delete/list) for Memory Stores and CRUD operations for Memory entries. It also supports querying message history and request logs. ```APIDOC ## Memory Store 操作(Memory Store API) Memory Store 是面向 AI Agent 场景的持久化记忆存储能力,提供 Memory Store 的完整生命周期管理(创建/获取/更新/删除/列出),以及 Memory 条目的增删改查和语义搜索,同时支持查询历史消息和请求记录。 ```javascript // 创建 Memory Store await client.createMemoryStore({ instanceName: 'my-instance', memoryStoreName: 'agent-memory', description: 'AI Agent 长期记忆' }); // 添加 Memory 条目 await client.addMemories({ instanceName: 'my-instance', memoryStoreName: 'agent-memory', memories: [ { content: '用户偏好:喜欢简洁的技术文档', metadata: { userId: 'u001' } } ] }); // 搜索 Memory client.searchMemories({ instanceName: 'my-instance', memoryStoreName: 'agent-memory', query: '用户喜好', topK: 3 }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('相关记忆:', JSON.stringify(data, null, 2)); }); // 列出 Memory Store 中的消息历史 client.listMemoryStoreMessages({ instanceName: 'my-instance', memoryStoreName: 'agent-memory' }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('消息历史:', data); }); ``` ``` -------------------------------- ### describeTable Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Queries the schema information for a specified table, including primary key, throughput, TTL, versions, and stream configuration. ```APIDOC ## describeTable — Query Table Schema Queries the schema information of a specified table (primary key definition, reserved throughput, TTL, version count, Stream configuration, index synchronization phase, etc.). ```javascript client.describeTable({ tableName: 'sampleTable' }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('Table schema:', JSON.stringify(data, null, 2)); // data.tableOptions.timeToLive, data.tableMeta.primaryKey, ... }); ``` ``` -------------------------------- ### computeSplits + parallelScan Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Performs a parallel full export of data. `computeSplits` retrieves shard information and sessionId, while `parallelScan` exports data in parallel based on shards. This is suitable for large-scale offline exports and uses `nextToken` for pagination. ```APIDOC ## computeSplits + parallelScan — 并行全量导出 `computeSplits` 获取索引分片信息和 sessionId,`parallelScan` 基于分片并行导出全量数据,适合大数据量离线导出场景,通过 `nextToken` 实现迭代翻页直至读完所有数据。 ```javascript var TableStore = require('tablestore'); (async () => { const tableName = 'sampleTable'; const indexName = 'sampleIndex'; // 1. 获取 sessionId 和分片数 const splits = await new Promise((resolve, reject) => { client.computeSplits({ tableName, searchIndexSplitsOptions: { indexName } }, (err, data) => err ? reject(err) : resolve(data)); }); console.log('分片数:', splits.splits.length, 'sessionId:', splits.sessionId); // 2. 构造扫描请求 const scanQuery = { query: { queryType: TableStore.QueryType.MATCH_ALL_QUERY }, limit: 1000, aliveTime: 60, currentParallelId: 0, maxParallel: splits.splits.length }; // 3. 迭代翻页直至读完所有数据 let totalRows = 0; const scan = () => new Promise((resolve, reject) => { client.parallelScan({ tableName, indexName, sessionId: splits.sessionId, scanQuery, columnToGet: { returnType: TableStore.ColumnReturnType.RETURN_ALL_FROM_INDEX } }, (err, data) => err ? reject(err) : resolve(data)); }); let resp = await scan(); totalRows += resp.rows.length; while (resp.nextToken && resp.nextToken.length > 0) { scanQuery.token = resp.nextToken; resp = await scan(); totalRows += resp.rows.length; } console.log('导出总行数:', totalRows); })(); ``` ``` -------------------------------- ### Range Read in Tablestore Node.js SDK Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Use getRange to retrieve data within a specified primary key range. Supports forward/backward scans and pagination using nextStartPrimaryKey. Configure inclusiveStartPrimaryKey and exclusiveEndPrimaryKey for range definition. ```javascript var TableStore = require('tablestore'); var Long = TableStore.Long; var params = { tableName: 'sampleTable', direction: TableStore.Direction.FORWARD, maxVersions: 1, inclusiveStartPrimaryKey: [{ 'gid': TableStore.INF_MIN }, { 'uid': TableStore.INF_MIN }], exclusiveEndPrimaryKey: [{ 'gid': TableStore.INF_MAX }, { 'uid': TableStore.INF_MAX }], limit: 100 }; var allRows = []; function getRange() { client.getRange(params, function(err, data) { if (err) { console.log('error:', err); return; } allRows = allRows.concat(data.rows); // 若 nextStartPrimaryKey 不为空,继续翻页 if (data.nextStartPrimaryKey) { params.inclusiveStartPrimaryKey = [ { 'gid': data.nextStartPrimaryKey[0].value }, { 'uid': data.nextStartPrimaryKey[1].value } ]; getRange(); } else { console.log('全部数据,共', allRows.length, '行'); } }); } getRange(); ``` -------------------------------- ### Search Memories in a Memory Store Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Performs a semantic search within a Memory Store to find relevant memories based on a query. Returns the topK most relevant results. ```javascript client.searchMemories({ instanceName: 'my-instance', memoryStoreName: 'agent-memory', query: '用户喜好', topK: 3 }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('相关记忆:', JSON.stringify(data, null, 2)); }); ``` -------------------------------- ### batchWriteRow Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Performs batch PUT, UPDATE, or DELETE operations on one or more tables in a single request. Also supports atomic INCREMENT. ```APIDOC ## batchWriteRow ### Description Performs batch PUT, UPDATE, or DELETE operations on one or more tables in a single request. Also supports atomic INCREMENT. ### Method ```javascript client.batchWriteRow({ tables: [{ tableName: 'sampleTable', rows: [ { type: 'PUT', condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null), primaryKey: [{ 'gid': Long.fromNumber(8) }, { 'uid': Long.fromNumber(81) }], attributeColumns: [{ 'attrCol1': 'value1' }, { 'attrCol2': 'value2' }], returnContent: { returnType: TableStore.ReturnType.Primarykey } }, { type: 'UPDATE', condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null), primaryKey: [{ 'gid': Long.fromNumber(8) }, { 'uid': Long.fromNumber(80) }], attributeColumns: [{ 'PUT': [{ 'attrCol1': 'updated' }] }], returnContent: { returnType: 1 } } ] }] }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('success:', data); }); ``` ``` -------------------------------- ### Update Table Configuration Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Modify table settings such as reserved throughput, TTL, or maximum versions. Ensure the table exists before attempting an update. ```javascript client.updateTable({ tableName: 'sampleTable', reservedThroughput: { capacityUnit: { read: 0, write: 0 } }, tableOptions: { timeToLive: 86400, // Data retention for 1 day maxVersions: 3 } }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('success:', data); }); ``` -------------------------------- ### Execute SQL Query on Table Store Data Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Use SQL syntax to query data in Table Store. The returned sqlRows object supports row and column index access and automatically handles special types like BINARY and LONG. ```javascript client.sqlQuery({ query: 'SELECT gid, uid, col1 FROM sampleTable WHERE gid > 100 LIMIT 10' }, function(err, resp) { if (err) { console.log('sqlQuery error:', err.toString()); return; } const { sqlRows } = resp; const rowCount = sqlRows.rowCount.toFloat64(); const colCount = sqlRows.columnCount; const meta = sqlRows.sqlTableMeta; console.log(`共 ${rowCount} 行,${colCount} 列`); console.log('列定义:', meta.schemas.map(s => `${s.name}(${s.typeName})`)); for (let i = 0; i < rowCount; i++) { for (let j = 0; j < colCount; j++) { const val = sqlRows.get(i, j); if (meta.schemas[j].typeName === 'LONG') { console.log(`[${i}][${j}] =`, val.toFloat64()); } else { console.log(`[${i}][${j}] =`, val); } } } }); ``` -------------------------------- ### Add Memories to a Memory Store Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Adds memory entries to a Memory Store. Each memory can have content and associated metadata, useful for storing agent states or user preferences. ```javascript await client.addMemories({ instanceName: 'my-instance', memoryStoreName: 'agent-memory', memories: [ { content: '用户偏好:喜欢简洁的技术文档', metadata: { userId: 'u001' } } ] }); ``` -------------------------------- ### sqlQuery Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Executes a SQL query against Table Store data. The returned sqlRows object supports row and column index access and automatically handles special types like BINARY and LONG. ```APIDOC ## sqlQuery — SQL 查询 使用 SQL 语法对表格存储数据进行查询,返回的 `sqlRows` 对象支持按行列索引访问,自动处理 BINARY 和 LONG 等特殊类型。 ```javascript client.sqlQuery({ query: 'SELECT gid, uid, col1 FROM sampleTable WHERE gid > 100 LIMIT 10' }, function(err, resp) { if (err) { console.log('sqlQuery error:', err.toString()); return; } const { sqlRows } = resp; const rowCount = sqlRows.rowCount.toFloat64(); const colCount = sqlRows.columnCount; const meta = sqlRows.sqlTableMeta; console.log(`共 ${rowCount} 行,${colCount} 列`); console.log('列定义:', meta.schemas.map(s => `${s.name}(${s.typeName})`)); for (let i = 0; i < rowCount; i++) { for (let j = 0; j < colCount; j++) { const val = sqlRows.get(i, j); if (meta.schemas[j].typeName === 'LONG') { console.log(`[${i}][${j}] =`, val.toFloat64()); } else { console.log(`[${i}][${j}] =`, val); } } } }); ``` ``` -------------------------------- ### batchGetRow Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Reads multiple rows from one or more tables in a single request. Supports automatic retries for failed rows. ```APIDOC ## batchGetRow ### Description Reads multiple rows from one or more tables in a single request. Supports automatic retries for failed rows. ### Method ```javascript var maxRetryTimes = 3; var retryCount = 0; function batchGetRow(params) { client.batchGetRow(params, function(err, data) { if (err) { console.log('error:', err); return; } var retryRequest = { tables: [] }; var isAllSuccess = true; for (var i = 0; i < data.tables.length; i++) { var failedRequest = { tableName: data.tables[i][0].tableName, primaryKey: [] }; for (var j = 0; j < data.tables[i].length; j++) { if (!data.tables[i][j].isOk && data.tables[i][j].primaryKey != null) { isAllSuccess = false; var pks = data.tables[i][j].primaryKey.map(function(pk) { var kp = {}; kp[pk.name] = pk.value; return kp; }); failedRequest.primaryKey.push(pks); } } if (failedRequest.primaryKey.length > 0) retryRequest.tables.push(failedRequest); } if (!isAllSuccess && retryCount++ < maxRetryTimes) { batchGetRow(retryRequest); // Retry failed rows } console.log('Result:', JSON.stringify(data, null, 2)); }); } batchGetRow({ tables: [{ tableName: 'sampleTable', primaryKey: [ [{ 'gid': Long.fromNumber(20013) }, { 'uid': Long.fromNumber(20013) }], [{ 'gid': Long.fromNumber(20015) }, { 'uid': Long.fromNumber(20015) }] ], startColumn: 'col2', endColumn: 'col4' }] }); ``` ``` -------------------------------- ### List Messages in a Memory Store Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Retrieves a list of messages stored within a Memory Store. This can be used to access conversation history or logs. ```javascript client.listMemoryStoreMessages({ instanceName: 'my-instance', memoryStoreName: 'agent-memory' }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('消息历史:', data); }); ``` -------------------------------- ### updateTable Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Updates the configuration of a specified table, such as reserved read/write throughput, TTL, or maximum versions. ```APIDOC ## updateTable — Update Table Configuration Updates the configuration of a specified table, such as reserved read/write throughput, TTL, or maximum versions. ```javascript client.updateTable({ tableName: 'sampleTable', reservedThroughput: { capacityUnit: { read: 0, write: 0 } }, tableOptions: { timeToLive: 86400, // Data retention for 1 day maxVersions: 3 } }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('success:', data); }); ``` ``` -------------------------------- ### Batch Write Row in Tablestore Node.js SDK Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Use batchWriteRow to perform multiple PUT, UPDATE, or DELETE operations on one or more tables in a single request. Supports atomic increment operations. Define row type, primary key, and attribute columns for each operation. ```javascript var TableStore = require('tablestore'); var Long = TableStore.Long; client.batchWriteRow({ tables: [{ tableName: 'sampleTable', rows: [ { type: 'PUT', condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null), primaryKey: [{ 'gid': Long.fromNumber(8) }, { 'uid': Long.fromNumber(81) }], attributeColumns: [{ 'attrCol1': 'value1' }, { 'attrCol2': 'value2' }], returnContent: { returnType: TableStore.ReturnType.Primarykey } }, { type: 'UPDATE', condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null), primaryKey: [{ 'gid': Long.fromNumber(8) }, { 'uid': Long.fromNumber(80) }], attributeColumns: [{ 'PUT': [{ 'attrCol1': 'updated' }] }], returnContent: { returnType: 1 } } ] }] }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('success:', data); }); ``` -------------------------------- ### Read Single Row Data with Filter Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Retrieve a single row by its primary key, with options to specify columns, max versions, and apply column filters. Composite conditions allow complex filtering logic. ```javascript var TableStore = require('tablestore'); var Long = TableStore.Long; // Example: Read row with composite filter conditions var condition = new TableStore.CompositeCondition(TableStore.LogicalOperator.AND); condition.addSubCondition( new TableStore.SingleColumnCondition('col1', '表格存储', TableStore.ComparatorType.EQUAL) ); condition.addSubCondition( new TableStore.SingleColumnCondition('col5', Long.fromNumber(123456789), TableStore.ComparatorType.EQUAL) ); client.getRow({ tableName: 'sampleTable', primaryKey: [ { 'gid': Long.fromNumber(20013) }, { 'uid': Long.fromNumber(20013) } ], maxVersions: 1, columnsToGet: ['col1', 'col2', 'col5'], columnFilter: condition }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('Row data:', JSON.stringify(data.row, null, 2)); }); ``` -------------------------------- ### updateRow Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Updates attribute column data for a specified row. Supports PUT (add/overwrite columns), DELETE (delete by version), DELETE_ALL (delete entire column), and INCREMENT (atomic increment) operations. ```APIDOC ## updateRow ### Description Updates attribute column data for a specified row. Supports PUT (add/overwrite columns), DELETE (delete by version), DELETE_ALL (delete entire column), and INCREMENT (atomic increment) operations. ### Method ```javascript client.updateRow({ tableName: 'sampleTable', condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null), primaryKey: [ { 'gid': Long.fromNumber(9) }, { 'uid': Long.fromNumber(90) } ], updateOfAttributeColumns: [ { 'PUT': [{ 'col4': Long.fromNumber(4) }, { 'col5': 'newValue' }] }, { 'DELETE': [{ 'col1': Long.fromNumber(1496826473186) }] }, // Delete by version { 'DELETE_ALL': ['col2'] } // Delete entire column ], returnContent: { returnType: TableStore.ReturnType.Primarykey } }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('success:', data); }); ``` ``` -------------------------------- ### Delete Table Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Permanently remove a table from the instance. This operation is irreversible. ```javascript client.deleteTable({ tableName: 'sampleTable' }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('Table deleted:', data); }); ``` -------------------------------- ### putRow Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Writes a single row of data to a specified table. Overwrites if the row exists, creates if it doesn't. Supports conditional writes and timestamps. ```APIDOC ## putRow — Write Single Row Data Writes a single row of data to the specified table. If the row already exists, it will be overwritten; otherwise, it will be created. Supports conditional writes (Condition) and timestamps. ```javascript var TableStore = require('tablestore'); var Long = TableStore.Long; client.putRow({ tableName: 'sampleTable', // RowExistenceExpectation: IGNORE (don't care) / EXPECT_EXIST (expect row to exist) / EXPECT_NOT_EXIST (expect row not to exist) condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null), primaryKey: [ { 'gid': Long.fromNumber(20013) }, { 'uid': Long.fromNumber(20013) } ], attributeColumns: [ { 'col1': '表格存储' }, { 'col2': '2', 'timestamp': Date.now() }, // Custom version number (timestamp) { 'col3': 3.14 }, { 'col5': Long.fromNumber(123456789) } ], returnContent: { returnType: TableStore.ReturnType.Primarykey } }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('success:', data); // data.row.primaryKey }); ``` ``` -------------------------------- ### deleteTable Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Deletes a specified table from the current instance. This operation is irreversible. ```APIDOC ## deleteTable — Delete Table Deletes a specified table from the current instance (this operation is irreversible). ```javascript client.deleteTable({ tableName: 'sampleTable' }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('Table deleted:', data); }); ``` ``` -------------------------------- ### Write Single Row Data Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Insert or overwrite a single row in a table using primary key and attribute columns. Supports conditional writes and custom timestamps. Use Long.fromNumber for large numbers. ```javascript var TableStore = require('tablestore'); var Long = TableStore.Long; client.putRow({ tableName: 'sampleTable', // RowExistenceExpectation: IGNORE (don't care) / EXPECT_EXIST (expect row exists) / EXPECT_NOT_EXIST (expect row does not exist) condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null), primaryKey: [ { 'gid': Long.fromNumber(20013) }, { 'uid': Long.fromNumber(20013) } ], attributeColumns: [ { 'col1': '表格存储' }, { 'col2': '2', 'timestamp': Date.now() }, // Custom version number (timestamp) { 'col3': 3.14 }, { 'col5': Long.fromNumber(123456789) } ], returnContent: { returnType: TableStore.ReturnType.Primarykey } }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('success:', data); // data.row.primaryKey }); ``` -------------------------------- ### Update Row in Tablestore Node.js SDK Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Use updateRow to modify attribute columns of a specific row. Supports PUT, DELETE, DELETE_ALL, and INCREMENT operations. Ensure correct primary key and update definitions. ```javascript var TableStore = require('tablestore'); var Long = TableStore.Long; client.updateRow({ tableName: 'sampleTable', condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null), primaryKey: [ { 'gid': Long.fromNumber(9) }, { 'uid': Long.fromNumber(90) } ], updateOfAttributeColumns: [ { 'PUT': [{ 'col4': Long.fromNumber(4) }, { 'col5': 'newValue' }] }, { 'DELETE': [{ 'col1': Long.fromNumber(1496826473186) }] }, // 删除指定版本 { 'DELETE_ALL': ['col2'] } // 删除整列 ], returnContent: { returnType: TableStore.ReturnType.Primarykey } }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('success:', data); }); ``` -------------------------------- ### deleteRow Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Deletes a row based on its primary key. Supports conditional deletion. ```APIDOC ## deleteRow ### Description Deletes a row based on its primary key. Supports conditional deletion. ### Method ```javascript client.deleteRow({ tableName: 'sampleTable', condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null), primaryKey: [ { 'gid': Long.fromNumber(20013) }, { 'uid': Long.fromNumber(20013) } ] }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('Deletion successful:', data); }); ``` ``` -------------------------------- ### Delete Row in Tablestore Node.js SDK Source: https://context7.com/aliyun/aliyun-tablestore-nodejs-sdk/llms.txt Use deleteRow to remove a row based on its primary key. Conditional deletion is supported. Ensure the primary key accurately identifies the row to be deleted. ```javascript var TableStore = require('tablestore'); var Long = TableStore.Long; client.deleteRow({ tableName: 'sampleTable', condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null), primaryKey: [ { 'gid': Long.fromNumber(20013) }, { 'uid': Long.fromNumber(20013) } ] }, function(err, data) { if (err) { console.log('error:', err); return; } console.log('删除成功:', data); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.