Tablestore provides the PutRow and UpdateRow operations to allow you to write a single row of data, and the BatchWriteRow operation to allow you to write multiple rows of data in a batch.
Prerequisites
- The OTSClient instance is initialized. For more information, see Initialization.
- A data table is created. Data is written to the table.
Insert a single row of data
You can call the PutRow operation to insert a row of data. If the row exists, the PutRow operation deletes all versions of data in all columns from the existing row, and then inserts a new row.
API operations
/// <summary>
/// Write a row of data based on the specified table name, primary keys, 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 of the row.
Note
|
attribute | The attribute column of the row.
|
condition | The condition that you can configure to perform the DeleteRow operation. You can configure
a row existence condition or a column-based condition. For more information, see Configure conditional update.
Note
|
Examples
- Example 1
Insert a row of data.
// Specify the primary key of the row. The primary key must be consistent with the primary key specified in TableMeta when you create a table. 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 indicates that data is inserted no matter 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 and handled. Console.WriteLine("Put row failed, exception:{0}", ex.Message); }
For the detailed sample code, visit PutRow@GitHub.
- Example 2
The following code provides an example on how to insert a row of data based on specified conditions. In the following example, the data is inserted only when the row exists and the value of col0 is greater than 24.
// Specify the primary key of the row. The primary key must be consistent with the primary key specified in TableMeta when you create a table. 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 col0 is greater than 24, the row can be inserted to overwrite the original value. try { var request = new PutRowRequest(tableName, new Condition(RowExistenceExpectation.EXPECT_EXIST), primaryKey, attribute); request.Condition.ColumnCondition = new RelationalCondition("col0", RelationalCondition.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.
- Example 3
The following code provides an example on how to asynchronously insert a row of data.
Important Each asynchronous invocation starts a thread. A timeout error may occur if too many asynchronous invocations are started consecutively and each invocation 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 primary key must be the same as the primary key 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(TableName, new Condition(RowExistenceExpectation.IGNORE), primaryKey, attribute); putRowTaskList.Add(TabeStoreClient.PutRowAsync(request)); } // Wait until each asynchronous invocation 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 is successful, 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); }
To view the detailed sample code, visit PutRowAsync@GitHub.
Update a row of data
API operations
/// <summary>
/// You can call this operation to update the data of a specified 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 deleted based on the request content.
/// </summary>
/// <param name="request">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 of 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.
|
condition | The condition that you want to specify to perform the UpdateRow operation. You can specify a row existence condition or a condition based on column values. For more information, see Configure conditional update. |
attribute | The attribute column you want to update.
|
Examples
The following code provides an example on how to update the data of a specified row:
// Specify the primary key of the row. The primary key must be the same as the primary key 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")); // Set the original value of 'a' to 'b'.
attribute.AddAttributeColumnToPut("col2", new ColumnValue(true));
try
{
// Construct the request object to update the row. RowExistenceExpectation.IGNORE indicates that data is updated no matter whether the specified row exists.
var request = new UpdateRowRequest(TableName, new Condition(RowExistenceExpectation.IGNORE),
primaryKey, attribute);
// Call the UpdateRow operation to update data.
otsClient.UpdateRow(request);
// If the operation is successful, 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);
}
To view the detailed sample code, visit UpdateRow@GitHub.
Write multiple rows of data in a batch
You can call the BatchWriteRow operation to write multiple rows to one or more tables in a batch. The BatchWriteRow operation is a set of PutRow, UpdateRow, or DeleteRow operations. When you call the BatchWriteRow operation, the process of constructing the PutRow, UpdateRow, or DeleteRow operations is the same as the process of constructing the PutRow, UpdateRow, or DeleteRow operation when you call the PutRow, UpdateRow, or DeleteRow operation. BatchWriteRow supports conditional update.
If you call the BatchWriteRow operation, each PutRow, UpdateRow, or DeleteRow operation is separately performed and the response to each PutRow, UpdateRow, or DeleteRow operation is separately returned.
Usage notes
When you call the BatchWriteRow operation to write multiple rows in a batch, some rows may fail to be written. If this happens, Tablestore does not return exceptions, but 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 the operation on each row is successful. If you do not check the return values, failures of operations on some rows are ignored.
If the server detects that invalid parameters exist in some operations, the BatchWriteRow operation may return an exception about parameter errors before the first operation in the request is performed.
API operations
/// <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">Request instance</param>
/// <returns>Response instance</returns>
public BatchWriteRowResponse BatchWriteRow(BatchWriteRowRequest request);
/// <summary>
/// Asynchronous mode of BatchWriteRow.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public Task<BatchWriteRowResponse> BatchWriteRowAsync(BatchWriteRowRequest request);
Examples
The following code provides an example on how to write 100 rows of data in a batch:
// Construct a request object to write multiple rows of data in a batch. Specify the primary key for 100 rows of data.
var request = new BatchWriteRowRequest();
var rowChanges = new RowChanges();
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 row.
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 in a batch, 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);
}
To view the detailed sample code, visit BatchWriteRow@GitHub.