All Products
Search
Document Center

Tablestore:Write data

Last Updated:Sep 18, 2024

Tablestore allows you to write a single row of data, update a single row of data, and write multiple rows of data at a 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, delete, or modify. To write data to a highly concurrent application, you can configure row existence conditions or column 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

/**
 * Write a single row of data. If the row exists, the PutRow operation deletes all versions of data in all columns from the existing row, and then writes new data. The number of capacity units (CUs) that are consumed by the operation is returned. 
 * @api
 * @param [] $request The request parameters. 
 * @return [] The response.  
 * @throws OTSClientException The exception that is thrown when a parameter error occurs or the Tablestore server returns a verification error. 
 * @throws OTSServerException The exception that is thrown when the Tablestore server returns an error. 
 */
public function putRow(array $request);            

Request information

Request parameters

Parameter

Description

table_name

The name of the data table.

condition

The condition that you want to specify for the PutRow operation. You can specify a row existence condition or a condition based on column values. For more information, see Perform conditional update.

  • row_existence: the row existence condition.

    Note
    • RowExistenceExpectationConst::CONST_IGNORE indicates 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.

    • RowExistenceExpectationConst::CONST_EXPECT_EXIST indicates that new data is inserted only when the specified row exists. The existing data is overwritten.

    • RowExistenceExpectationConst::CONST_EXPECT_NOT_EXIST indicates that new data is inserted only when the specified row does not exist.

  • column_condition: the condition based on column values.

primary_key

The primary key information about the row.

Note
  • The number and types of the primary key columns that you specify must be the same as the actual number and types of primary key columns in the data 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.

  • The primary key of a data table consists of one to four primary key columns. Primary key columns are sorted in the order in which they are added. For example, PRIMARY KEY (A, B, C) and PRIMARY KEY (A, C, B) have different schemas. Tablestore sorts rows based on the values of all primary key columns.

  • A primary key column is specified by parameters in the following sequence: the primary key column name, primary key column value (PrimaryKeyValue), and primary key column type (PrimaryKeyType). The primary key column type is optional.

  • The value of PrimaryKeyValue can be an integer, a binary, or a string.

  • The valid values of PrimaryKeyType are PrimaryKeyTypeConst::CONST_INTEGER, PrimaryKeyTypeConst::CONST_STRING, PrimaryKeyTypeConst::CONST_BINARY, and PrimaryKeyTypeConst::CONST_PK_AUTO_INCR, which respectively specify the INTEGER, STRING (UTF-8 encoded string), BINARY, and PK_AUTO_INCR types. If the type is INTEGER or STRING, you can specify only the value. If the type is not INTEGER or STRING, the type must be specified.

attribute_columns

The attribute columns of the row.

  • An attribute column is specified by parameters in the following sequence: the attribute column name, attribute column value (ColumnValue), attribute column type (ColumnType), and timestamp. The attribute column type and timestamp are optional.

  • The valid values of ColumnType are ColumnTypeConst::CONST_INTEGER, ColumnTypeConst::CONST_STRING, ColumnTypeConst::CONST_BINARY, ColumnTypeConst::CONST_BOOLEAN, and ColumnTypeConst::CONST_DOUBLE, which respectively specify the INTEGER, STRING (UTF-8 encoded string), BINARY, BOOLEAN, and DOUBLE types. If the type is BINARY, the type must be specified. If the type is not BINARY, you can specify only the value or set the ColumnType parameter to null.

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

    You can specify a data version number or use the data version number that is generated by Tablestore. By default, if you do not specify this parameter, the data version number that is generated by Tablestore is used.

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

    • 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.

return_content

The content that you want to return.

return_type: You can set the value to ReturnTypeConst::CONST_PK to return the primary key of the row. This parameter is used by the auto-increment primary key column feature.

Request syntax

$result = $client->putRow([
    'table_name' => '<string>', // Specify the name of the data table. 
    'condition' => [
        'row_existence' => <RowExistence>,   
        'column_condition' => <ColumnCondition>
    ],
    'primary_key' => [                              // Specify the primary key. 
        ['<string>', <PrimaryKeyValue>], 
        ['<string>', <PrimaryKeyValue>],
        ['<string>', <PrimaryKeyValue>, <PrimaryKeyType>]
    ],  
    'attribute_columns' => [         // Specify the attribute columns. 
            ['<string>', <ColumnValue>], 
            ['<string>', <ColumnValue>, <ColumnType>],
            ['<string>', <ColumnValue>, <ColumnType>, <integer>]
    ],
    'return_content' => [
        'return_type' => <ReturnType>
    ]
]);         

Response information

Response parameters

Parameter

Description

consumed

The number of CUs that are consumed by the operation.

capacity_unit: the number of read/write CUs that are consumed. Parameters:

  • read: the read throughput.

  • write: the write throughput.

primary_key

The value of the primary key, which is consistent with that specified in the request.

Note

If you set return_type to ReturnTypeConst::CONST_PK, the value of the primary key is returned. This parameter is used by the auto-increment primary key column feature.

attribute_columns

The values of attribute columns, which are consistent with those specified in the request. At present, the value of this parameter is empty.

Response syntax

[
    'consumed' => [
        'capacity_unit' => [
            'read' => <integer>,
            'write' => <integer>
        ]
    ],
    'primary_key' => [ 
        ['<string>', <PrimaryKeyValue>], 
        ['<string>', <PrimaryKeyValue>],
        ['<string>', <PrimaryKeyValue>, <PrimaryKeyType>]
    ],  
    'attribute_columns' => []
]        

Examples

Use the data version number that is automatically generated by Tablestore when you write a row of data

The following sample code shows how to write a row that contains 10 attribute columns, each of which stores data of only one version. In this example, data version numbers are automatically generated by Tablestore.

$attr = array();
for($i = 0; $i < 10; $i++) {
    $attr[] = ['Col'. $i, $i]; 
}
$request = [
    'table_name' => 'MyTable',
    'condition' => RowExistenceExpectationConst::CONST_IGNORE, // You can set condition to IGNORE, EXPECT_EXIST, or EXPECT_NOT_EXIST. 
    'primary_key' => [ // Specify the primary key. 
        ['PK0', 123],
        ['PK1', 'abc']
    ],
    'attribute_columns' => $attr
];
$response = $otsClient->putRow ($request);            

Specify a custom data version number when you write a row of data

The following sample code shows how to write a row that contains 10 attribute columns, each of which stores data of three versions. In this example, custom data version numbers are specified.

$attr = array();
$timestamp = getMicroTime();
for($i = 0; $i < 10; $i++) {
    for($j = 0; $j < 3; $j++) {
        $attr[] = ['Col'. $i, $j, null, $timestamp+$j];
    }
}
$request = [
    'table_name' => 'MyTable',
    'condition' => RowExistenceExpectationConst::CONST_IGNORE, // You can set condition to IGNORE, EXPECT_EXIST, or EXPECT_NOT_EXIST. 
    'primary_key' => [ // Specify the primary key. 
        ['PK0', 123],
        ['PK1', 'abc']
    ],
    'attribute_columns' => $attr
];
$response = $otsClient->putRow ($request);            

Specify a row existence condition when you write a row of data

The following sample code shows how to write a row that contains 10 attribute columns, each of which stores data of three versions, when the specified row does not exist. In this example, custom data version numbers are specified.

$attr = array();
$timestamp = getMicroTime();
for($i = 0; $i < 10; $i++) {
    for($j = 0; $j < 3; $j++) {
        $attr[] = ['Col'. $i, $j, null, $timestamp+$j];
    }
}
$request = [
    'table_name' => 'MyTable',
    'condition' => RowExistenceExpectationConst::CONST_EXPECT_NOT_EXIST, // Configure the condition parameter to write data when the specified row does not exist. 
    'primary_key' => [ // Specify the primary key. 
        ['PK0', 123],
        ['PK1', 'abc']
    ],
    'attribute_columns' => $attr
];
$response = $otsClient->putRow ($request);            

Specify a column-based condition and a row existence condition when you write a row of data

The following sample code shows how to write a row that contains 10 attribute columns, each of which stores data of three versions, when the specified row exists and the value of the Col0 column is greater than 100. In this example, custom data version numbers are specified.

$attr = array();
$timestamp = getMicroTime();
for($i = 0; $i < 10; $i++) {
    for($j = 0; $j < 3; $j++) {
        $attr[] = ['Col'. $i, $j, null, $timestamp+$j];
    }
}
$request = [
    'table_name' => 'MyTable',
    'condition' => [
        'row_existence' => RowExistenceExpectationConst::CONST_EXPECT_EXIST, // Configure the condition parameter to write data when the specified row exists. 
        'column_condition' => [                  // If the condition is met, the data is updated. 
            'column_name' => 'Col0',
            'value' => 100,
            'comparator' => ComparatorTypeConst::CONST_GREATER_THAN
        ]
    ,
    'primary_key' => [ // Specify the primary key. 
        ['PK0', 123],
        ['PK1', 'abc']
    ],
    'attribute_columns' => $attr
];
$response = $otsClient->putRow ($request);           

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 a single row of data. 
 * @api
 * @param [] $request The request parameters. 
 * @return [] The response. 
 * @throws OTSClientException The exception that is thrown when a parameter error occurs or the Tablestore server returns a verification error. 
 * @throws OTSServerException The exception that is thrown when the Tablestore server returns an error. 
 */
public function updateRow(array $request);            

Request information

Request parameters

Parameter

Description

table_name

The name of the data table.

condition

The condition that you want to specify for the UpdateRow operation. You can specify a row existence condition or a condition based on column values. For more information, see Perform conditional update.

primary_key

The primary key information about the row.

Note

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

update_of_attribute_columns

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.

return_content

The content that you want to return.

return_type: You can set the value only to ReturnTypeConst::CONST_PK to return the primary key of the row. This parameter is used by the auto-increment primary key column feature.

Request syntax

$result = $client->updateRow([
    'table_name' => '<string>', // Specify the name of the data table. 
    'condition' => [
        'row_existence' => <RowExistence>,
        'column_condition' => <ColumnCondition>
    ],
    'primary_key' => [                              // Specify the primary key. 
        ['<string>', <PrimaryKeyValue>], 
        ['<string>', <PrimaryKeyValue>],
        ['<string>', <PrimaryKeyValue>, <PrimaryKeyType>]
    ], 
    'update_of_attribute_columns' => [         // Specify the attribute columns that you want to update. 
        'PUT' => [
            ['<string>', <ColumnValue>], 
            ['<string>', <ColumnValue>, <ColumnType>],
            ['<string>', <ColumnValue>, <ColumnType>, <integer>]
        ],
        'DELETE' => [
            ['<string>', <integer>], 
            ['<string>', <integer>], 
            ['<string>', <integer>], 
            ['<string>', <integer>]
        ],
        'DELETE_ALL' => [
            '<string>',
            '<string>',
            '<string>',
            '<string>'
        ],        
    ],
    'return_content' => [
        'return_type' => <ReturnType>
    ]
]);            

Response information

Response parameters

Parameter

Description

consumed

The number of CUs that are consumed by the operation.

capacity_unit: the number of read/write CUs that are consumed. Parameters:

  • read: the read throughput.

  • write: the write throughput.

primary_key

The value of the primary key, which is consistent with that specified in the request.

Note

If you set return_type to ReturnTypeConst::CONST_PK, the value of the primary key is returned. This parameter is used by the auto-increment primary key column feature.

attribute_columns

The values of attribute columns, which are consistent with those specified in the request. At present, the value of this parameter is empty.

Response syntax

[
    'consumed' => [
        'capacity_unit' => [
            'read' => <integer>,
            'write' => <integer>
        ]
    ],
    'primary_key' => [ 
        ['<string>', <PrimaryKeyValue>], 
        ['<string>', <PrimaryKeyValue>],
        ['<string>', <PrimaryKeyValue>, <PrimaryKeyType>]
    ],  
    'attribute_columns' => []
]            

Examples

Update a row of data without specifying conditions

The following sample code shows how to update multiple columns of a row, delete a specific version of data from a column, and delete a column.

$request = [
    'table_name' => 'MyTable',
    'condition' => RowExistenceExpectationConst::CONST_IGNORE,
    'primary_key' => [ // Specify the primary key. 
        ['PK0', 123],
        ['PK1', 'abc']
    ],
    'update_of_attribute_columns' => [
        'PUT' => [                       // Update multiple columns. 
            ['Col0', 100],
            ['Col1', 'Hello'],
            ['Col2', 'a binary', ColumnTypeConst::CONST_BINARY],
            ['Col3', 100, null, 1526418378526]
        ],
        'DELETE' => [                    // Delete a specific version of data from a column. 
            ['Col10', 1526418378526]
        ],
        'DELETE_ALL' => [
            'Col11'                      // Delete a column. 
        ]
    ]
];
$response = $otsClient->updateRow($request);            

Specify a column-based condition and a row existence condition when you update a row of data

The following sample code shows how to update a row of data when the specified row exists and the value of the Col0 column is greater than 100.

$request = [
    'table_name' => 'MyTable',
    'primary_key' => [ // Specify the primary key. 
        ['PK0', 123],
        ['PK1', 'abc']
    ],
    'condition' => [
        'row_existence' => RowExistenceExpectationConst::CONST_EXPECT_EXIST, // Configure the condition parameter to update the row when the specified row exists. 
        'column_filter' => [                                                 // Update the row when the value of the Col0 column is greater than 100. 
            'column_name' => 'Col0',
            'value' => 100,
            'comparator' => ComparatorTypeConst::CONST_GREATER_THAN
        ]
    ],    
    'update_of_attribute_columns' => [
        'PUT' => [                       // Update multiple columns. 
            ['Col0', 100],
            ['Col1', 'Hello'],
            ['Col2', 'a binary', ColumnTypeConst::CONST_BINARY],
            ['Col3', 100, null, 1526418378526]
        ],
        'DELETE' => [                    // Delete a specific version of data from a column. 
            ['Col10', 1526418378526]
        ],
        'DELETE_ALL' => [
            'Col11'                      // Delete a column. 
        ]
    ]
];         

Write multiple rows of data at a time

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

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 a 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, you must 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.

API operation

/**
 * Write, update, or delete the specified rows of data. 
 * When you call the BatchWriteRow operation to write multiple rows of data at a time, some rows may fail to be written. In this case, Tablestore does not return exceptions. Tablestore returns the information about the failed rows in $response. For more information, see the sample response to the BatchWriteRow operation. 
 * @api
 * @param [] $request The request parameters. 
 * @return [] The response. 
 * @throws OTSClientException The exception that is thrown when a parameter error occurs or the Tablestore server returns a verification error. 
 * @throws OTSServerException The exception that is thrown when the Tablestore server returns an error. 
 */
public function batchWriteRow(array $request);              

Request information

Request parameters

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

  • Hierarchies are created for tables. Multiple tables can be processed at a 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 operation_type parameter is added to distinguish between different operation types.

    Valid values of operation_type are OperationTypeConst::CONST_PUT, OperationTypeConst::CONST_UPDATE, and OperationTypeConst::CONST_DELETE.

    • If the operation type is PUT, the primary_key and attribute_columns parameters take effect.

    • If the operation type is UPDATE, the primary_key and update_of_attribute_columns parameters take effect.

    • If the operation type is DELETE, the primary_key parameter takes effect.

Request syntax

$result = $client->batchWriteRow([
    'tables' => [                                            // Specify the hierarchies of tables. 
        [
            'table_name' => '<string>',                     // Specify the name of the data table. 
            'operation_type' => <OperationType>,
            'condition' => [
                'row_existence' => <RowExistence>,   
                'column_condition' => <ColumnCondition>
            ],
            'primary_key' => [                              // Specify the primary key. 
                ['<string>', <PrimaryKeyValue>], 
                ['<string>', <PrimaryKeyValue>],
                ['<string>', <PrimaryKeyValue>, <PrimaryKeyType>]
            ], 
            'attribute_columns' => [                        // This parameter is required when the operation type is PUT. 
                    ['<string>', <ColumnValue>], 
                    ['<string>', <ColumnValue>, <ColumnType>],
                    ['<string>', <ColumnValue>, <ColumnType>, <integer>]
            ],
            'update_of_attribute_columns' => [               // This parameter is required when the operation type is UPDATE. 
                'PUT' => [
                    ['<string>', <ColumnValue>], 
                    ['<string>', <ColumnValue>, <ColumnType>],
                    ['<string>', <ColumnValue>, <ColumnType>, <integer>]
                ],
                'DELETE' => [
                    ['<string>', <integer>], 
                    ['<string>', <integer>], 
                    ['<string>', <integer>], 
                    ['<string>', <integer>]
                ],
                'DELETE_ALL' => [
                    '<string>',
                    '<string>',
                    '<string>',
                    '<string>'
                ],
            ],
            'return_content' => [
                'return_type' => <ReturnType>
            ]
        ],
        // Other tables. 
    ]
]);        

Response information

Response parameters

Each table indicated by the tables parameter in the response corresponds to each table specified in the request. The following table describes the parameters in the response.

Parameter

Description

table_name

The name of the data table.

is_ok

Indicates whether the operation on the row is successful.

  • A value of true indicates that the operation on the row is successful. In this case, the error parameter is invalid.

  • A value of false indicates that the operation on the row fails.

error

The error information in the response if the operation on the row fails. Parameters:

  • code: the error code that is returned in the response if the operation on the row fails.

  • message: the error message that is returned in the response if the operation on the row fails.

consumed

The number of CUs that are consumed by this operation.

capacity_unit: the number of read/write CUs that are consumed. Parameters:

  • read: the read throughput.

  • write: the write throughput.

primary_key

The value of the primary key, which is consistent with that specified in the request.

If a value is specified for return_type, the value of this parameter exists. This parameter is used for the auto-increment primary key column feature.

attribute_columns

The values of attribute columns, which are consistent with those specified in the request. At present, the value of this parameter is empty.

Response syntax

[
    'tables' => [
        [
            'table_name' => '<string>',
            'rows' => [
                [
                    'is_ok' => true || false,
                    'error' => [
                        'code' => '<string>',
                        'message' => '<string>',
                    ]
                    'consumed' => [
                        'capacity_unit' => [
                            'read' => <integer>,
                            'write' => <integer>
                        ]
                    ],
                    'primary_key' => [ 
                        ['<string>', <PrimaryKeyValue>], 
                        ['<string>', <PrimaryKeyValue>],
                        ['<string>', <PrimaryKeyValue>, <PrimaryKeyType>]
                    ],
                    'attribute_columns' => []
                ],
                // Other rows. 
            ]
        ],
        // Other tables. 
    ]
]           

Example

The following sample code shows how to write 30 rows of data to three tables at a time. Ten rows are written to each table.

// Write data to three tables. Ten rows are written to each table. 
$tables = array();
for($i = 0; $i < 3; $i++) {
    $rows = array();
    for($j = 0; $j < 10; $j++) {
        $rows[] = [
            'operation_type' => OperationTypeConst::CONST_PUT, // Set the operation type to PUT. 
            'condition' => RowExistenceExpectationConst::CONST_IGNORE,
            'primary_key' => [
                ['pk0', $i],
                ['pk1', $j]
            ],
            'attribute_columns' => [
                ['Col0', 4],
                ['Col2', 'Beijing']
            ]
        ];
    }
    $tables[] = [
        'table_name' => 'SampleTable' . $i,
        'rows' => $rows
    ];
}
$request = [
    'tables' => $tables
];
$response = $otsClient->batchWriteRow ($request);
// Process each table that is returned. 
foreach ($response['tables'] as $tableData) {
  print "Handling table {$tableData['table_name']} ...\n";

  // Process the result that is returned by the PutRow operation on the table. 
  $putRows = $tableData['rows'];

  foreach ($putRows as $rowData) {

    if ($rowData['is_ok']) {
      // Data is written. 
      print "Capacity Unit Consumed: {$rowData['consumed']['capacity_unit']['write']}\n";
    } else {

      // Handle errors. 
      print "Error: {$rowData['error']['code']} {$rowData['error']['message']}\n";
    }
  }
}           

The following table describes the examples of detailed sample code.

Example

Description

BatchWriteRow1.php

Shows you how to perform multiple PUT operations in BatchWriteRow.

BatchWriteRow2.php

Shows you how to perform multiple UPDATE operations in BatchWriteRow.

BatchWriteRow3.php

Shows you how to perform multiple DELETE operations in BatchWriteRow.

BatchWriteRow4.php

Shows you how to perform the UPDATE, PUT, and DELETE operations in BatchWriteRow.

BatchWriteRowWithColumnFilter.php

Shows you how to use BatchWriteRow together with conditional update.

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 Perform 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.