Tablestore provides the GetRow operation to allow you to read a single row of data and provides operations such as BatchGetRow and GetRange to allow you to read 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.

Read a single row of data

You can call the GetRow operation to read a single row of data.

One of the following results of the read operation 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 columns that you want to return. You can specify the names of primary key columns or attribute columns.

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

Note
  • By default, Tablestore returns the data from all columns of a row when you query the 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 configure the columnsToGet and filter parameters, Tablestore queries the columns that are specified by columnsToGet, and then returns the rows that meet the filter conditions.
maxVersions The maximum number of data versions that you can read.
Note You must configure at least one of the following parameters: maxVersions and timeRange.
  • If only maxVersions is configured, data of the specified number of versions is returned from the most recent data entry to the earliest data entry.
  • If only timeRange is configured, all data whose versions are in the specified time range or data of the specified version is returned.
  • If maxVersions and timeRange are configured, data of the specified number of versions in the time range is returned from the most recent data entry to the earliest data entry.
timeRange The range of versions or the specific version that you want to read. For more information, see TimeRange.
Note You must configure at least one of the following parameters: maxVersions and timeRange.
  • If only maxVersions is configured, data of the specified number of versions is returned from the most recent data entry to the earliest data entry.
  • If only timeRange is configured, all data whose versions are in the specified time range or data of the specified version is returned.
  • If maxVersions and timeRange are configured, data of the specified number of versions in the time range is returned from the most recent data entry to the earliest data entry.
  • To query data in a range, you must configure the StartTime and EndTime parameters. StartTime specifies the start timestamp. EndTime specifies the end timestamp. The time range is a left-closed, right-open interval that is in the [StartTime, EndTime) format.
  • To query data of a specific version, you must configure the SpecificTime parameter. SpecificTime specifies a specific timestamp.

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

Valid values of timeRange range from 0 to Int64.MaxValue. Unit: milliseconds.

filter The filter that you want to use 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 configure the columnsToGet and filter parameters, Tablestore queries the columns that are specified by columnsToGet, and then returns the rows that meet the filter conditions.

Examples

  • Example 1

    Read a single row of data

        // 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"));
    
        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);
    
            // Return the data of the row. In this example, the sample code that is used to return the data of the row is omitted. For more information, visit the GitHub link to view the sample code. 
    
            // If the operation is successful, 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);
        }
                

    To view the detailed sample code, visit GetRow@GitHub.

  • Example 2

    The following code provides an example on how to read a row of data when a filter is used:

    In this example, the values of col0 and col1 that meet the following filter condition are 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 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"));
    
        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. Use the OR operator to define the relationship of the combination. 
        var filter = new CompositeCondition(CompositeCondition.LogicOperator.OR);
        filter.AddCondition(filter1);
        filter.AddCondition(filter2);
    
        rowQueryCriteria.Filter = filter;
    
        // Specify col0 and col1 as the columns that you want to return. Tablestore queries the values of col0 and col1, and then returns the rows that meet the filter conditions. 
        rowQueryCriteria.AddColumnsToGet("col0");
        rowQueryCriteria.AddColumnsToGet("col1");
    
        // Construct GetRowRequest. 
        var request = new GetRowRequest(rowQueryCriteria);
    
        try
        {
            // Perform the query. 
            var response = otsClient.GetRow(request);
    
            // Return data or perform the related logical operation. In this example, the code that is used to return data or perform the related logical operation is omitted. 
    
            // If the operation is successful, 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);
        }
                

    To view the detailed sample code, visit GetRowWithFilter@GitHub.

Read multiple rows of data in a batch

You can call the BatchGetRow operation to read multiple rows of data from one or more tables in a batch. The BatchGetRow operation consists of multiple GetRow operations. The process of constructing a suboperation is the same as the process of calling the GetRow operation. BatchGetRow supports filters.

Note that the BatchGetRow operation uses the same parameter configurations for all rows. For example, if ColumnsToGet is set to [colA], only the value of the colA column is read from all rows.

If you call the BatchGetRow operation, each GetRow operation is separately performed and the response to each GetRow operation is separately returned.

Usage notes

When you call the BatchGetRow operation to read multiple rows in a batch, some rows may fail to be read. If this happens, Tablestore does not return exceptions, but returns BatchGetRowResponse in which the indexes and error messages of the failed rows are included. Therefore, when you call the BatchGetRow operation, you must check the return values to determine whether the status of each row is successful.

Operations

/// <summary>
/// <para>Concurrently read multiple rows of data from one or more tables. </para>
/// <para>The BatchGetRow operation performs a set of multiple GetRow operations. The execution, the return process of results, and the CU consumption of each operation are separately performed. </para>
/// Compared with the execution of a large number of GetRow operations, you can use BatchGetRow to reduce the request response time and increase the data read rate. 
/// </summary>
/// <param name="request">Request instance</param>
/// <returns>Response instance</returns>
public BatchGetRowResponse BatchGetRow(BatchGetRowRequest request);

/// <summary>
/// Asynchronous mode of BatchGetRow. 
/// </summary>
public Task<BatchGetRowResponse> BatchGetRowAsync(BatchGetRowRequest request);            

Example

The following code provides an example on how to read 10 rows of data in a batch:

// Construct a request object to read multiple rows of data. Set the primary key for 10 rows of data. 
List<PrimaryKey> primaryKeys = new List<PrimaryKey>();
for (int i = 0; i < 10; i++)
{
    PrimaryKey primaryKey = new PrimaryKey();
    primaryKey.Add("pk0", new ColumnValue(i));
    primaryKey.Add("pk1", new ColumnValue("abc"));
    primaryKeys.Add(primaryKey);
}

try
{
    BatchGetRowRequest request = new BatchGetRowRequest();
    request.Add(TableName, primaryKeys);

    // Call BatchGetRow to read 10 rows of data. 
    var response = otsClient.BatchGetRow(request);
    var tableRows = response.RowDataGroupByTable;
    var rows = tableRows[TableName];

    // Export data in rows. In this example, the code for this operation is omitted. For more information, visit the GitHub link that is specified in the sample code. 

    // When multiple rows are written, specific rows may fail to be read. You must check the return values and whether the status of each row is successful. For more information, visit the GitHub link that is provided in the sample code. 
}
catch (Exception ex)
{
    // If the operation fails, an exception is returned. Handle the exception. 
    Console.WriteLine("Batch get row failed, exception:{0}", ex.Message);
}            

To view the detailed sample code, visit BatchGetRow@GitHub.

Read data whose primary key is in a specified range

You can call the GetRange operation to read data whose primary key is in a specified range.

The GetRange operation allows you to read data whose primary key is in a specified range in a forward or backward direction. You can also specify the number of rows to read. If the range is large and the number of scanned rows or the volume of scanned data exceeds the upper limit, the scan stops, and the rows that are read and information about the primary key of the next row are returned. You can initiate a request to start from where the last operation left off and read the remaining rows based on information about the primary key of the next row returned by the previous operation.

Note In Tablestore tables, all rows are sorted by the primary key. The primary key of a table sequentially consists of all primary key columns. Therefore, do not assume that the rows are sorted based on a specific primary key column.

Usage notes

GetRange follows the leftmost matching principle. Tablestore compares values in sequence from the first primary key column to the last primary key column to read data whose primary key is in a specified range. For example, the primary key of a data table consists of the following primary key columns: PK1, PK2, and PK3. When data is read, Tablestore first determines whether the PK1 value of a row is in the range that is specified for the first primary key column. If the PK1 value of a row is in the range, Tablestore stops determining whether the values of other primary key columns of the row are in the ranges that are specified for each primary key column and returns the row. If the PK1 value of a row is not in the range, Tablestore continues to determine whether the values of other primary key columns of the row are in the ranges that are specified for each primary key column in the same manner as PK1.

If one of the following conditions is met, the GetRange operation may stop and return data:
  • The amount of scanned data reaches 4 MB.
  • The number of scanned rows reaches 5,000.
  • The number of returned rows reaches the upper limit.
  • The read throughput is insufficient to read the next row of data because all reserved read throughput is consumed.

API operations

/// <summary>
/// Query data whose primary key is in a specified range. 
/// </summary>
/// <param name="request">Request instance</param>
/// <returns>Response instance</returns>
public GetRangeResponse GetRange(GetRangeRequest request);

/// <summary>
/// The asynchronous mode of GetRange. 
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public Task<GetRangeResponse> GetRangeAsync(GetRangeRequest request);              

Parameters

Parameter Description
tableName The name of the data table.
direction The order in which you want to sort the rows in the response.
  • If you set this parameter to FORWARD, the value of the inclusiveStartPrimaryKey parameter must be smaller than the value of the exclusiveEndPrimaryKey parameter, and the rows in the response are sorted in the ascending order of primary key values.
  • If you set this parameter to BACKWARD, the value of the inclusiveStartPrimaryKey parameter must be greater than the value of the exclusiveEndPrimaryKey parameter, and the rows in the response are sorted in the descending order of primary key values.

For example, if you set the direction parameter to FORWARD for a table that contains two primary keys A and B, and the value of A is smaller than the value of B, the rows whose primary key values are greater than or equal to the value of A but smaller than the value of B are returned in ascending order from A to B. If you set the direction parameter to BACKWARD, the rows whose primary key values are smaller than or equal to the value of B and greater than the value of A are returned in descending order from B to A.

inclusiveStartPrimaryKey The start primary key and end primary key of the range that you want to read. The start primary key and end primary key must be valid primary keys or virtual points that contain data of the INF_MIN type and INF_MAX type. The number of columns for each virtual point must be the same as the number of columns of each primary key.

INF_MIN indicates an infinitely small value. All values of other types are greater than the INF_MIN type value. INF_MAX indicates an infinitely great value. All values of other types are smaller than the INF_MAX type value.

  • inclusiveStartPrimaryKey indicates the start primary key. If a row that contains the start primary key exists, the row of data is returned.
  • exclusiveEndPrimaryKey indicates the end primary key. Regardless of whether a row that contains the end primary key exists, the row of data is not returned.

The rows in the data table are sorted in ascending order based on the primary key values. The range that is used to read data is a left-closed, right-open interval. If data is read in the forward direction, the rows whose primary keys are greater than or equal to the start primary key but smaller than the end primary key are returned.

exclusiveEndPrimaryKey
limit The maximum number of rows that can be returned. The value of this parameter must be greater than 0.

An operation stops after the maximum number of rows that can be returned in the forward or backward direction is reached, even if some rows in the specified range are not returned. In this case, you can use the checkpoint value in the response for the next read operation.

columnsToGet The columns that you want to return. You can specify the names of primary key columns or attribute columns.

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

Note
  • By default, Tablestore returns the data from all columns of a row when you query the row. You can use the columnsToGet parameter to return specific columns. For example, if col0 and col1 are added to columnsToGet, only the values of the col0 and col1 columns are returned.
  • If a row is in the specified range that you want to read based on the primary key value but does not contain the specified columns that you want to return, the response excludes the row.
  • If you configure the columnsToGet and filter parameters, Tablestore queries the columns that are specified by columnsToGet, and then returns the rows that meet the filter conditions.
maxVersions The maximum number of data versions that can be returned.
Note You must configure at least one of the following parameters: maxVersions and timeRange.
  • If only maxVersions is configured, data of the specified number of versions is returned from the most recent data entry to the earliest data entry.
  • If only timeRange is configured, all data whose versions are in the specified time range or data of the specified version is returned.
  • If maxVersions and timeRange are configured, data of the specified number of versions in the time range is returned from the most recent data entry to the earliest data entry.
timeRange The range of versions or the specific version that you want to read. For more information, see TimeRange.
Note You must configure at least one of the following parameters: maxVersions and timeRange.
  • If only maxVersions is configured, data of the specified number of versions is returned from the most recent data entry to the earliest data entry.
  • If only timeRange is configured, all data whose versions are in the specified time range or data of the specified version is returned.
  • If maxVersions and timeRange are configured, data of the specified number of versions in the time range is returned from the most recent data entry to the earliest data entry.
  • To query data in a range, you must configure the StartTime and EndTime parameters. StartTime specifies the start timestamp. EndTime specifies the end timestamp. The time range is a left-closed, right-open interval that is in the [StartTime, EndTime) format.
  • To query data of a specific version, you must configure the SpecificTime parameter. SpecificTime specifies a specific timestamp.

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

Valid values of timeRange range from 0 to Int64.MaxValue. Unit: milliseconds.

filter The filter that you want to use to filter the query results on the server side. Only rows that meet the filter conditions are returned. For more information, see Configure a filter.
Note If you configure the columnsToGet and filter parameters, Tablestore queries the columns that are specified by columnsToGet, and then returns the rows that meet the filter conditions.
nextStartPrimaryKey The start primary key of the next read request. The value of nextStartPrimaryKey can be used to determine whether all data is read.
  • If the value of nextStartPrimaryKey is not empty in the response, the nextStartPrimaryKey value can be used as the value of the start primary key for the next GetRange operation.
  • If the value of nextStartPrimaryKey is empty in the response, all data in the range is returned.

Examples

The following code provides an example on how to read data whose primary key is in a specified range:

// Read all rows whose primary key is in the range (0, INF_MIN) to (100, INF_MAX). 
var inclusiveStartPrimaryKey = new PrimaryKey();
inclusiveStartPrimaryKey.Add("pk0", new ColumnValue(0));
inclusiveStartPrimaryKey.Add("pk1", ColumnValue.INF_MIN);

var exclusiveEndPrimaryKey = new PrimaryKey();
exclusiveEndPrimaryKey.Add("pk0", new ColumnValue(100));
exclusiveEndPrimaryKey.Add("pk1", ColumnValue.INF_MAX);

try
{
    // Construct a request object to read data whose primary key is in the specified range. 
    var request = new GetRangeRequest(TableName, GetRangeDirection.Forward,
                    inclusiveStartPrimaryKey, exclusiveEndPrimaryKey);

    var response = otsClient.GetRange(request);

    // Continue the read operation if only part of data is returned. 
    var rows = response.RowDataList;
    var nextStartPrimaryKey = response.NextPrimaryKey;
    while (nextStartPrimaryKey != null)
    {
        request = new GetRangeRequest(TableName, GetRangeDirection.Forward,
                        nextStartPrimaryKey, exclusiveEndPrimaryKey);
        response = otsClient.GetRange(request);
        nextStartPrimaryKey = response.NextPrimaryKey;
        foreach (RowDataFromGetRange row in response.RowDataList)
        {
            rows.Add(row);
        }
    }

    // Return the data of the rows. In this example, the sample code that is used to return the data of the rows is omitted. For more information, visit the GitHub link to view the sample code. 

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

To view the detailed sample code, visit GetRange@GitHub.

Read data whose primary key is in a specified range by using an iterator

You can call the GetRangeIterator operation to read data whose primary key is in a specified range by using an iterator.

Operations

/// <summary>
/// Obtain data from multiple rows in the specified range. Return the iterator that is used to process each row of data. 
/// </summary>
/// <param name="request"><see cref="GetIteratorRequest"/></param>
/// <returns>Return the <see cref="RowDataFromGetRange"/> iterator. </returns>
public IEnumerable<RowDataFromGetRange> GetRangeIterator(GetIteratorRequest request);           

Example

// Read all rows in the range (0, "a") to (1000, "xyz").

// Read all rows in the range from (0, "a") to (1000, "xyz"). 
PrimaryKey inclusiveStartPrimaryKey = new PrimaryKey();
inclusiveStartPrimaryKey.Add("pk0", new ColumnValue(0));
inclusiveStartPrimaryKey.Add("pk1", new ColumnValue("a"));

PrimaryKey exclusiveEndPrimaryKey = new PrimaryKey();
exclusiveEndPrimaryKey.Add("pk0", new ColumnValue(1000));
exclusiveEndPrimaryKey.Add("pk1", new ColumnValue("xyz"));

// Construct a CapacityUnit to record the number of CUs that are consumed by the iteration operation. 
var cu = new CapacityUnit(0, 0);

try
{
    // Construct a GetIteratorRequest. Filter conditions are supported. 
    var request = new GetIteratorRequest(TableName, GetRangeDirection.Forward, inclusiveStartPrimaryKey,
                                                exclusiveEndPrimaryKey, cu);

    var iterator = otsClient.GetRangeIterator(request);
    // Use the iterator that reads data in a traversal method. 
    foreach (var row in iterator)
    {
        // Execute the processing logic. 
    }

    Console.WriteLine("Iterate row succeeded");
} 
catch (Exception ex)
{
    Console.WriteLine("Iterate row failed, exception:{0}", ex.Message);
}            

To view the detailed code, visit GetRangeIterator@GitHub.