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 you want to insert exists, the PutRow operation deletes all versions of data from all columns in the existing row and then inserts a new row.

  • 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 table.
    primaryKey The primary key of the row.
    Note
    • The configured number and types of primary key columns must be consistent with the actual number and types of primary key columns of the table.
    • For an auto-increment primary key column, you need only to set the value of the auto-increment primary key column to a placeholder. For more information, see Configure an auto-increment primary key column.
    attribute The attribute columns of the row.
    • Each attribute column is specified by parameters in the following sequence: the attribute column name, attribute column value type (optional), attribute column value, and timestamp (optional).
    • A timestamp is the data version number. For more information, see Max 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 the system 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.
      • When you choose to specify the version number, ensure 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-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. 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 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));
    
                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.
        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 operation succeeds, no exception is returned.
            Console.WriteLine("Put row async succeeded.");
        }
        catch (Exception ex)
        {
            // If the operation 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.
  • 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 table.
    primaryKey The primary key of the row.
    Note The configured number and types of primary key columns must be consistent with the actual number and types of primary key columns of the table.
    columnsToGet The names of the columns to return. You can specify the names of the primary key columns and the names of attribute columns.

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

    Note
    • By default, Tablestore returns the data from all columns of the row when you query a row. You can use the columnsToGet parameter to read data from specified columns. For example, the system returns only the values of col0 and col1 if col0 and col1 are included in columnsToGet.
    • If you use columnsToGet and filter together, the system first queries the columns specified by columnsToGet, and then returns rows that meet the filter conditions.
    maxVersions The maximum number of versions that can be read.
    Note You must set at least one of the following parameters: 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 whose versions are within the specified time range or data of the specified version 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 Specifies a range of versions to read or a version of data to read. For more information, see TimeRange.
    Note You must set at least one of the following parameters: 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 whose versions are within the specified time range or data of the specified version 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 specifies the end timestamp. The time range is a left-closed and right-open interval, which is [start_time, end_time).
    • 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 You can set filter conditions to filter the queried results on the server side. Only rows that meet the specified filter conditions are returned. For more information, see Configure filter.
    Note If you use columnsToGet and filter together, the system first queries the columns specified by columnsToGet, and then returns rows that meet the filter conditions.
  • 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 operation succeeds, no exception is returned.
            Console.WriteLine("Get row succeeded.");
        }
        catch (Exception ex)
        {
            // If the operation 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.

    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 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 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 specified 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.
  • 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 table.
    primaryKey The primary key of the row.
    Note The configured number and types of primary key columns must be consistent with the actual number and types of primary key columns of the table.
    condition You can use conditional update to set a row existence condition or columns-based conditions for the row. For more information, see Configure conditional update.
    attribute The attribute column to be updated.
    • 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).

      The timestamp is the version number of the data. It can be automatically generated or customized. If you do not specify this parameter, Tablestore automatically generates a timestamp. For more information, see Max versions and TTL.

      • 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.
      • When you choose to specify the version number, ensure that the version number is a 64-bit timestamp accurate to the millisecond within the valid version range.
    • To delete a specified version of data from an attribute column, you need only to 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 only to 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.
  • 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 operation succeeds, no exception is returned.
            Console.Writeline("Update row succeeded.");
        }
        catch (Exception ex)
        {
            // If the operation 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. If the specified row does not exist, no change is made to the table.

  • 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 table.
    primaryKey The primary key of the row.
    Note The configured number and types of primary key columns must be consistent with the actual number and types of primary key columns of the table.
    condition You can use conditional update to set a row existence condition or columns-based conditions for the row. For more information, see Configure conditional update.
  • Examples

    The following code provides an example on how to delete a row from a table:

        // 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 and handled.
            Console.WriteLine("Delete table failed, exception:{0}", ex.Message);
        }
                

    For the detailed sample code, visit DeleteRow@GitHub.