Tablestore provides the following single-row operations: PutRow, GetRow, UpdateRow, and DeleteRow.

Prerequisites

  • The OTSClient instance is initialized. For more information, see Initialization.
  • A data table is created. Data is written to the table.

PutRow

You can call this operation to insert a row. 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
  • 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 column, you need only to set the value of the auto-increment column to a placeholder. For more information, see Configure an auto-increment primary key column.
attribute The attribute column of the row.
  • Each attribute column is specified by parameters in the following sequence: the attribute column name, attribute column value type, attribute column value, and timestamp. The attribute column value type and timestamp are optional.
  • The timestamp is the data version number. For more information, see Data versions and TTL.

    You can customize a data version number or use the data version number generated by Tablestore. If you do not specify this parameter, the data version number generated by Tablestore is used.

    • The version number generated by Tablestore is calculated based on the number of milliseconds that have elapsed since 00:00:00 UTC on January 1, 1970.
    • If you customize the version number, make sure that the version number is a 64-bit timestamp accurate to the millisecond within the valid version range.
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
  • In addition to row conditions, the Condition parameter also supports column-based conditions in Tablestore SDK for .NET 2.2.0 and later.
  • Condition.IGNORE, Condition.EXPECT_EXIST, and Condition.EXPECT_NOT_EXIST are deprecated since Tablestore SDK for .NET 3.0.0. Replace them with new Condition (RowExistenceExpectation.IGNORE), new Condition (RowExistenceExpectation.EXPECT_EXIST), and new Condition (RowExistenceExpectation.EXPECT_NOT_EXIST).
  • RowExistenceExpectation.IGNORE indicates that new data is inserted into a row regardless of whether the specified row exists or not. If the specified row exists, the existing data is overwritten.
  • RowExistenceExpectation.EXPECT_EXIST indicates that new data is inserted only when the specified row exists. The existing data is overwritten.
  • RowExistenceExpectation.EXPECT_NOT_EXIST indicates that data is inserted only when the specified row does not exist.

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.

    Notice Each asynchronous call 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 consistent with the primary key specified in TableMeta when you create a table. 
            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 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.

GetRow

You can call this operation to read a row.

One of the following results of the read request may be returned:
  • If the row exists, the primary key columns and attribute columns of the row are returned.
  • If the row does not exist, no row is returned and no error is reported.

API operations

/// <summary>
/// Read a single row of data based on a specified primary key. 
/// </summary>
/// <param name="request">Data query request</param>
/// <returns>Response of GetRow</returns>
public GetRowResponse GetRow(GetRowRequest request);

/// <summary>
/// The asynchronous mode of GetRow. 
/// </summary>
public Task<GetRowResponse> GetRowAsync(GetRowRequest 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.
columnsToGet The set of columns that you want to read. You can specify the name of a primary key column or an attribute column.

If you do not specify a column name, all data in the row is returned.

Note
  • By default, Tablestore returns the data from all the columns of the row when you query a row. You can use the columnsToGet parameter to read data from specific columns. For example, if col0 and col1 are added to columnsToGet, only the values of the col0 and col1 columns are returned.
  • If you use columnsToGet and a filter together, Tablestore first queries the columns specified by columnsToGet, and then returns rows that meet the filter conditions.
maxVersions The maximum number of data versions that you want to read.
Note You must set at least one of the following parameters: maxVersions and timeRange.
  • If only maxVersions is specified, data of the specified number of versions is returned from the latest to the earliest.
  • If only timeRange is specified, all data whose versions are within the specified time range or data of the specified version is returned.
  • If both maxVersions and timeRange are specified, data of the specified number of versions within the time range is returned from the latest to the earliest.
timeRange The range of versions or a version to be read. For more information, see TimeRange.
Note You must set at least one of the following parameters: maxVersions and timeRange.
  • If only maxVersions is specified, data of the specified number of versions is returned from the latest to the earliest.
  • If only timeRange is specified, all data whose versions are within the specified time range or data of the specified version is returned.
  • If both maxVersions and timeRange are specified, data of the specified number of versions within the time range is returned from the latest to the earliest.
  • To query data within a range, you must set StartTime and EndTime. StartTime specifies the start timestamp. EndTime specifies the end timestamp. The time range is a left-closed and right-open interval, which is [StartTime, EndTime).
  • To query data within a range of versions, set SpecificTime. SpecificTime specifies a specific timestamp.

Only one of SpecificTime and [StartTime, EndTime) is required.

The timestamp used for the value of time_range ranges from 0 to Int64.MaxValue. Unit: milliseconds.

filter The filter used to filter the query results on the server side. Only rows that meet the filter conditions are returned. For more information, see Configure filter.
Note If you use columnsToGet and a filter together, Tablestore first queries the columns specified by columnsToGet, and then returns rows that meet the filter conditions.

Examples

  • Example 1

    Reads a row.

        // 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. 
        PrimaryKey primaryKey = new PrimaryKey();
        primaryKey.Add("pk0", new ColumnValue(0));
        primaryKey.Add("pk1", new ColumnValue("abc"));
    
        try
        {
            // Construct a query request object. The entire row is read if no column is specified. 
            var request = new GetRowRequest(TableName, primaryKey);
    
            // Call the GetRow operation to query data. 
            var response = otsClient.GetRow(request);
    
            // Generate the data of the row. The code for generated data is omitted. For more information, visit the GitHub link of the sample code. 
    
            // If the operation succeeds, no exception is returned. 
            Console.WriteLine("Get row succeeded.");
        }
        catch (Exception ex)
        {
            // If the operation fails, an exception is returned. Handle the exception. 
            Console.WriteLine("Update table failed, exception:{0}", ex.Message);
        }
                

    For the detailed sample code, visit GetRow@GitHub.

  • Example 2

    The following code provides an example on how to use the filter feature to read a row of data.

    In this example, the values of col0 and col1 that meet the following filter condition are set to returned: the value of col0 is 5 or the value of col1 is not ff.

        // 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. 
        PrimaryKey primaryKey = new PrimaryKey();
        primaryKey.Add("pk0", new ColumnValue(0));
        primaryKey.Add("pk1", new ColumnValue("abc"));
    
        var rowQueryCriteria = new SingleRowQueryCriteria("SampleTable");
        rowQueryCriteria.RowPrimaryKey = primaryKey;
    
        // Condition 1: The value of col0 is 5. 
        var filter1 = new RelationalCondition("col0",
                    RelationalCondition.CompareOperator.EQUAL,
                    new ColumnValue(5));
    
        // Condition 2 :The value of col1 is not equal to ff. 
        var filter2 = new RelationalCondition("col1", RelationalCondition.CompareOperator.NOT_EQUAL, new ColumnValue("ff"));
    
        // Construct a combination of Condition 1 and Condition 2. The relationship of the combination is OR. 
        var filter = new CompositeCondition(CompositeCondition.LogicOperator.OR);
        filter.AddCondition(filter1);
        filter.AddCondition(filter2);
    
        rowQueryCriteria.Filter = filter;
    
        // Set to return the values of col0 and col1 from the rows you want to query. Then, filter the queried data based on the specified conditions. 
        rowQueryCriteria.AddColumnsToGet("col0");
        rowQueryCriteria.AddColumnsToGet("col1");
    
        // Construct GetRowRequest. 
        var request = new GetRowRequest(rowQueryCriteria);
    
        try
        {
            // Perform the query. 
            var response = otsClient.GetRow(request);
    
            // Generate data or perform the related logical operation. The code for generated data is omitted. 
    
            // If the operation succeeds, no exception is returned. 
            Console.WriteLine("Get row with filter succeeded.");
        }
        catch (Exception ex)
        {
            // If the operation fails, an exception is returned. Handle the exception. 
            Console.WriteLine("Get row with filter failed, exception:{0}", ex.Message);
        }
                

    For the detailed sample code, visit GetRowWithFilter@GitHub.

UpdateRow

You can call this operation to update the data of a specified row. You can add attribute columns to or delete attribute columns from a row, delete a specified version of data from an attribute column, or update the existing data in an attribute column. If the row does not exist, a new row is added.

Note If an UpdateRow operation only specifies columns to delete from a row and the row does not exist, no row is inserted into the table.

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 can configure to perform the UpdateRow operation. You can configure a row existence condition or a column-based condition. For more information, see Configure conditional update.
attribute The attribute column you want to update.
  • An attribute column is specified by parameters in the following sequence: the attribute column name, attribute column value, attribute column value type (optional), and timestamp (optional).

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

    • The 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 the version number, make sure that the version number is a 64-bit timestamp accurate to milliseconds within the valid version range.
  • To delete a specified version of data from an attribute column, you need to only set the attribute column name and timestamp.

    The timestamp is a 64-bit integer that indicates a specified version of data. Unit: milliseconds.

  • To delete an attribute column, you need to only set the attribute column name.
    Note A row exists even if all attribute columns in the row are deleted. To delete a row, use the DeleteRow operation.

Example

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 consistent with the primary key specified in TableMeta when you create a table. 
    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 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.

DeleteRow

You can call this operation to delete a row. If the row to delete does not exist, the table remains unchanged.

API operations

    /// <summary>
    /// Delete a row of data based on the specified table name and primary keys of the row. 
    /// </summary>
    /// <param name="request">Request instance</param>
    /// <returns>Response instance</returns>
    public DeleteRowResponse DeleteRow(DeleteRowRequest request);

    /// <summary>
    /// The asynchronous mode of DeleteRow. 
    /// </summary>
    public Task<DeleteRowResponse> DeleteRowAsync(DeleteRowRequest 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 can configure to perform the UpdateRow operation. You can configure a row existence condition or a column-based condition. For more information, see Configure conditional update.

Example

The following code provides an example on how to delete a row of data:

    // The values of the primary key columns of the row to be deleted are 0 and "abc". 
    var primaryKey = new PrimaryKey();
    primaryKey.Add("pk0", new ColumnValue(0));
    primaryKey.Add("pk1", new ColumnValue("abc"));

    try
    {
        // Construct a request. RowExistenceExpectation.EXPECT_EXIST indicates that the row is deleted only when the specified row exists. 
        var deleteRowRequest = new DeleteRowRequest("SampleTable", new Condition(RowExistenceExpectation.EXPECT_EXIST), primaryKey);

        // Call the DeleteRow operation to delete data. 
        otsClient.DeleteRow(deleteRowRequest);

        // If the operation succeeds, no exception is returned. 
        Console.Writeline("Delete table succeeded.");
    }
    catch (Exception ex)
    {
        // If the operation fails, an exception is returned. Handle the exception. 
        Console.WriteLine("Delete table failed, exception:{0}", ex.Message);
    }
            

For the detailed sample code, visit DeleteRow@GitHub.