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.
Methods
Tablestore provides the PutRow, UpdateRow, and BatchWriteRow operations to allow you to write data. Before you write data, select a suitable write method based on your business requirements.
Write method | Description | Scenario |
You can call the PutRow operation to insert a single row of data. If the row exists, Tablestore deletes all versions of data in all columns from the existing row and writes new data. | This operation is suitable for scenarios in which you want to write a small amount of data. | |
You can call the UpdateRow operation to update a single row of data. 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. | This operation is suitable for scenarios in which you want to update the existing data. For example, you want to remove an attribute column, delete a specific version of data, or update the value of an attribute column. | |
You can call the BatchWriteRow operation to write multiple rows of data to one or more tables at the same 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. | This operation is suitable for scenarios in which you want to write, delete, or update a large amount of data and scenarios in which you want to write, delete, and update data at the same time. |
Prerequisites
An OTSClient instance is initialized. For more information, see Initialize an OTSClient instance.
A data table is created, and data is written to the data table. For more information, see Create data tables and Write data.
Insert 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
/// <summary>
/// Write a row of data based on the specified table name, primary key, and attributes. Thu number of capacity units (CUs) consumed by the operation is returned.
/// </summary>
/// <param name="request">Data insertion request</param>
/// <returns>The number of CUs consumed by the operation</returns>
public PutRowResponse PutRow(PutRowRequest request);
/// <summary>
/// The asynchronous mode of PutRow.
/// </summary>
public Task<PutRowResponse> PutRowAsync(PutRowRequest request);
Parameters
Parameter | Description |
tableName | The name of the data table. |
primaryKey | The primary key information about the row. The value of this parameter consists of the name, type, and value of each primary key column. Important
|
attribute | The attribute columns 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).
|
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 Perform conditional updates. Note
|
Examples
Insert a row of data
The following sample code provides an example on how to insert a single row of data:
// Specify the primary key of the row. The schema of the primary key must be the same as the schema that is specified in TableMeta when the table is created.
var primaryKey = new PrimaryKey();
primaryKey.Add("pk0", new ColumnValue(0));
primaryKey.Add("pk1", new ColumnValue("abc"));
// Specify the attribute columns of the row.
var attribute = new AttributeColumns();
attribute.Add("col0", new ColumnValue(0));
attribute.Add("col1", new ColumnValue("a"));
attribute.Add("col2", new ColumnValue(true));
try
{
// Construct the request object to insert a row of data. RowExistenceExpectation.IGNORE specifies that data is inserted regardless of whether the specified row exists.
var request = new PutRowRequest("SampleTable", new Condition(RowExistenceExpectation.IGNORE),
primaryKey, attribute);
// Call the PutRow operation to insert data.
otsClient.PutRow(request);
// If the operation succeeds, no exception is returned.
Console.WriteLine("Put row succeeded.");
}
catch (Exception ex)
{
// If the operation fails, an exception is returned. Handle the exception.
Console.WriteLine("Put row failed, exception:{0}", ex.Message);
}
For the detailed sample code, visit PutRow@GitHub.
Specify a condition based on column values and a row existence condition when you insert a row of data
The following sample code provides an example on how to insert a row of data only when the row exists and the value of the col0 column is greater than 24:
// Specify the primary key of the row. The schema of the primary key must be the same as the schema that is specified in TableMeta when the table is created.
var primaryKey = new PrimaryKey();
primaryKey.Add("pk0", new ColumnValue(0));
primaryKey.Add("pk1", new ColumnValue("abc"));
// Specify the attribute columns of the row.
AttributeColumns attribute = new AttributeColumns();
attribute.Add("col0", new ColumnValue(0));
attribute.Add("col1", new ColumnValue("a"));
attribute.Add("col2", new ColumnValue(true));
// When the value of the col0 column is greater than 24, the row can be inserted to overwrite the original value.
try
{
var request = new PutRowRequest("SampleTable", new Condition(RowExistenceExpectation.EXPECT_EXIST),
primaryKey, attribute);
request.Condition.ColumnCondition = new RelationalCondition("col0",
CompareOperator.GREATER_THAN,
new ColumnValue(24));
otsClient.PutRow(request);
Console.WriteLine("Put row succeeded.");
}
catch (Exception ex)
{
Console.WriteLine("Put row failed. error:{0}", ex.Message);
}
For the detailed sample code, visit ConditionPutRow@GitHub.
Asynchronously insert data
The following sample code provides an example on how to asynchronously insert multiple rows of data.
Each asynchronous call starts a thread. A timeout error may occur if a large number of asynchronous calls are started consecutively and each call consumes an extended period of time.
try
{
var putRowTaskList = new List<Task<PutRowResponse>>();
for (int i = 0; i < 100; i++)
{
// Specify the primary key of the row. The schema of the primary key must be the same as the schema that is specified in TableMeta when the table is created.
var primaryKey = new PrimaryKey();
primaryKey.Add("pk0", new ColumnValue(i));
primaryKey.Add("pk1", new ColumnValue("abc"));
// Specify the attribute columns of the row.
var attribute = new AttributeColumns();
attribute.Add("col0", new ColumnValue(i));
attribute.Add("col1", new ColumnValue("a"));
attribute.Add("col2", new ColumnValue(true));
var request = new PutRowRequest("SampleTable", new Condition(RowExistenceExpectation.IGNORE),
primaryKey, attribute);
putRowTaskList.Add(otsClient.PutRowAsync(request));
}
// Wait until each asynchronous call returns results and displays the consumed CUs.
foreach (var task in putRowTaskList)
{
task.Wait();
Console.WriteLine("consumed read:{0}, write:{1}", task.Result.ConsumedCapacityUnit.Read,
task.Result.ConsumedCapacityUnit.Write);
}
// If the operation succeeds, no exception is returned.
Console.WriteLine("Put row async succeeded.");
}
catch (Exception ex)
{
// If the operation fails, an exception is returned. Handle the exception.
Console.WriteLine("Put row async failed. exception:{0}", ex.Message);
}
For the detailed sample code, visit PutRowAsync@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.
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
/// <summary>
/// You can call this operation to update the data of a specific row. If the row does not exist, a new row is added. If the row exists, the values of the specified columns are added, modified, or removed based on the request content.
/// </summary>
/// <param name="request">The request instance.</param>
public UpdateRowResponse UpdateRow(UpdateRowRequest request);
/// <summary>
/// The asynchronous mode of UpdateRow.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public Task<UpdateRowResponse> UpdateRowAsync(UpdateRowRequest request);
Parameters
Parameter | Description |
tableName | The name of the data table. |
primaryKey | The primary key information about the row. The value of this parameter consists of the name, type, and value of each 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. |
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 Perform conditional updates. |
attribute | The attribute columns that you want to update.
|
Examples
The following sample code provides an example on how to update a single row of data:
// Specify the primary key of the row. The schema of the primary key must be the same as the schema that is specified in TableMeta when the table is created.
PrimaryKey primaryKey = new PrimaryKey();
primaryKey.Add("pk0", new ColumnValue(0));
primaryKey.Add("pk1", new ColumnValue("abc"));
// Specify the attribute columns of the row.
UpdateOfAttribute attribute = new UpdateOfAttribute();
attribute.AddAttributeColumnToPut("col0", new ColumnValue(0));
attribute.AddAttributeColumnToPut("col1", new ColumnValue("b")); // Change the value of the column from a to b.
attribute.AddAttributeColumnToPut("col2", new ColumnValue(true));
try
{
// Construct a request object to update the row. RowExistenceExpectation.IGNORE specifies that data is updated regardless of whether the specified row exists.
var request = new UpdateRowRequest("SampleTable", new Condition(RowExistenceExpectation.IGNORE),
primaryKey, attribute);
// Call the UpdateRow operation to update data.
otsClient.UpdateRow(request);
// If the operation succeeds, no exception is returned.
Console.WriteLine("Update row succeeded.");
}
catch (Exception ex)
{
// If the operation fails, an exception is returned. Handle the exception.
Console.WriteLine("Update row failed, exception:{0}", ex.Message);
}
For 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 at a time, some rows may fail to be written. If this happens, Tablestore does not return exceptions, but returns BatchWriteRowResponse in which the information about the failed rows is included. Therefore, when you call the BatchWriteRow operation, you must check the return values. You can use the isAllSucceed method of BatchWriteRowResponse to check whether all rows are written. If you do not check the return values, you may ignore the rows that fail to be written.
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
/// <summary>
/// <para>Insert, modify, or delete multiple rows of data in one or more tables. </para>
/// <para>The BatchWriteRow operation is a set of multiple PutRow, UpdateRow, and DeleteRow operations. The execution, returning of results, and capacity unit (CU) consumption of each individual operation are carried out independently. </para>
/// <para>Compared with the execution of a large number of single-row write operations, the use of BatchWriteRow can reduce the request response time and increase the data write rate. </para>
/// </summary>
/// <param name="request">The request instance.</param>
/// <returns>The response instance</returns>
public BatchWriteRowResponse BatchWriteRow(BatchWriteRowRequest request);
/// <summary>
/// The asynchronous mode of BatchWriteRow.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public Task<BatchWriteRowResponse> BatchWriteRowAsync(BatchWriteRowRequest request);
Examples
The following sample code provides an example on how to write 100 rows of data at the same time:
var TableName = "SampleTable";
// Construct a request object to write 100 rows of data in at the same time. Specify the primary key for 100 rows of data.
var request = new BatchWriteRowRequest();
var rowChanges = new RowChanges(TableName);
for (int i = 0; i < 100; i++)
{
PrimaryKey primaryKey = new PrimaryKey();
primaryKey.Add("pk0", new ColumnValue(i));
primaryKey.Add("pk1", new ColumnValue("abc"));
// Specify the attribute columns of the rows.
UpdateOfAttribute attribute = new UpdateOfAttribute();
attribute.AddAttributeColumnToPut("col0", new ColumnValue(0));
attribute.AddAttributeColumnToPut("col1", new ColumnValue("a"));
attribute.AddAttributeColumnToPut("col2", new ColumnValue(true));
rowChanges.AddUpdate(new Condition(RowExistenceExpectation.IGNORE), primaryKey, attribute);
}
request.Add(TableName, rowChanges);
try
{
// Call the BatchWriteRow operation.
var response = otsClient.BatchWriteRow(request);
var tableRows = response.TableRespones;
var rows = tableRows[TableName];
// When you write multiple rows of data at the same time, some rows may fail to be written. You must check the return values and check whether the status of each row is successful. For more information, see the link of GitHub in the sample code.
}
catch (Exception ex)
{
// If the operation fails, an exception is returned. Handle the exception.
Console.WriteLine("Batch put row failed, exception:{0}", ex.Message);
}
For 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 Perform conditional updates.
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.
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.