Usage

Now, you are ready to start doing some awesome things with TsFile. This section demonstrates the detailed usages of TsFile.

Time-series Data

A time-series is considered as a sequence of quadruples. A quadruple is defined as (device, measurement, time, value).

  • measurement: A physical or formal measurement that a time-series is taking, e.g., the temperature of a city, the sales number of some goods or the speed of a train at different times. As a traditional sensor (like a thermometer) also takes a single measurement and produce a time-series, we will use measurement and sensor interchangeably below.

  • device: A device refers to an entity that is taking several measurements (producing multiple time-series), e.g., a running train monitors its speed, oil meter, miles it has run, current passengers each is conveyed to a time-series.

Table 1 illustrates a set of time-series data. The set showed in the following table contains one device named “device_1” with three measurements named “sensor_1”, “sensor_2” and “sensor_3”.

device_1
sensor_1sensor_2sensor_3
timevaluetimevaluetimevalue
11.2120250
31.4220451
51.1321652
71.8420853

A set of time-series data

One Line of Data: In many industrial applications, a device normally contains more than one sensor and these sensors may have values at a same timestamp, which is called one line of data.

Formally, one line of data consists of a device_id, a timestamp which indicates the milliseconds since January 1, 1970, 00:00:00, and several data pairs composed of measurement_id and corresponding value. All data pairs in one line belong to this device_id and have the same timestamp. If one of the measurements does not have a value in the timestamp, use a space instead(Actually, TsFile does not store null values). Its format is shown as follow:

  1. device_id, timestamp, <measurement_id, value>...

An example is illustrated as follow. In this example, the data type of two measurements are INT32, FLOAT respectively.

  1. device_1, 1490860659000, m1, 10, m2, 12.12

Writing TsFile

Generate a TsFile File.

A TsFile can be generated by following three steps and the complete code will be given in the section “Example for writing TsFile”.

  • First, construct a TsFileWriter instance.

    Here are the available constructors:

    • Without pre-defined schema
    1. public TsFileWriter(File file) throws IOException
    • With pre-defined schema
    1. public TsFileWriter(File file, FileSchema schema) throws IOException

    This one is for using the HDFS file system. TsFileOutput can be an instance of class HDFSOutput.

    1. public TsFileWriter(TsFileOutput output, FileSchema schema) throws IOException

    Parameters:

    • file : The TsFile to write

    • schema : The file schemas, will be introduced in next part.

  • Second, add measurements

    Or you can make an instance of class FileSchema first and pass this to the constructor of class TsFileWriter

    The class FileSchema contains a map whose key is the name of one measurement schema, and the value is the schema itself.

    Here are the interfaces:

    1. // Create an empty FileSchema or from an existing map
    2. public FileSchema()
    3. public FileSchema(Map<String, MeasurementSchema> measurements)
    4. // Use this two interfaces to add measurements
    5. public void registerMeasurement(MeasurementSchema descriptor)
    6. public void registerMeasurements(Map<String, MeasurementSchema> measurements)
    7. // Some useful getter and checker
    8. public TSDataType getMeasurementDataType(String measurementId)
    9. public MeasurementSchema getMeasurementSchema(String measurementId)
    10. public Map<String, MeasurementSchema> getAllMeasurementSchema()
    11. public boolean hasMeasurement(String measurementId)

    You can always use the following interface in TsFileWriter class to add additional measurements: ​

    1. public void addMeasurement(MeasurementSchema measurementSchema) throws WriteProcessException

    The class MeasurementSchema contains the information of one measurement, there are several constructors:

    1. public MeasurementSchema(String measurementId, TSDataType type, TSEncoding encoding)
    2. public MeasurementSchema(String measurementId, TSDataType type, TSEncoding encoding, CompressionType compressionType)
    3. public MeasurementSchema(String measurementId, TSDataType type, TSEncoding encoding, CompressionType compressionType,
    4. Map<String, String> props)

    Parameters:

    • measurementID: The name of this measurement, typically the name of the sensor.

    • type: The data type, now support six types: BOOLEAN, INT32, INT64, FLOAT, DOUBLE, TEXT;

    • encoding: The data encoding. See Chapter 2-3.

    • compression: The data compression. Now supports UNCOMPRESSED and SNAPPY.

    • props: Properties for special data types.Such as max_point_number for FLOAT and DOUBLE, max_string_length for TEXT. Use as string pairs into a map such as (“max_point_number”, “3”).

  1. > **Notice:** Although one measurement name can be used in multiple deltaObjects, the properties cannot be changed. I.e. it's not allowed to add one measurement name for multiple times with different type or encoding. ​ Here is a bad example:
  2. ```
  3. // The measurement "sensor_1" is float type
  4. addMeasurement(new MeasurementSchema("sensor_1", TSDataType.FLOAT, TSEncoding.RLE));
  5. // This call will throw a WriteProcessException exception
  6. addMeasurement(new MeasurementSchema("sensor_1", TSDataType.INT32, TSEncoding.RLE));
  7. ```
  • Third, insert and write data continually.

    Use this interface to create a new TSRecord(a timestamp and device pair).

    1. public TSRecord(long timestamp, String deviceId)

    Then create a DataPoint(a measurement and value pair), and use the addTuple method to add the DataPoint to the correct TsRecord.

    Use this method to write

    1. public void write(TSRecord record) throws IOException, WriteProcessException
  • Finally, call close to finish this writing process.

    1. public void close() throws IOException

Example for writing a TsFile

You should install TsFile to your local maven repository.

  1. mvn clean install -pl tsfile -am -DskipTests

A more thorough example can be found at /tsfile/example/src/main/java/org/apache/iotdb/tsfile/TsFileWrite.java

  1. package org.apache.iotdb.tsfile;
  2. import java.io.File;
  3. import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
  4. import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding;
  5. import org.apache.iotdb.tsfile.write.TsFileWriter;
  6. import org.apache.iotdb.tsfile.write.record.TSRecord;
  7. import org.apache.iotdb.tsfile.write.record.datapoint.DataPoint;
  8. import org.apache.iotdb.tsfile.write.record.datapoint.FloatDataPoint;
  9. import org.apache.iotdb.tsfile.write.record.datapoint.IntDataPoint;
  10. import org.apache.iotdb.tsfile.write.schema.MeasurementSchema;
  11. /**
  12. * An example of writing data to TsFile
  13. * It uses the interface:
  14. * public void addMeasurement(MeasurementSchema MeasurementSchema) throws WriteProcessException
  15. */
  16. public class TsFileWrite {
  17. public static void main(String args[]) {
  18. try {
  19. String path = "test.tsfile";
  20. File f = new File(path);
  21. if (f.exists()) {
  22. f.delete();
  23. }
  24. TsFileWriter tsFileWriter = new TsFileWriter(f);
  25. // add measurements into file schema
  26. tsFileWriter
  27. .addMeasurement(new MeasurementSchema("sensor_1", TSDataType.INT64, TSEncoding.RLE));
  28. tsFileWriter
  29. .addMeasurement(new MeasurementSchema("sensor_2", TSDataType.INT64, TSEncoding.RLE));
  30. tsFileWriter
  31. .addMeasurement(new MeasurementSchema("sensor_3", TSDataType.INT64, TSEncoding.RLE));
  32. // construct TSRecord
  33. TSRecord tsRecord = new TSRecord(1, "device_1");
  34. DataPoint dPoint1 = new LongDataPoint("sensor_1", 1);
  35. DataPoint dPoint2 = new LongDataPoint("sensor_2", 2);
  36. DataPoint dPoint3 = new LongDataPoint("sensor_3", 3);
  37. tsRecord.addTuple(dPoint1);
  38. tsRecord.addTuple(dPoint2);
  39. tsRecord.addTuple(dPoint3);
  40. // write TSRecord
  41. tsFileWriter.write(tsRecord);
  42. // close TsFile
  43. tsFileWriter.close();
  44. } catch (Throwable e) {
  45. e.printStackTrace();
  46. System.out.println(e.getMessage());
  47. }
  48. }
  49. }

Interface for Reading TsFile

Before the Start

The set of time-series data in section “Time-series Data” is used here for a concrete introduction in this section. The set showed in the following table contains one deltaObject named “device_1” with three measurements named “sensor_1”, “sensor_2” and “sensor_3”. And the measurements has been simplified to do a simple illustration, which contains only 4 time-value pairs each.

RelationshipDescription
TimeFilter.eq(value)Choose the time equal to the value
TimeFilter.lt(value)Choose the time less than the value
TimeFilter.gt(value)Choose the time greater than the value
TimeFilter.ltEq(value)Choose the time less than or equal to the value
TimeFilter.gtEq(value)Choose the time greater than or equal to the value
TimeFilter.notEq(value)Choose the time not equal to the value
TimeFilter.not(TimeFilter)Choose the time not satisfy another TimeFilter

Definition of Path

A path is a dot-separated string which uniquely identifies a time-series in TsFile, e.g., “root.area_1.device_1.sensor_1”. The last section “sensor_1” is called “measurementId” while the remaining parts “root.area_1.device_1” is called deviceId. As mentioned above, the same measurement in different devices has the same data type and encoding, and devices are also unique.

In read interfaces, The parameter paths indicates the measurements to be selected.

Path instance can be easily constructed through the class Path. For example:

  1. Path p = new Path("device_1.sensor_1");

We will pass an ArrayList of paths for final query call to support multiple paths.

  1. List<Path> paths = new ArrayList<Path>();
  2. paths.add(new Path("device_1.sensor_1"));
  3. paths.add(new Path("device_1.sensor_3"));

Notice: When constructing a Path, the format of the parameter should be a dot-separated string, the last part will be recognized as measurementId while the remaining parts will be recognized as deviceId.

Definition of Filter

Usage Scenario

Filter is used in TsFile reading process to select data satisfying one or more given condition(s).

IExpression

The IExpression is a filter expression interface and it will be passed to our final query call. We create one or more filter expressions and may use binary filter operators to link them to our final expression.

  • Create a Filter Expression

    There are two types of filters.

    • TimeFilter: A filter for time in time-series data.

      1. IExpression timeFilterExpr = new GlobalTimeExpression(TimeFilter);
  1. ```
  2. Use the following relationships to get a `TimeFilter` object (value is a long int variable).
  3. | Relationship | Description |
  4. | :------------------------: | :------------------------------------------------: |
  5. | TimeFilter.eq(value) | Choose the time equal to the value |
  6. | TimeFilter.lt(value) | Choose the time less than the value |
  7. | TimeFilter.gt(value) | Choose the time greater than the value |
  8. | TimeFilter.ltEq(value) | Choose the time less than or equal to the value |
  9. | TimeFilter.gtEq(value) | Choose the time greater than or equal to the value |
  10. | TimeFilter.notEq(value) | Choose the time not equal to the value |
  11. | TimeFilter.not(TimeFilter) | Choose the time not satisfy another TimeFilter |
  12. * ValueFilter: A filter for `value` in time-series data.
  13. ```
  14. IExpression valueFilterExpr = new SingleSeriesExpression(Path, ValueFilter);
  15. ```
  16. ​ The usage of `ValueFilter` is the same as using `TimeFilter`, just to make sure that the type of the value
  17. ​ equal to the measurement's(defined in the path).
  18. ```
  • Binary Filter Operators

    Binary filter operators can be used to link two single expressions.

    • BinaryExpression.and(Expression, Expression): Choose the value satisfy for both expressions.
    • BinaryExpression.or(Expression, Expression): Choose the value satisfy for at least one expression.
Filter Expression Examples
  • TimeFilterExpression Examples

    1. IExpression timeFilterExpr = new GlobalTimeExpression(TimeFilter.eq(15)); // series time = 15
    1. IExpression timeFilterExpr = new GlobalTimeExpression(TimeFilter.ltEq(15)); // series time <= 15
    1. IExpression timeFilterExpr = new GlobalTimeExpression(TimeFilter.lt(15)); // series time < 15
    1. IExpression timeFilterExpr = new GlobalTimeExpression(TimeFilter.gtEq(15)); // series time >= 15
    1. IExpression timeFilterExpr = new GlobalTimeExpression(TimeFilter.notEq(15)); // series time != 15
    1. IExpression timeFilterExpr = BinaryExpression.and(new GlobalTimeExpression(TimeFilter.gtEq(15L)),
    2. new GlobalTimeExpression(TimeFilter.lt(25L))); // 15 <= series time < 25
    1. IExpression timeFilterExpr = BinaryExpression.or(new GlobalTimeExpression(TimeFilter.gtEq(15L)),
    2. new GlobalTimeExpression(TimeFilter.lt(25L))); // series time >= 15 or series time < 25

Read Interface

First, we open the TsFile and get a ReadOnlyTsFile instance from a file path string path.

  1. TsFileSequenceReader reader = new TsFileSequenceReader(path);
  2. ReadOnlyTsFile readTsFile = new ReadOnlyTsFile(reader);

Next, we prepare the path array and query expression, then get final QueryExpression object by this interface:

  1. QueryExpression queryExpression = QueryExpression.create(paths, statement);

The ReadOnlyTsFile class has two query method to perform a query.

  • Method 1

    1. public QueryDataSet query(QueryExpression queryExpression) throws IOException
  • Method 2

    1. public QueryDataSet query(QueryExpression queryExpression, long partitionStartOffset, long partitionEndOffset) throws IOException

    This method is designed for advanced applications such as the TsFile-Spark Connector.

    • params : For method 2, two additional parameters are added to support partial query:

      • partitionStartOffset: start offset for a TsFile
      • partitionEndOffset: end offset for a TsFile

      What is Partial Query ?

      In some distributed file systems(e.g. HDFS), a file is split into severval parts which are called “Blocks” and stored in different nodes. Executing a query paralleled in each nodes involved makes better efficiency. Thus Partial Query is needed. Paritial Query only selects the results stored in the part split by QueryConstant.PARTITION_START_OFFSET and QueryConstant.PARTITION_END_OFFSET for a TsFile.

QueryDataset Interface

The query performed above will return a QueryDataset object.

Here’s the useful interfaces for user.

  • bool hasNext();

    Return true if this dataset still has elements.

  • List<Path> getPaths()

    Get the paths in this data set.

  • List<TSDataType> getDataTypes();

    Get the data types. The class TSDataType is an enum class, the value will be one of the following:

    1. BOOLEAN,
    2. INT32,
    3. INT64,
    4. FLOAT,
    5. DOUBLE,
    6. TEXT;
  • RowRecord next() throws IOException;

    Get the next record.

    The class RowRecord consists of a long timestamp and a List<Field> for data in different sensors, we can use two getter methods to get them.

    1. long getTimestamp();
    2. List<Field> getFields();

    To get data from one Field, use these methods:

    1. TSDataType getDataType();
    2. Object getObjectValue();

Example for reading an existing TsFile

You should install TsFile to your local maven repository.

  1. mvn clean install -pl tsfile -am -DskipTests

A more thorough example with query statement can be found at /tsfile/example/src/main/java/org/apache/iotdb/tsfile/TsFileRead.java

  1. package org.apache.iotdb.tsfile;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import org.apache.iotdb.tsfile.read.ReadOnlyTsFile;
  5. import org.apache.iotdb.tsfile.read.TsFileSequenceReader;
  6. import org.apache.iotdb.tsfile.read.common.Path;
  7. import org.apache.iotdb.tsfile.read.expression.IExpression;
  8. import org.apache.iotdb.tsfile.read.expression.QueryExpression;
  9. import org.apache.iotdb.tsfile.read.expression.impl.BinaryExpression;
  10. import org.apache.iotdb.tsfile.read.expression.impl.GlobalTimeExpression;
  11. import org.apache.iotdb.tsfile.read.expression.impl.SingleSeriesExpression;
  12. import org.apache.iotdb.tsfile.read.filter.TimeFilter;
  13. import org.apache.iotdb.tsfile.read.filter.ValueFilter;
  14. import org.apache.iotdb.tsfile.read.query.dataset.QueryDataSet;
  15. /**
  16. * The class is to show how to read TsFile file named "test.tsfile".
  17. * The TsFile file "test.tsfile" is generated from class TsFileWrite.
  18. * Run TsFileWrite to generate the test.tsfile first
  19. */
  20. public class TsFileRead {
  21. private static void queryAndPrint(ArrayList<Path> paths, ReadOnlyTsFile readTsFile, IExpression statement)
  22. throws IOException {
  23. QueryExpression queryExpression = QueryExpression.create(paths, statement);
  24. QueryDataSet queryDataSet = readTsFile.query(queryExpression);
  25. while (queryDataSet.hasNext()) {
  26. System.out.println(queryDataSet.next());
  27. }
  28. System.out.println("------------");
  29. }
  30. public static void main(String[] args) throws IOException {
  31. // file path
  32. String path = "test.tsfile";
  33. // create reader and get the readTsFile interface
  34. TsFileSequenceReader reader = new TsFileSequenceReader(path);
  35. ReadOnlyTsFile readTsFile = new ReadOnlyTsFile(reader);
  36. // use these paths(all sensors) for all the queries
  37. ArrayList<Path> paths = new ArrayList<>();
  38. paths.add(new Path("device_1.sensor_1"));
  39. paths.add(new Path("device_1.sensor_2"));
  40. paths.add(new Path("device_1.sensor_3"));
  41. // no query statement
  42. queryAndPrint(paths, readTsFile, null);
  43. //close the reader when you left
  44. reader.close();
  45. }
  46. }

User-specified config file path

Default config file tsfile-format.properties.template is located at /tsfile/src/main/resources directory. If you want to use your own path, you can:

  1. System.setProperty(TsFileConstant.TSFILE_CONF, "your config file path");

and then call:

  1. TSFileConfig config = TSFileDescriptor.getInstance().getConfig();