Tablestore SDKs provide 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 of data. If the row already exists, this operation deletes the existing row (all columns and all versions of the original row), and then writes data to the row.

  • API operations
    /// <summary>
    /// Write a row of data based on the specified table name, primary keys, and attributes. Thu number of capacity unites (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>
    /// Asynchronous mode of PutRow.
    /// </summary>
    public Task<PutRowResponse> PutRowAsync(PutRowRequest request);
                        
  • Parameters
    Parameter Description
    tableName The name of the table.
    primaryKey The primary key of the row.
    Note
    • The number and type of primary key columns configured must be consistent with those of primary key columns of the table.
    • When the primary key column is an auto-increment column, you need only to set the value of the auto-increment column to placeholders. For more information, see Configure an auto-increment primary key column.
    attribute The attribute column of the row.
    • Each item specifies the values in the following sequence: the attribute column name, attribute column value type (optional), attribute column value, and timestamp (optional).
    • The timestamp is the version number of the data. For more information, see Max versions and TTL.

      You can customize a version number or specify that the system generates the version number. If the timestamp is not set, the version number is generated by the system.

      • The version number is calculated based on the number of milliseconds that have elapsed since the epoch time January 1, 1970, 00:00:00 UTC.
      • When you choose to 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 You can use conditional update to set row existence conditions or column-based conditions. For more information, see Configure conditional update.
    Note
    • In addition to row conditions, the Condition parameter also supports column 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 no matter whether the specified row exists. 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.
  • Example 1

    The following code provides an example on how to 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 when you 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 task succeeds, no exception is returned.
            Console.WriteLine("Put row succeeded.");
        }
        catch (Exception ex)
        {
            // If the task 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 col1 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));
    
                var request = new PutRowRequest(tableName, new Condition(RowExistenceExpectation.EXPECT_EXIST),
                                    primaryKey, attribute);
    
        // When the value of col0 is greater than 24, the row can be inserted to overwrite the original value again.
        try
        {
            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 task succeeds, no exception is returned.
            Console.WriteLine("Put row async succeeded.");
        }
        catch (Exception ex)
        {
            // If the task fails, an exception is returned and handled.
            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 of data.

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>
    /// Asynchronous mode of GetRow.
    /// </summary>
    public Task<GetRowResponse> GetRowAsync(GetRowRequest request);
                
  • Parameters
    Parameter Description
    tableName The name of the table.
    primaryKey The primary key of the row.
    Note The number and type of primary key columns configured must be consistent with those of primary key columns of the table.
    columnsToGet The set of columns to read. The column name can be the primary key column or attribute column.

    If you do not specify this parameter, all data in the row is returned.

    Note
    • If you query a row of data, the system returns the data in all columns of the row. You can set the columnsToGet parameter to read the data only in specified columns. If col0 and col1 are added to columnsToGet, only the values of the col0 and col1 columns are returned.
    • When columnsToGet and filter are used at the same time, the columns specified by columnsToGet are returned. Then, the returned columns are filtered.
    maxVersions The maximum number of read versions.
    Note You must specify at least one of maxVersions and timeRange.
    • If you specify only maxVersions, data of up to the specified number of versions is returned from the latest to the earliest.
    • If you specify only timeRange, all data within a range or a version of data is returned.
    • If you specify both maxVersions and timeRange, data of up to the specified number of versions within the time range is returned from the latest to the earliest.
    timeRange Reads data within a range of versions or a version of data. For more information, see TimeRange.
    Note You must specify at least one of maxVersions and timeRange.
    • If you specify only maxVersions, data of up to the specified number of versions is returned from the latest to the earliest.
    • If you specify only timeRange, all data within a range or a version of data is returned.
    • If you specify both maxVersions and timeRange, data of up to 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 indicates the end timestamp. The time range is a left-closed and right-open interval, which is [StartTime, EndTime).
    • If you query data within a range of versions, set SpecificTime. SpecificTime specifies a specific timestamp.

    You can set one of SpecificTime and [StartTime, EndTime),

    Valid values: [0, Int64.MaxValue). Unit: milliseconds.

    filter Filters the read results on the server side and returns only the rows of data that meet the conditions in the filter. For more information, see Configure filter.
    Note When columnsToGet and filter are used at the same time, the columns specified by columnsToGet are returned. Then, the returned columns are filtered.
  • Example 1

    The following code provides an example on how to read 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.
        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 task succeeds, no exception is returned.
            Console.WriteLine("Get row succeeded.");
        }
        catch (Exception ex)
        {
            // If the task fails, an exception is returned and handled.
            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.

    The following example queries data, configures the system to return the data only in col0 and col1, and filters the data in col0 and col1 based on the condition that values in col0 are equal to 5 or col1 is not equal to 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;
    
        // Configure the rows you want to query by using the condition [col0, col1], and then filter the queried data based on the specified conditions.
        rowQueryCriteria.AddColumnsToGet("col0");
        rowQueryCriteria.AddColumnsToGet("col1");
    
        // Construct GetRowRequest.
        var request = new GetRowRequest(rowQueryCriteria);
    
        try
        {
            // Execute the query.
            var response = otsClient.GetRow(request);
    
            // Generate data or perform the related logical operation. The code for generated data is omitted.
    
            // If the task succeeds, no exception is returned.
            Console.WriteLine("Get row with filter succeeded.");
        }
        catch (Exception ex)
        {
            // If the task fails, an exception is returned and handled.
            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 data of a specified row. You can add or delete attribute columns of 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 the UpdateRow request contains only columns to delete, and the specified row does not exist, a new row is not added.
  • 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>
        /// 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 table.
    primaryKey The primary key of the row.
    Note The number and type of primary key columns configured must be consistent with those of primary key columns of the table.
    condition You can use conditional update to set row existence conditions or column-based conditions. For more information, see Configure conditional update.
    attribute The attribute column to be updated.
    • To add or update data, you must set the attribute name, attribute value, attribute type (optional), and timestamp (optional).

      You can customize a version number or specify that the system generates the version number. If the timestamp is not set, the version number is generated by the system. For more information, see Max versions and TTL.

      • The version number is calculated based on the number of milliseconds that have elapsed since 00:00:00 UTC on January 1, 1970.
      • When you choose to customize the version number, make sure that the version number is a 64-bit timestamp accurate to the millisecond within the valid version range.
    • To delete a specific version of an attribute, you need only to set the attribute name and timestamp.

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

    • When you delete an attribute column, you need only to set the attribute name.
      Note A row exists even if all attribute columns in the row are deleted. To delete a row, use the DeleteRow operation.
  • 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 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 task succeeds, no exception is returned.
            Console.Writeline("Update row succeeded.");
        }
        catch (Exception ex)
        {
            // If the task fails, an exception is returned and handled.
            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 of data. If the row to delete does not exist, no changes are made to the table.

  • 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>
        /// Asynchronous mode of DeleteRow.
        /// </summary>
        public Task<DeleteRowResponse> DeleteRowAsync(DeleteRowRequest request);
                
  • Parameters
    Parameter Description
    tableName The name of the table.
    primaryKey The primary key of the row.
    Note The number and type of primary key columns configured must be consistent with those of primary key columns of the table.
    condition You can use conditional update to set row existence conditions or column-based conditions. For more information, see Configure conditional update.
  • Examples

    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 task succeeds, no exception is returned.
            Console.Writeline("Delete table succeeded.");
        }
        catch (Exception ex)
        {
            // If the task fails, an exception is returned and handled.
            Console.WriteLine("Delete table failed, exception:{0}", ex.Message);
        }
                

    For the detailed sample code, visit DeleteRow@GitHub.