Java Native API

Installation

Dependencies

  • JDK >= 1.8
  • Maven >= 3.6

How to install

In root directory:

mvn clean install -pl iotdb-client/session -am -DskipTests

Using IoTDB Java Native API with Maven

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.apache.iotdb</groupId>
  4. <artifactId>iotdb-session</artifactId>
  5. <version>1.0.0</version>
  6. </dependency>
  7. </dependencies>

Syntax Convention

  • IoTDB-SQL interface: The input SQL parameter needs to conform to the syntax conventions and be escaped for JAVA strings. For example, you need to add a backslash before the double-quotes. (That is: after JAVA escaping, it is consistent with the SQL statement executed on the command line.)
  • Other interfaces:
    • The node names in path or path prefix as parameter: The node names which should be escaped by backticks (`) in the SQL statement, escaping is required here.
    • Identifiers (such as template names) as parameters: The identifiers which should be escaped by backticks (`) in the SQL statement, and escaping is not required here.
  • Code example for syntax convention could be found at: example/session/src/main/java/org/apache/iotdb/SyntaxConventionRelatedExample.java

Native APIs

Here we show the commonly used interfaces and their parameters in the Native API:

Initialization

  • Initialize a Session
  1. // use default configuration
  2. session = new Session.Builder.build();
  3. // initialize with a single node
  4. session =
  5. new Session.Builder()
  6. .host(String host)
  7. .port(int port)
  8. .build();
  9. // initialize with multiple nodes
  10. session =
  11. new Session.Builder()
  12. .nodeUrls(List<String> nodeUrls)
  13. .build();
  14. // other configurations
  15. session =
  16. new Session.Builder()
  17. .fetchSize(int fetchSize)
  18. .username(String username)
  19. .password(String password)
  20. .thriftDefaultBufferSize(int thriftDefaultBufferSize)
  21. .thriftMaxFrameSize(int thriftMaxFrameSize)
  22. .enableRedirection(boolean enableRedirection)
  23. .version(Version version)
  24. .build();

Version represents the SQL semantic version used by the client, which is used to be compatible with the SQL semantics of 0.12 when upgrading 0.13. The possible values are: V_0_12, V_0_13, V_1_0.

  • Open a Session
  1. void open()
  • Open a session, with a parameter to specify whether to enable RPC compression
  1. void open(boolean enableRPCCompression)

Notice: this RPC compression status of client must comply with that of IoTDB server

  • Close a Session
  1. void close()

Data Definition Interface (DDL Interface)

Database Management

  • CREATE DATABASE
  1. void setStorageGroup(String storageGroupId)
  • Delete one or several databases
  1. void deleteStorageGroup(String storageGroup)
  2. void deleteStorageGroups(List<String> storageGroups)

Timeseries Management

  • Create one or multiple timeseries
  1. void createTimeseries(String path, TSDataType dataType,
  2. TSEncoding encoding, CompressionType compressor, Map<String, String> props,
  3. Map<String, String> tags, Map<String, String> attributes, String measurementAlias)
  4. void createMultiTimeseries(List<String> paths, List<TSDataType> dataTypes,
  5. List<TSEncoding> encodings, List<CompressionType> compressors,
  6. List<Map<String, String>> propsList, List<Map<String, String>> tagsList,
  7. List<Map<String, String>> attributesList, List<String> measurementAliasList)
  • Create aligned timeseries
  1. void createAlignedTimeseries(String prefixPath, List<String> measurements,
  2. List<TSDataType> dataTypes, List<TSEncoding> encodings,
  3. List <CompressionType> compressors, List<String> measurementAliasList);

Attention: Alias of measurements are not supported currently.

  • Delete one or several timeseries
  1. void deleteTimeseries(String path)
  2. void deleteTimeseries(List<String> paths)
  • Check whether the specific timeseries exists.
  1. boolean checkTimeseriesExists(String path)

Schema Template

Create a schema template for massive identical devices will help to improve memory performance. You can use Template, InternalNode and MeasurementNode to depict the structure of the template, and use belowed interface to create it inside session.

  1. public void createSchemaTemplate(Template template);
  2. Class Template {
  3. private String name;
  4. private boolean directShareTime;
  5. Map<String, Node> children;
  6. public Template(String name, boolean isShareTime);
  7. public void addToTemplate(Node node);
  8. public void deleteFromTemplate(String name);
  9. public void setShareTime(boolean shareTime);
  10. }
  11. Abstract Class Node {
  12. private String name;
  13. public void addChild(Node node);
  14. public void deleteChild(Node node);
  15. }
  16. Class MeasurementNode extends Node {
  17. TSDataType dataType;
  18. TSEncoding encoding;
  19. CompressionType compressor;
  20. public MeasurementNode(String name,
  21. TSDataType dataType,
  22. TSEncoding encoding,
  23. CompressionType compressor);
  24. }

We strongly suggest you implement templates only with flat-measurement (like object ‘flatTemplate’ in belowed snippet), since tree-structured template may not be a long-term supported feature in further version of IoTDB.

A snippet of using above Method and Class:

  1. MeasurementNode nodeX = new MeasurementNode("x", TSDataType.FLOAT, TSEncoding.RLE, CompressionType.SNAPPY);
  2. MeasurementNode nodeY = new MeasurementNode("y", TSDataType.FLOAT, TSEncoding.RLE, CompressionType.SNAPPY);
  3. MeasurementNode nodeSpeed = new MeasurementNode("speed", TSDataType.DOUBLE, TSEncoding.GORILLA, CompressionType.SNAPPY);
  4. // This is the template we suggest to implement
  5. Template flatTemplate = new Template("flatTemplate");
  6. template.addToTemplate(nodeX);
  7. template.addToTemplate(nodeY);
  8. template.addToTemplate(nodeSpeed);
  9. createSchemaTemplate(flatTemplate);

You can query measurement inside templates with these APIS:

  1. // Return the amount of measurements inside a template
  2. public int countMeasurementsInTemplate(String templateName);
  3. // Return true if path points to a measurement, otherwise returne false
  4. public boolean isMeasurementInTemplate(String templateName, String path);
  5. // Return true if path exists in template, otherwise return false
  6. public boolean isPathExistInTemplate(String templateName, String path);
  7. // Return all measurements paths inside template
  8. public List<String> showMeasurementsInTemplate(String templateName);
  9. // Return all measurements paths under the designated patter inside template
  10. public List<String> showMeasurementsInTemplate(String templateName, String pattern);

To implement schema template, you can set the measurement template named ‘templateName’ at path ‘prefixPath’.

Please notice that, we strongly recommend not setting templates on the nodes above the database to accommodate future updates and collaboration between modules.

  1. void setSchemaTemplate(String templateName, String prefixPath)

Before setting template, you should firstly create the template using

  1. void createSchemaTemplate(Template template)

After setting template to a certain path, you can use the template to create timeseries on given device paths through the following interface, or you can write data directly to trigger timeseries auto creation using schema template under target devices.

  1. void createTimeseriesUsingSchemaTemplate(List<String> devicePathList)

After setting template to a certain path, you can query for info about template using belowed interface in session:

  1. /** @return All template names. */
  2. public List<String> showAllTemplates();
  3. /** @return All paths have been set to designated template. */
  4. public List<String> showPathsTemplateSetOn(String templateName);
  5. /** @return All paths are using designated template. */
  6. public List<String> showPathsTemplateUsingOn(String templateName)

If you are ready to get rid of schema template, you can drop it with belowed interface. Make sure the template to drop has been unset from MTree.

  1. void unsetSchemaTemplate(String prefixPath, String templateName);
  2. public void dropSchemaTemplate(String templateName);

Unset the measurement template named ‘templateName’ from path ‘prefixPath’. When you issue this interface, you should assure that there is a template named ‘templateName’ set at the path ‘prefixPath’.

Attention: Unsetting the template named ‘templateName’ from node at path ‘prefixPath’ or descendant nodes which have already inserted records using template is not supported.

Data Manipulation Interface (DML Interface)

Insert

It is recommended to use insertTablet to help improve write efficiency.

  • Insert a Tablet,which is multiple rows of a device, each row has the same measurements
    • Better Write Performance
    • Support batch write
    • Support null values: fill the null value with any value, and then mark the null value via BitMap
  1. void insertTablet(Tablet tablet)
  2. public class Tablet {
  3. /** deviceId of this tablet */
  4. public String prefixPath;
  5. /** the list of measurement schemas for creating the tablet */
  6. private List<MeasurementSchema> schemas;
  7. /** timestamps in this tablet */
  8. public long[] timestamps;
  9. /** each object is a primitive type array, which represents values of one measurement */
  10. public Object[] values;
  11. /** each bitmap represents the existence of each value in the current column. */
  12. public BitMap[] bitMaps;
  13. /** the number of rows to include in this tablet */
  14. public int rowSize;
  15. /** the maximum number of rows for this tablet */
  16. private int maxRowNumber;
  17. /** whether this tablet store data of aligned timeseries or not */
  18. private boolean isAligned;
  19. }
  • Insert multiple Tablets
  1. void insertTablets(Map<String, Tablet> tablet)
  • Insert a Record, which contains multiple measurement value of a device at a timestamp. This method is equivalent to providing a common interface for multiple data types of values. Later, the value can be cast to the original type through TSDataType.

    The correspondence between the Object type and the TSDataType type is shown in the following table.

    TSDataTypeObject
    BOOLEANBoolean
    INT32Integer
    INT64Long
    FLOATFloat
    DOUBLEDouble
    TEXTString, Binary
  1. void insertRecord(String deviceId, long time, List<String> measurements,
  2. List<TSDataType> types, List<Object> values)
  • Insert multiple Records
  1. void insertRecords(List<String> deviceIds, List<Long> times,
  2. List<List<String>> measurementsList, List<List<TSDataType>> typesList,
  3. List<List<Object>> valuesList)
  • Insert multiple Records that belong to the same device.
    With type info the server has no need to do type inference, which leads a better performance
  1. void insertRecordsOfOneDevice(String deviceId, List<Long> times,
  2. List<List<String>> measurementsList, List<List<TSDataType>> typesList,
  3. List<List<Object>> valuesList)

Insert with type inference

When the data is of String type, we can use the following interface to perform type inference based on the value of the value itself. For example, if value is “true” , it can be automatically inferred to be a boolean type. If value is “3.2” , it can be automatically inferred as a flout type. Without type information, server has to do type inference, which may cost some time.

  • Insert a Record, which contains multiple measurement value of a device at a timestamp
  1. void insertRecord(String prefixPath, long time, List<String> measurements, List<String> values)
  • Insert multiple Records
  1. void insertRecords(List<String> deviceIds, List<Long> times,
  2. List<List<String>> measurementsList, List<List<String>> valuesList)
  • Insert multiple Records that belong to the same device.
  1. void insertStringRecordsOfOneDevice(String deviceId, List<Long> times,
  2. List<List<String>> measurementsList, List<List<String>> valuesList)

Insert of Aligned Timeseries

The Insert of aligned timeseries uses interfaces like insertAlignedXXX, and others are similar to the above interfaces:

  • insertAlignedRecord
  • insertAlignedRecords
  • insertAlignedRecordsOfOneDevice
  • insertAlignedStringRecordsOfOneDevice
  • insertAlignedTablet
  • insertAlignedTablets

Delete

  • Delete data before or equal to a timestamp of one or several timeseries
  1. void deleteData(String path, long time)
  2. void deleteData(List<String> paths, long time)

Query

  • Time-series raw data query with time range:
    • The specified query time range is a left-closed right-open interval, including the start time but excluding the end time.
  1. SessionDataSet executeRawDataQuery(List<String> paths, long startTime, long endTime);
  • Last query:

    • Query the last data, whose timestamp is greater than or equal LastTime.

      1. SessionDataSet executeLastDataQuery(List<String> paths, long LastTime);
    • Query the latest point of the specified series of single device quickly, and support redirection;
      If you are sure that the query path is valid, set ‘isLegalPathNodes’ to true to avoid performance penalties from path verification.

      1. SessionDataSet executeLastDataQueryForOneDevice(
      2. String db, String device, List<String> sensors, boolean isLegalPathNodes);
  • Aggregation query:

    • Support specified query time range: The specified query time range is a left-closed right-open interval, including the start time but not the end time.
    • Support GROUP BY TIME.
  1. SessionDataSet executeAggregationQuery(List<String> paths, List<Aggregation> aggregations);
  2. SessionDataSet executeAggregationQuery(
  3. List<String> paths, List<Aggregation> aggregations, long startTime, long endTime);
  4. SessionDataSet executeAggregationQuery(
  5. List<String> paths,
  6. List<Aggregation> aggregations,
  7. long startTime,
  8. long endTime,
  9. long interval);
  10. SessionDataSet executeAggregationQuery(
  11. List<String> paths,
  12. List<Aggregation> aggregations,
  13. long startTime,
  14. long endTime,
  15. long interval,
  16. long slidingStep);

IoTDB-SQL Interface

  • Execute query statement
  1. SessionDataSet executeQueryStatement(String sql)
  • Execute non query statement
  1. void executeNonQueryStatement(String sql)

Write Test Interface (to profile network cost)

These methods don’t insert data into database and server just return after accept the request.

  • Test the network and client cost of insertRecord
  1. void testInsertRecord(String deviceId, long time, List<String> measurements, List<String> values)
  2. void testInsertRecord(String deviceId, long time, List<String> measurements,
  3. List<TSDataType> types, List<Object> values)
  • Test the network and client cost of insertRecords
  1. void testInsertRecords(List<String> deviceIds, List<Long> times,
  2. List<List<String>> measurementsList, List<List<String>> valuesList)
  3. void testInsertRecords(List<String> deviceIds, List<Long> times,
  4. List<List<String>> measurementsList, List<List<TSDataType>> typesList
  5. List<List<Object>> valuesList)
  • Test the network and client cost of insertTablet
  1. void testInsertTablet(Tablet tablet)
  • Test the network and client cost of insertTablets
  1. void testInsertTablets(Map<String, Tablet> tablets)

Coding Examples

To get more information of the following interfaces, please view session/src/main/java/org/apache/iotdb/session/Session.java

The sample code of using these interfaces is in example/session/src/main/java/org/apache/iotdb/SessionExample.java,which provides an example of how to open an IoTDB session, execute a batch insertion.

For examples of aligned timeseries and measurement template, you can refer to example/session/src/main/java/org/apache/iotdb/AlignedTimeseriesSessionExample.java

Session Pool for Native API

We provide a connection pool (`SessionPool) for Native API.
Using the interface, you need to define the pool size.

If you can not get a session connection in 60 seconds, there is a warning log but the program will hang.

If a session has finished an operation, it will be put back to the pool automatically.
If a session connection is broken, the session will be removed automatically and the pool will try
to create a new session and redo the operation.
You can also specify an url list of multiple reachable nodes when creating a SessionPool, just as you would when creating a Session. To ensure high availability of clients in distributed cluster.

For query operations:

  1. When using SessionPool to query data, the result set is SessionDataSetWrapper;
  2. Given a SessionDataSetWrapper, if you have not scanned all the data in it and stop to use it,
    you have to call SessionPool.closeResultSet(wrapper) manually;
  3. When you call hasNext() and next() of a SessionDataSetWrapper and there is an exception, then
    you have to call SessionPool.closeResultSet(wrapper) manually;
  4. You can call getColumnNames() of SessionDataSetWrapper to get the column names of query result;

Examples: session/src/test/java/org/apache/iotdb/session/pool/SessionPoolTest.java

Or example/session/src/main/java/org/apache/iotdb/SessionPoolExample.java

Cluster information related APIs allow users get the cluster info like where a database will be
partitioned to, the status of each node in the cluster.

To use the APIs, add dependency in your pom file:

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.apache.iotdb</groupId>
  4. <artifactId>iotdb-thrift-cluster</artifactId>
  5. <version>1.0.0</version>
  6. </dependency>
  7. </dependencies>

How to open a connection:

  1. import org.apache.thrift.protocol.TBinaryProtocol;
  2. import org.apache.thrift.transport.TSocket;
  3. import org.apache.thrift.transport.TTransport;
  4. import org.apache.thrift.transport.TTransportException;
  5. import org.apache.iotdb.rpc.RpcTransportFactory;
  6. public class CluserInfoClient {
  7. TTransport transport;
  8. ClusterInfoService.Client client;
  9. public void connect() {
  10. transport =
  11. RpcTransportFactory.INSTANCE.getTransport(
  12. new TSocket(
  13. // the RPC address
  14. IoTDBDescriptor.getInstance().getConfig().getRpcAddress(),
  15. // the RPC port
  16. ClusterDescriptor.getInstance().getConfig().getClusterRpcPort()));
  17. try {
  18. transport.open();
  19. } catch (TTransportException e) {
  20. Assert.fail(e.getMessage());
  21. }
  22. //get the client
  23. client = new ClusterInfoService.Client(new TBinaryProtocol(transport));
  24. }
  25. public void close() {
  26. transport.close();
  27. }
  28. }

APIs in ClusterInfoService.Client:

  • Get the physical hash ring of the cluster:
  1. list<Node> getRing();
  • Get data partition information of input path and time range:
  1. /**
  2. * @param path input path (should contains a database name as its prefix)
  3. * @return the data partition info. If the time range only covers one data partition, the the size
  4. * of the list is one.
  5. */
  6. list<DataPartitionEntry> getDataPartition(1:string path, 2:long startTime, 3:long endTime);
  • Get metadata partition information of input path:
  1. /**
  2. * @param path input path (should contains a database name as its prefix)
  3. * @return metadata partition information
  4. */
  5. list<Node> getMetaPartition(1:string path);
  • Get the status (alive or not) of all nodes:
  1. /**
  2. * @return key: node, value: live or not
  3. */
  4. map<Node, bool> getAllNodeStatus();
  • get the raft group info (voteFor, term, etc..) of the connected node
    (Notice that this API is rarely used by users):
  1. /**
  2. * @return A multi-line string with each line representing the total time consumption, invocation
  3. * number, and average time consumption.
  4. */
  5. string getInstrumentingInfo();