All Products
Search
Document Center

Tablestore:Getting started with Tablestore SDK for Java

Last Updated:Dec 01, 2023

You can use the Wide Column model and TimeSeries model of Tablestore by using Tablestore SDK for Java to create a table, write data to the table, and then read data from the table. This topic describes how to use the Wide Column model and TimeSeries model by using Tablestore SDK for Java.

Background information

Tablestore provides various data models such as the Wide Column model, TimeSeries model, and Timeline model. The SDK reference of Tablestore SDK for Java describes how to use the features supported by the Wide Column model and TimeSeries model by using Tablestore SDK for Java.

  • You can use the Wide Column model to create a data table, write data to the data table, and then read data from the data table. For more information about the sample code, see Examples of using the Wide Column model.

  • You can use the TimeSeries model to create a time series table, write data to the time series table, and then read data from the time series table. For more information about the sample code, see Examples of using the TimeSeries model.

Prerequisites

  • An OTSClient instance and a TimeseriesClient instance are initialized. For more information, see Initialization.

  • Tablestore SDK for Java V4.0.0 or later is installed. Tablestore SDK for Java V4.0.0 and later support multi-version and time to live (TTL) management. Before you create a data table, make sure that you understand data versions and TTL. For more information, see Data versions and TTL.

Examples of using the Wide Column model

You can use the initialized OTSClient instance to use the features supported by the Tablestore Wide Column model. This section describes how to use the Wide Column model to create a data table, write data to the data table, and then read data from the data table by using Tablestore SDK for Java and provides sample code.

Step 1: Create a data table

The following sample code provides an example on how to create a data table in the Tablestore instance named myinstance. In this table, a maximum of three versions of data can be retained for an attribute column, and the data never expires.

Note

The endpoint of an instance varies based on the region in which the instance resides. For more information about how to obtain the endpoint, see the Obtain an endpoint section of the "Initialization" topic.

import com.alicloud.openservices.tablestore.SyncClient;
import com.alicloud.openservices.tablestore.model.*;

public class CreateTable {
    public static void main(String[] args) {
        
        // Create and initialize a Tablestore client. 
        final String endPoint = "https://myinstance.cn-hangzhou.ots.aliyuncs.com";
        String accessKeyId = System.getenv("OTS_AK_ENV");
        String accessKeySecret = System.getenv("OTS_SK_ENV");
        final String instanceName = "myinstance";
        SyncClient client = new SyncClient(endPoint, accessKeyId, accessKeySecret, instanceName);
        
        // Create an API request and specify the request parameters. 
        // Specify the name of the data table. 
        TableMeta tableMeta = new TableMeta("<TABLE_NAME>");
        // Add a primary key column to the data table. 
        tableMeta.addPrimaryKeyColumn(new PrimaryKeySchema("pk", PrimaryKeyType.STRING));
        // Specify the validity period of data. A value of -1 specifies that the data never expires. Unit: seconds. You must set the timeToLive parameter to -1 for a data table for which index tables are created. 
        int timeToLive = -1;
        // Specify the maximum number of data versions that can be retained for each column. A value of 1 specifies that only the latest version of data is retained for each column. You must set the maxVersions parameter to 1 for a data table for which index tables are created. 
        int maxVersions = 3;
        TableOptions tableOptions = new TableOptions(timeToLive, maxVersions);
        CreateTableRequest request = new CreateTableRequest(tableMeta, tableOptions);
        // Specify the reserved read throughput and reserved write throughout. The values must be set to 0 for data tables in capacity instances and can be set to non-zero values for data tables in high-performance instances. 
        request.setReservedThroughput(new ReservedThroughput(new CapacityUnit(0, 0)));
        
        // Initiate the request. 
        client.createTable(request);
    }
}

Step 2: Write data to the data table

The following sample code provides an example on how to write a row of data to a data table. The row of data contains 10 attribute columns. Three versions of data are written to each attribute column.

import com.alicloud.openservices.tablestore.SyncClient;
import com.alicloud.openservices.tablestore.model.*;

public class PutRow {
    public static void main(String[] args) {
        
        // Create and initialize a Tablestore client. 
        final String endPoint = "https://myinstance.cn-hangzhou.ots.aliyuncs.com";
        String accessKeyId = System.getenv("OTS_AK_ENV");
        String accessKeySecret = System.getenv("OTS_SK_ENV");
        final String instanceName = "myinstance";
        SyncClient client = new SyncClient(endPoint, accessKeyId, accessKeySecret, instanceName);
        
        // Create an API request and specify the request parameters. 
        // Construct the primary key. 
        PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
        primaryKeyBuilder.addPrimaryKeyColumn("pk", PrimaryKeyValue.fromString("pkvalue"));
        PrimaryKey primaryKey = primaryKeyBuilder.build();
        // Specify the name of the data table. 
        RowPutChange rowPutChange = new RowPutChange("<TABLE_NAME>", primaryKey);

        // Add attribute columns. 
        long ts = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 3; j++) {
                rowPutChange.addColumn(new Column("Col" + i, ColumnValue.fromLong(j), ts + j));
            }
        }
        PutRowRequest request = new PutRowRequest(rowPutChange);
       
        // Initiate the request. 
        client.putRow(request);
    }
}

Step 3: Read data from the data table

The following sample code provides an example on how to read a row of data from a data table. Only the latest version of data is read, and only the value of the Col0 column is returned.

import com.alicloud.openservices.tablestore.SyncClient;
import com.alicloud.openservices.tablestore.model.*;

public class GetRow {
    public static void main(String[] args) {
        
        // Create and initialize a Tablestore client. 
        final String endPoint = "https://myinstance.cn-hangzhou.ots.aliyuncs.com";
        String accessKeyId = System.getenv("OTS_AK_ENV");
        String accessKeySecret = System.getenv("OTS_SK_ENV");
        final String instanceName = "myinstance";
        SyncClient client = new SyncClient(endPoint, accessKeyId, accessKeySecret, instanceName);
        
        // Create an API request and specify the request parameters. 
        // Construct the primary key. 
        PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
        primaryKeyBuilder.addPrimaryKeyColumn("pk", PrimaryKeyValue.fromString("pkvalue"));
        PrimaryKey primaryKey = primaryKeyBuilder.build();

        // Specify the table name and primary key to read a row of data. 
        SingleRowQueryCriteria criteria = new SingleRowQueryCriteria("<TABLE_NAME>", primaryKey);
        // Set the setMaxVersions parameter to 1 to read the latest version of data. 
        criteria.setMaxVersions(1);
        // Specify the columns that you want to read. 
        criteria.addColumnsToGet("Col0");
        GetRowRequest getRowRequest = new GetRowRequest(criteria);
        
        // Initiate the request and display the response. 
        GetRowResponse getRowResponse = client.getRow(getRowRequest);
        Row row = getRowResponse.getRow();

        System.out.println("Read complete. Result:");
        System.out.println(row);
    }
}

Examples of using the TimeSeries model

You can use the initialized TimeseriesClient instance to use the features supported by the Tablestore TimeSeries model. This section describes how to use the TimeSeries model to create a time series table, write data to the time series table, and then read data from the time series table by using Tablestore SDK for Java and provides sample code.

Step 1: Create a time series table

The following sample code provides an example on how to create a time series table in the Tablestore instance named myinstance. The data of this time series table never expires.

import com.alicloud.openservices.tablestore.TimeseriesClient;
import com.alicloud.openservices.tablestore.model.TimeseriesTableMeta;
import com.alicloud.openservices.tablestore.model.TimeseriesTableOptions;
import com.alicloud.openservices.tablestore.model.timeseries.CreateTimeseriesTableRequest;

public class CreateTimeseriesTable {
    public static void main(String[] args) {
        
        // Create and initialize a Tablestore client. 
        final String endPoint = "https://myinstance.cn-hangzhou.ots.aliyuncs.com";
        String accessKeyId = System.getenv("OTS_AK_ENV");
        String accessKeySecret = System.getenv("OTS_SK_ENV");
        final String instanceName = "myinstance";
        TimeseriesClient client = new TimeseriesClient(endPoint, accessKeyId, accessKeySecret, instanceName);
        
        // Create an API request and specify the request parameters. 
        String tableName = "<TABLE_NAME>";
        TimeseriesTableMeta timeseriesTableMeta = new TimeseriesTableMeta(tableName);
        int timeToLive = -1;
        timeseriesTableMeta.setTimeseriesTableOptions(new TimeseriesTableOptions(timeToLive));
        CreateTimeseriesTableRequest request = new CreateTimeseriesTableRequest(timeseriesTableMeta);
        
        // Initiate the request. 
        client.createTimeseriesTable(request);
    }
}

Step 2: Write data to the time series table

The following sample code provides an example on how to write data to 10 time series of a time series table:

import com.alicloud.openservices.tablestore.TimeseriesClient;
import com.alicloud.openservices.tablestore.model.ColumnValue;
import com.alicloud.openservices.tablestore.model.timeseries.PutTimeseriesDataRequest;
import com.alicloud.openservices.tablestore.model.timeseries.PutTimeseriesDataResponse;
import com.alicloud.openservices.tablestore.model.timeseries.TimeseriesKey;
import com.alicloud.openservices.tablestore.model.timeseries.TimeseriesRow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PutTimeseriesData {
    public static void main(String[] args) {
        
        // Create and initialize a Tablestore client. 
        final String endPoint = "https://myinstance.cn-hangzhou.ots.aliyuncs.com";
        String accessKeyId = System.getenv("OTS_AK_ENV");
        String accessKeySecret = System.getenv("OTS_SK_ENV");
        final String instanceName = "myinstance";
        TimeseriesClient client = new TimeseriesClient(endPoint, accessKeyId, accessKeySecret, instanceName);
        
        // Create an API request and specify the request parameters. 
        List<TimeseriesRow> rows = new ArrayList<TimeseriesRow>();
        for (int i = 0; i < 10; i++) {
            Map<String, String> tags = new HashMap<String, String>();
            tags.put("region", "hangzhou");
            tags.put("os", "Ubuntu16.04");
            // Specify the measurement name, data source, and tags of a time series to construct the identifier of the time series. 
            TimeseriesKey timeseriesKey = new TimeseriesKey("cpu", "host_" + i, tags);
            // Specify the timeseriesKey and timeInUs parameters to create a row of time series data. 
            TimeseriesRow row = new TimeseriesRow(timeseriesKey, System.currentTimeMillis() * 1000 + i);
            // Add data values. 
            row.addField("cpu_usage", ColumnValue.fromDouble(10.0));
            row.addField("cpu_sys", ColumnValue.fromDouble(5.0));
            rows.add(row);
        }
        String tableName = "<TABLE_NAME>";
        PutTimeseriesDataRequest putTimeseriesDataRequest = new PutTimeseriesDataRequest(tableName);
        putTimeseriesDataRequest.setRows(rows);
        
        // Initiate the request and check whether data is written to the time series table. 
        // Write multiple rows of time series data at a time. 
        PutTimeseriesDataResponse putTimeseriesDataResponse = client.putTimeseriesData(putTimeseriesDataRequest);
        // Check whether all data is written to the time series table. 
        if (!putTimeseriesDataResponse.isAllSuccess()) {
            for (PutTimeseriesDataResponse.FailedRowResult failedRowResult : putTimeseriesDataResponse.getFailedRows()) {
                System.out.println(failedRowResult.getIndex());
                System.out.println(failedRowResult.getError());
            }
        }
    }
}

Step 3: Read data from the time series table

The following sample code provides an example on how to read data from a time series table and return the number of rows of data that meets the specified conditions. The data in the time series in which the measurement name is cpu and the tags include the host_0 tag is returned.

import com.alicloud.openservices.tablestore.TimeseriesClient;
import com.alicloud.openservices.tablestore.model.ColumnType;
import com.alicloud.openservices.tablestore.model.timeseries.GetTimeseriesDataRequest;
import com.alicloud.openservices.tablestore.model.timeseries.GetTimeseriesDataResponse;
import com.alicloud.openservices.tablestore.model.timeseries.TimeseriesKey;

import java.util.HashMap;
import java.util.Map;

public class GetTimeseriesData {
    public static void main(String[] args) {
       
        // Create and initialize a Tablestore client. 
        final String endPoint = "https://myinstance.cn-hangzhou.ots.aliyuncs.com";
        String accessKeyId = System.getenv("OTS_AK_ENV");
        String accessKeySecret = System.getenv("OTS_SK_ENV");
        final String instanceName = "myinstance";
        TimeseriesClient client = new TimeseriesClient(endPoint, accessKeyId, accessKeySecret, instanceName);
        
        // Create an API request and specify the request parameters. 
        String tableName = "<TABLE_NAME>";
        GetTimeseriesDataRequest getTimeseriesDataRequest = new GetTimeseriesDataRequest(tableName);
        Map<String, String> tags = new HashMap<String, String>();
        tags.put("region", "hangzhou");
        tags.put("os", "Ubuntu16.04");
        // Specify the measurement name, data source, and tags of a time series to construct the identifier of the time series. 
        TimeseriesKey timeseriesKey = new TimeseriesKey("cpu", "host_0", tags);
        getTimeseriesDataRequest.setTimeseriesKey(timeseriesKey);
        // Specify the time range. 
        getTimeseriesDataRequest.setTimeRange(0, (System.currentTimeMillis() + 60 * 1000) * 1000);
        // Specify the maximum number of rows that you want to return. 
        getTimeseriesDataRequest.setLimit(10);
        // Optional. Specify whether to sort the query results in reverse chronological order. Default value: false. If you set this parameter to true, the query results are sorted in reverse chronological order. 
        getTimeseriesDataRequest.setBackward(false);
        // Optional. Specify the columns that you want to return. If you do not specify this parameter, all columns are returned. 
        getTimeseriesDataRequest.addFieldToGet("cpu_sys", ColumnType.DOUBLE);
        getTimeseriesDataRequest.addFieldToGet("cpu_usage", ColumnType.DOUBLE);

        // Initiate the request and display the response. 
        GetTimeseriesDataResponse getTimeseriesDataResponse = client.getTimeseriesData(getTimeseriesDataRequest);
        System.out.println(getTimeseriesDataResponse.getRows().size());
        if (getTimeseriesDataResponse.getNextToken() != null) {
            // If the nextToken parameter is not empty, you can initiate another request to obtain the remaining data. 
            getTimeseriesDataRequest.setNextToken(getTimeseriesDataResponse.getNextToken());
            getTimeseriesDataResponse = client.getTimeseriesData(getTimeseriesDataRequest);
            System.out.println(getTimeseriesDataResponse.getRows().size());
        }
    }
}

References