All Products
Search
Document Center

Tablestore:Write data

Last Updated:Aug 07, 2024

Tablestore allows you to write a single row of data, update a single row of data, and write multiple rows of data at the same time by calling different operations. To write data to a data table, you must specify the complete primary key information and the attribute columns that you want to add, remove, or modify. When you write data to a highly concurrent application, you can configure row existence conditions or column-based conditions to update data based on the specified conditions.

Prerequisites

Write a single row of data

You can call the PutRow operation to write a row of data. If the row exists, Tablestore deletes all versions of data in all columns from the existing row and writes new data.

API operation

/**
 * Insert data into a specific row. If the row exists, the existing data is overwritten. Otherwise, a new row is added. 
 */
putRow(params, callback)

Parameters

Parameter

Description

tableName

The name of the data table.

primaryKey

The primary key information about the row. The primary key information includes the name, type, and value of the primary key column.

Important
  • The number and types of primary key columns that you specify must be the same as the actual number and types of primary key columns in the table.

  • If a primary key column is an auto-increment primary key column, you need to only set the value of the auto-increment primary key column to a placeholder. For more information, see Configure an auto-increment primary key column.

condition

The condition that must be met to perform the operation. You can specify a row existence condition or a condition based on column values. For more information, see Configure conditional update.

Note
  • RowExistenceExpectation.IGNORE specifies that new data is inserted into a row regardless of whether the specified row exists. If the specified row exists, the existing data is overwritten.

  • RowExistenceExpectation.EXPECT_EXIST specifies that new data is inserted only if the specified row exists. The existing data is overwritten.

  • RowExistenceExpectation.EXPECT_NOT_EXIST specifies that data is inserted only if the specified row does not exist.

attributeColumns

The attribute column of the row. Each attribute column is specified by parameters in the following sequence: the attribute column name, attribute column type (optional), attribute column value, and timestamp (optional).

  • The attribute column name is the name of the attribute column, and the attribute column type is the data type of the attribute column. For more information, see Naming conventions and data types.

    You can use ColumnType.INTEGER to specify an INTEGER value, ColumnType.STRING to specify a UTF-8 encoded STRING, ColumnType.BINARY to specify a BINARY value, ColumnType.BOOLEAN to specify a BOOLEAN value, or ColumnType.DOUBLE to specify a DOUBLE value. If the attribute column type is BINARY, you must use ColumnType.BINARY. In other cases, you can leave the attribute column type unspecified.

  • The timestamp is a data version number. For more information, see Data versions and TTL.

    You can use the data version number that is automatically generated by the system or specify a custom data version number. If you do not specify a data version number, the data version number that is automatically generated by the system is used.

    • The data version number generated by Tablestore is the number of milliseconds that have elapsed since 00:00:00 UTC on January 1, 1970.

    • If you specify a data version number, make sure that the data version number is a 64-bit timestamp that is accurate to milliseconds and is in the valid version range.

returnContent

The return type.

returnType: You can set the returnType parameter to TableStore.ReturnType.Primarykey to return the primary key of the row. This parameter is used by the auto-increment primary key column feature.

Examples

The following sample code provides an example on how to write a single row of data:

var TableStore = require('../index.js');
var Long = TableStore.Long;
var client = require('./client');

var currentTimeStamp = Date.now();
var params = {
  tableName: "sampleTable",
  condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null),
  primaryKey: [{ 'gid': Long.fromNumber(20013) }, { 'uid': Long.fromNumber(20013) }],
  attributeColumns: [
    { 'col1': 'Tablestore' },
    { 'col2': '2', 'timestamp': currentTimeStamp },
    { 'col3': 3.1 },
    { 'col4': -0.32 },
    { 'col5': Long.fromNumber(123456789) }
  ],
  returnContent: { returnType: TableStore.ReturnType.Primarykey }
};

client.putRow(params, function (err, data) {
  if (err) {
    console.log('error:', err);
    return;
  }

  console.log('success:', data);
});

To view the detailed sample code, visit PutRow@GitHub.

Update a single row of data

You can call the UpdateRow operation to update the data in a row. You can add attribute columns to a row, remove attribute columns from a row, delete a specific version of data from an attribute column, or update the value of an attribute column. If the row does not exist, a new row is inserted.

Note

If you call the UpdateRow operation only to remove columns from a row and the row does not exist, no row is inserted into the table.

API operation

/**
 * Update the data of the specified row. If the row does not exist, a new row is added. If the row exists, the values of the specified columns of the row are added, modified, or removed based on the request content. 
 */
updateRow(params, callback)

Parameters

Parameter

Description

tableName

The name of the data table.

primaryKey

The primary key information about the row.

Important

The number and types of primary key columns that you specify must be the same as the actual number and types of primary key columns in the table.

condition

The condition that must be met to perform the operation. You can specify a row existence condition or a condition based on column values. For more information, see Configure conditional update.

updateOfAttributeColumns

The attribute columns that you want to update.

  • When you add or modify an attribute column, you must specify the attribute column name and attribute column value. The attribute column value type and timestamp are optional.

    The attribute column name is the name of the attribute column, and the attribute column value type is the data type of the attribute column. For more information, see Naming conventions and data types.

    A timestamp is a data version number. You can use the data version number that is automatically generated by the system or specify a custom data version number. By default, if you do not specify a data version number, the data version number that is automatically generated by the system is used. For more information, see Data versions and TTL.

    • By default, the system uses the current UNIX timestamp as a data version number. A UNIX timestamp represents the number of milliseconds that have elapsed since January 1, 1970, 00:00:00 UTC.

    • If you specify a custom data version number, make sure that the version number is a 64-bit timestamp that is accurate to milliseconds and is in the valid version range.

  • To delete a specified version of data from an attribute column, you need to only specify the attribute column name and timestamp.

    The timestamp is a 64-bit integer in units of milliseconds, which specifies a version of data.

  • To remove an attribute column, you need to only specify the attribute column name.

    Note

    After you remove all attribute columns from a row, the row still exists. To delete a row, use the DeleteRow operation.

Examples

The following sample code provides an example on how to update a single row of data:

var TableStore = require('../index.js');
var Long = TableStore.Long;
var client = require('./client');

var params = {
    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': '5' }, { 'col6': Long.fromNumber(6) }] },
        { 'DELETE': [{ 'col1': Long.fromNumber(1496826473186) }] },
        { 'DELETE_ALL': ['col2'] }
    ]
};

client.updateRow(params,
    function (err, data) {
        if (err) {
            console.log('error:', err);
            return;
        }

        console.log('success:', data);
    });                

To view the detailed sample code, visit UpdateRow@GitHub.

Write multiple rows of data at the same time

You can call the BatchWriteRow operation to write multiple rows of data to one or more tables at a time.

The BatchWriteRow operation consists of multiple PutRow, UpdateRow, and DeleteRow operations. When you call the BatchWriteRow operation, the process of constructing a suboperation is the same as the process of calling the PutRow, UpdateRow, or DeleteRow operation.

When you call the BatchWriteRow operation, each PutRow, UpdateRow, or DeleteRow operation is separately performed and the response to each operation is separately returned by Tablestore.

Usage notes

  • When you call the BatchWriteRow operation to write multiple rows of data at the same time, some rows may fail to be written. In this case, Tablestore does not return exceptions. Tablestore returns BatchWriteRowResponse in which the indexes and error messages of the failed rows are included. Therefore, when you call the BatchWriteRow operation, make sure to check the return values to determine whether all rows are written. If you do not check the return values, the rows that fail to be written may be ignored.

    If the server detects that invalid parameters exist in some operations, an error message may return before the operations of the request are performed.

  • You can call the BatchWriteRow operation to write up to 4 MB of data in up to 200 rows at the same time.

API operation

/**
 // Add, remove, or update multiple rows of data in multiple tables. 
 */
batchWriteRow(params, callback)

Parameters

The BatchWriteRow operation consists of multiple PutRow, UpdateRow, and DeleteRow operations.

  • Hierarchies are created for tables. Multiple tables can be processed at the same time.

    You can configure the tables parameter to specify information about tables and rows on which you want to perform the write, update, or delete operations.

  • The type parameter is added to distinguish between different operation types.

    You can set the operation type to PUT, UPDATE, or DELETE.

    • If you set the operation type to PUT or UPDATE, primaryKey and attributeColumns are valid.

    • If you set the operation type to DELETE, primaryKey is valid.

Examples

The following sample code provides an example on how to write multiple rows of data at the same time:

var client = require('./client');
var TableStore = require('../index.js');
var Long = TableStore.Long;

var params = {

    tables: [
        {
            tableName: 'sampleTable',
            rows: [
                {
                    type: 'UPDATE',
                    condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null),
                    primaryKey: [{ 'gid': Long.fromNumber(20010) }, { 'uid': Long.fromNumber(20010) }],
                    attributeColumns: [{ 'PUT': [{ 'col1': 'test3' }, { 'col2': 'test4' }] }],
                    returnContent: { returnType: 1 }
                },
                {
                    type: 'PUT',
                    condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null),
                    primaryKey: [{ 'gid': Long.fromNumber(20020) }, { 'uid': Long.fromNumber(20020) }],
                    attributeColumns: [{ 'col1': 'test1' }, { 'col2': 'test2' }],
                    returnContent: { returnType: TableStore.ReturnType.Primarykey }
                },
                {
                    type: 'DELETE',
                    condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null),
                    primaryKey: [{ 'gid': Long.fromNumber(20018) }, { 'uid': Long.fromNumber(20018) }],
                }
            ]
        }
    ],
};

client.batchWriteRow(params, function (err, data) {

    if (err) {
        console.log('error:', err);
        return;
    }

    console.log('success:', data);
});                   

To view the detailed sample code, visit BatchWriteRow@GitHub.

FAQ

References

  • To update data in a highly concurrent application based on the specified conditions, you can use the conditional update feature. For more information, see Configure conditional update.

  • To collect real-time statistics about online applications, such as the number of page views (PVs) on various topics, you can use the atomic counter feature. For more information, see Use the atomic counter feature.

  • To perform atomic operations to write one or more rows of data, you can use the local transaction feature. For more information, see Configure local transaction.

  • After you write data to a table, you can read or delete the data in the table based on your business requirements. For more information, see Read data and Delete data.