Read data within a primary key range from a Tablestore table by using the `getRange` method in the Node.js SDK.
Prerequisites
Method
getRange: function getRange(params, callback)Examples
The following sample code shows how to read data from the test_table table where the primary key value is greater than row1.
var params = {
tableName: 'test_table',
// Set the start primary key for the query.
inclusiveStartPrimaryKey: [{ 'id': 'row1' }],
// Set the end primary key for the query. The end primary key is not included in the result.
exclusiveEndPrimaryKey: [{ 'id': TableStore.INF_MAX }]
};
// Call the getRange method to query data.
client.getRange(params, function (err, data) {
if (err) {
console.log('Get range failed with error: ', err);
return;
}
console.log('* RequestId: ', data.RequestId);
console.log('* Read CU Cost: ', data.consumed.capacityUnit.read);
console.log('* Write CU Cost: ', data.consumed.capacityUnit.write);
console.log('* Rows Data: ');
data.rows.forEach(function (row) {
console.log(row);
});
});A single range scan can return a maximum of 5,000 rows or 4 MB of data. If this limit is exceeded, the operation returns the start primary key for the next read. You can use the following code to perform an iterative query.
async function getRangeSample() {
try {
while (true) {
// Call the getRange method to query data.
const data = await client.getRange(params);
// Process the returned result.
console.log('* RequestId: ', data.RequestId);
console.log('* Read CU Cost: ', data.consumed.capacityUnit.read);
console.log('* Write CU Cost: ', data.consumed.capacityUnit.write);
console.log('* Rows Data: ');
data.rows.forEach(function (row) {
console.log(row);
});
// Set the start primary key for the next read.
if (data.nextStartPrimaryKey) {
params.inclusiveStartPrimaryKey = data.nextStartPrimaryKey.map(item => {
return {
[item.name]: item.value
};
});
} else {
break;
}
}
} catch (err) {
console.log('Range get failed with error: ', err);
}
}
getRangeSample();Also configure the following settings when you query data.
Set the data read direction.
var params = { tableName: 'test_table', // Set the start primary key for the query. When you read data in reverse order, the start primary key must be greater than the end primary key. inclusiveStartPrimaryKey: [{ 'id': TableStore.INF_MAX }], // Set the end primary key for the query. The end primary key is not included in the result. exclusiveEndPrimaryKey: [{ 'id': 'row1' }], // Set the read direction to reverse. direction: TableStore.Direction.BACKWARD };Set the version range of the data to read. The operation returns only data within the specified version range.
// Set the version range for the query to the last 24 hours. params.timeRange = { startTime: (Date.now() - 86400 * 1000).toString(), endTime: Date.now().toString() }Specify the attribute columns to read.
params.columnsToGet = ['col2']Set the maximum number of rows to return in a single request.
params.limit = 10