All Products
Search
Document Center

Tablestore:Use the TimeSeries model by using Tablestore SDKs

Last Updated:Oct 10, 2024

When you use the TimeSeries model by using Tablestore SDKs, you must create a time series table to store time series data. Then, you can write time series data to the time series table and retrieve time series data.

Prerequisites

Usage notes

The TimeSeries model is supported in the following regions: China (Hangzhou), China (Shanghai), China (Beijing), China (Zhangjiakou), China (Ulanqab), China (Shenzhen), China (Hong Kong), Germany (Frankfurt), US (Virginia), SAU (Riyadh - Partner Region), and Singapore.

Use Tablestore SDKs

You can use the following Tablestore SDKs to get started with the TimeSeries model: In this topic, Tablestore SDK for Java is used.

Step 1: Create a time series table

Call the CreateTimeseriesTable operation to create a time series table to store time series data.

The following sample code provides an example on how to create a time series table named test_timeseries_table whose data never expires.

private static void createTimeseriesTable(TimeseriesClient client) {
    String tableName = "test_timeseries_table";
    TimeseriesTableMeta timeseriesTableMeta = new TimeseriesTableMeta(tableName);
    int timeToLive = -1;
    timeseriesTableMeta.setTimeseriesTableOptions(new TimeseriesTableOptions(timeToLive));
    CreateTimeseriesTableRequest request = new CreateTimeseriesTableRequest(timeseriesTableMeta);
    
    client.createTimeseriesTable(request);
}

Step 2: Write time series data

After you create a time series table, call the PutTimeseriesData operation to write multiple time series data records to the time series table at the same time.

The following sample code provides an example on how to write multiple rows of time series data to a time series table named test_timeseries_table:

private static void putTimeseriesData(TimeseriesClient client) {
    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 identifiers 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 = "test_timeseries_table";
    PutTimeseriesDataRequest putTimeseriesDataRequest = new PutTimeseriesDataRequest(tableName);
    putTimeseriesDataRequest.setRows(rows);
    // Write multiple rows of time series data at the same 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: Retrieve time series

If you are not sure about the information about the time series that you want to query, such as the metric name and data source, call the QueryTimeseriesMeta operation to specify conditions to retrieve the time series that meet the specified conditions.

The following sample code provides an example on how to query all time series whose metric name is cpu and that have the os tag whose value is prefixed with Ubuntu in a time series table.

private static void queryTimeseriesMeta(TimeseriesClient client) {
    // Specify the name of the time series table. 
    String tableName = "<TIME_SERIES_TABLE>";
    QueryTimeseriesMetaRequest queryTimeseriesMetaRequest = new QueryTimeseriesMetaRequest(tableName);
    // Query all time series whose metric name is cpu and that have the os tag whose value is prefixed with Ubuntu. measurement_name="cpu" and have_prefix(os, "Ubuntu") 
    CompositeMetaQueryCondition compositeMetaQueryCondition = new CompositeMetaQueryCondition(MetaQueryCompositeOperator.OP_AND);
    compositeMetaQueryCondition.addSubCondition(new MeasurementMetaQueryCondition(MetaQuerySingleOperator.OP_EQUAL, "cpu"));
    compositeMetaQueryCondition.addSubCondition(new TagMetaQueryCondition(MetaQuerySingleOperator.OP_PREFIX, "os", "Ubuntu"));
    queryTimeseriesMetaRequest.setCondition(compositeMetaQueryCondition);
    queryTimeseriesMetaRequest.setGetTotalHits(true);
    // Specify the maximum number of time series metadata entries that can be returned for a single request. 
    queryTimeseriesMetaRequest.setLimit(100);
    // Initiate the query. 
    QueryTimeseriesMetaResponse queryTimeseriesMetaResponse = client.queryTimeseriesMeta(queryTimeseriesMetaRequest);
    // Display the total number of time series that meet the query conditions. 
    System.out.println(queryTimeseriesMetaResponse.getTotalHits());

    // Save the request results. 
    List<TimeseriesMeta> timeseriesMetas = new ArrayList<TimeseriesMeta>();
    timeseriesMetas.addAll(queryTimeseriesMetaResponse.getTimeseriesMetas());

    // If NextToken is included in the response, you can initiate a new request to obtain the remaining results. 
    while (queryTimeseriesMetaResponse.getNextToken() != null) {
        queryTimeseriesMetaRequest.setNextToken(queryTimeseriesMetaResponse.getNextToken());
        queryTimeseriesMetaResponse = client.queryTimeseriesMeta(queryTimeseriesMetaRequest);
        timeseriesMetas.addAll(queryTimeseriesMetaResponse.getTimeseriesMetas());
        // Specify the maximum number of time series that can be returned. 
        if (timeseriesMetas.size() >= 1000) {
            break;
        }
    }

    System.out.println(timeseriesMetas.size());
    for (TimeseriesMeta timeseriesMeta : timeseriesMetas) {
        System.out.println(timeseriesMeta.getTimeseriesKey().getMeasurementName());
        System.out.println(timeseriesMeta.getTimeseriesKey().getDataSource());
        System.out.println(timeseriesMeta.getTimeseriesKey().getTags());
        System.out.println(timeseriesMeta.getAttributes());
        System.out.println(timeseriesMeta.getUpdateTimeInUs());
    }
}

Step 4: Query time series data

Call the GetTimeseriesData operation to query the time series data that meets the specified conditions in a time series.

The following sample code provides an example on how to query the time series data that meets the specified conditions in a time series table named test_timeseries_table:

private static void getTimeseriesData(TimeseriesClient client) {
    String tableName = "test_timeseries_table";
    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 identifiers 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("string_1", ColumnType.STRING);
    getTimeseriesDataRequest.addFieldToGet("long_1", ColumnType.INTEGER);

    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());
    }
}

FAQ

References

You can also get started with the TimeSeries model by using the Tablestore console or Tablestore CLI. For more information, see Use the TimeSeries model in the Tablestore console and Use the TimeSeries model in the Tablestore CLI.