From 00bb746441a23e36c4b902ce60daa56be647a4a4 Mon Sep 17 00:00:00 2001 From: Zhijia Cao Date: Tue, 17 Dec 2024 17:26:46 +0800 Subject: [PATCH] solve conflict --- .../latest/API/Programming-Java-Native-API.md | 1402 +++++++++++------ .../latest/API/Programming-Java-Native-API.md | 1335 ++++++++++------ 2 files changed, 1746 insertions(+), 991 deletions(-) diff --git a/src/UserGuide/latest/API/Programming-Java-Native-API.md b/src/UserGuide/latest/API/Programming-Java-Native-API.md index 6061d473..8a819ca1 100644 --- a/src/UserGuide/latest/API/Programming-Java-Native-API.md +++ b/src/UserGuide/latest/API/Programming-Java-Native-API.md @@ -1,499 +1,914 @@ # Java Native API -## Installation +## Overview +Session in IoTDB's native API is the core interface to interact with the database. It integrates rich methods and supports functions such as data writing, query and metadata operation. By instantiating a Session, you can establish a connection to the IoTDB server and perform various database operations in the environment built by that connection. +In addition, IoTDB also provides a Session Pool, which is a pooling form of a Session and is optimized specifically for multi-threaded concurrency scenarios. In the case of multi-threaded concurrency, the Session Pool can reasonably manage and allocate connection resources. To improve system performance and resource utilization efficiency. Session and Session Pool are the same in terms of functions and methods, both of which provide strong support for developers to interact with the IoTDB database in different scenarios, and developers can flexibly select them according to actual requirements. + +## Step Overview +Core steps to use Session: +1. Create a Session instance: Initialize a session object to prepare for interaction with the IoTDB server. +2. Open the connection: Establish the connection with the IoTDB server through the Session instance. +3. Perform operations: Write data, query data, or manage metadata on the established connection. +4. Close the connection: After the operation is complete, close the connection with the IoTDB server to release resources. + -### Dependencies +Core steps for using SessionPool: +1. Create a Session pool instance: Initialize a SessionPool object to manage multiple session instances. +2. Perform operations: Directly obtain Session instances from the SessionPool and perform database operations without opening and closing connections each time. +3. Close SessionPool resources: If no database operation is required, close the session pool to release all related resources. -- JDK >= 1.8 -- Maven >= 3.6 +## Detailed steps +This chapter describes the core development process and does not demonstrate all parameters and interfaces. For all functions and parameters, please refer to: [Detailed Interface Description](./Programming-Java-Native-API.md#Detailed interface description) or visit: [Source Code](https://github.com/apache/iotdb/tree/master/example/session/src/main/java/org/apache/iotdb) -### Using IoTDB Java Native API with Maven +### 1. Create the maven project +Create a maven project and import the following dependencies (JDK >= 1.8, Maven >= 3.6) ```xml org.apache.iotdb iotdb-session - 1.0.0 + + ${project.version} ``` - -## Syntax Convention - -- **IoTDB-SQL interface:** The input SQL parameter needs to conform to the [syntax conventions](../User-Manual/Syntax-Rule.md#Literal-Values) 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: - -### Session Management - -- Initialize a Session - -```java -// use default configuration -session = new Session.Builder.build(); - -// initialize with a single node -session = - new Session.Builder() - .host(String host) - .port(int port) - .build(); - -// initialize with multiple nodes -session = - new Session.Builder() - .nodeUrls(List nodeUrls) - .build(); - -// other configurations -session = - new Session.Builder() - .fetchSize(int fetchSize) - .username(String username) - .password(String password) - .thriftDefaultBufferSize(int thriftDefaultBufferSize) - .thriftMaxFrameSize(int thriftMaxFrameSize) - .enableRedirection(boolean enableRedirection) - .version(Version version) - .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`, etc. - -- Open a Session - -```java -void open() -``` - -- Open a session, with a parameter to specify whether to enable RPC compression - -```java -void open(boolean enableRPCCompression) -``` - -Notice: this RPC compression status of client must comply with that of IoTDB server - -- Close a Session - -```java -void close() -``` - -- SessionPool - -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` - -### Database & Timeseries Management API - -#### Database Management - -- CREATE DATABASE - -```java -void setStorageGroup(String storageGroupId) -``` - -- Delete one or several databases - -```java -void deleteStorageGroup(String storageGroup) -void deleteStorageGroups(List storageGroups) -``` - -#### Timeseries Management - -- Create one or multiple timeseries - -```java -void createTimeseries(String path, TSDataType dataType, - TSEncoding encoding, CompressionType compressor, Map props, - Map tags, Map attributes, String measurementAlias) - -void createMultiTimeseries(List paths, List dataTypes, - List encodings, List compressors, - List> propsList, List> tagsList, - List> attributesList, List measurementAliasList) -``` - -- Create aligned timeseries - -```java -void createAlignedTimeseries(String prefixPath, List measurements, - List dataTypes, List encodings, - List compressors, List measurementAliasList); -``` - -Attention: Alias of measurements are **not supported** currently. - -- Delete one or several timeseries - -```java -void deleteTimeseries(String path) -void deleteTimeseries(List paths) -``` - -- Check whether the specific timeseries exists. - -```java -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. - +### 2. Create session instances +#### Session +Method 1: Create a Session instance using the Builder constructor. ```java -public void createSchemaTemplate(Template template); - -Class Template { - private String name; - private boolean directShareTime; - Map children; - public Template(String name, boolean isShareTime); - - public void addToTemplate(Node node); - public void deleteFromTemplate(String name); - public void setShareTime(boolean shareTime); -} - -Abstract Class Node { - private String name; - public void addChild(Node node); - public void deleteChild(Node node); -} - -Class MeasurementNode extends Node { - TSDataType dataType; - TSEncoding encoding; - CompressionType compressor; - public MeasurementNode(String name, - TSDataType dataType, - TSEncoding encoding, - CompressionType compressor); +package org.example; + +import org.apache.iotdb.isession.util.Version; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.session.Session; + +public class IoTDBSessionExample { + public static void main(String[] args) { + Session session = + new Session.Builder() + .host("127.0.0.1") + .port(6667) + .username("root") + .password("root") + .version(Version.V_1_0) + .build(); + try { + session.open(); + } catch (IoTDBConnectionException e) { + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + } } ``` -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: - -```java -MeasurementNode nodeX = new MeasurementNode("x", TSDataType.FLOAT, TSEncoding.RLE, CompressionType.SNAPPY); -MeasurementNode nodeY = new MeasurementNode("y", TSDataType.FLOAT, TSEncoding.RLE, CompressionType.SNAPPY); -MeasurementNode nodeSpeed = new MeasurementNode("speed", TSDataType.DOUBLE, TSEncoding.GORILLA, CompressionType.SNAPPY); - -// This is the template we suggest to implement -Template flatTemplate = new Template("flatTemplate"); -template.addToTemplate(nodeX); -template.addToTemplate(nodeY); -template.addToTemplate(nodeSpeed); - -createSchemaTemplate(flatTemplate); -``` - -You can query measurement inside templates with these APIS: - +Method 2: Create a Session instance using the new Session object. ```java -// Return the amount of measurements inside a template -public int countMeasurementsInTemplate(String templateName); - -// Return true if path points to a measurement, otherwise returne false -public boolean isMeasurementInTemplate(String templateName, String path); - -// Return true if path exists in template, otherwise return false -public boolean isPathExistInTemplate(String templateName, String path); - -// Return all measurements paths inside template -public List showMeasurementsInTemplate(String templateName); - -// Return all measurements paths under the designated patter inside template -public List 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.** - -```java -void setSchemaTemplate(String templateName, String prefixPath) +package org.example; + +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.session.Session; + +public class IoTDBSessionExample { + public static void main(String[] args) { + Session session = new Session("127.0.0.1", 6667); + try { + session.open(); + } catch (IoTDBConnectionException e) { + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + } +} ``` -Before setting template, you should firstly create the template using - +#### Session Pool +方式一:通过Builder来创建Session Pool实例 ```java -void createSchemaTemplate(Template template) +package org.example; + +import org.apache.iotdb.session.pool.SessionPool; + +public class IoTDBSessionExample { + public static void main(String[] args) { + SessionPool sessionPool = + new SessionPool.Builder() + .host("127.0.0.1") + .port(6667) + .user("root") + .password("root") + .maxSize(3) + .build(); + } +} ``` -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. - +#### Session Pool +Method 1: Create a Session Pool instance using Builder ```java -void createTimeseriesUsingSchemaTemplate(List devicePathList) +package org.example; + +import org.apache.iotdb.session.pool.SessionPool; + +public class IoTDBSessionExample { + public static void main(String[] args) { + SessionPool sessionPool = + new SessionPool.Builder() + .host("127.0.0.1") + .port(6667) + .user("root") + .password("root") + .maxSize(3) + .build(); + } +} ``` -After setting template to a certain path, you can query for info about template using belowed interface in session: - +Method 2: Create a SessionPool instance using a direct new SessionPool object ```java -/** @return All template names. */ -public List showAllTemplates(); - -/** @return All paths have been set to designated template. */ -public List showPathsTemplateSetOn(String templateName); - -/** @return All paths are using designated template. */ -public List showPathsTemplateUsingOn(String templateName) -``` +package org.example; -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. +import org.apache.iotdb.session.pool.SessionPool; -```java -void unsetSchemaTemplate(String prefixPath, String templateName); -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) - -### Data Insert API - -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 - -```java -void insertTablet(Tablet tablet) - -public class Tablet { - /** deviceId of this tablet */ - public String prefixPath; - /** the list of measurement schemas for creating the tablet */ - private List schemas; - /** timestamps in this tablet */ - public long[] timestamps; - /** each object is a primitive type array, which represents values of one measurement */ - public Object[] values; - /** each bitmap represents the existence of each value in the current column. */ - public BitMap[] bitMaps; - /** the number of rows to include in this tablet */ - public int rowSize; - /** the maximum number of rows for this tablet */ - private int maxRowNumber; - /** whether this tablet store data of aligned timeseries or not */ - private boolean isAligned; +public class IoTDBSessionExample { + public static void main(String[] args) { + SessionPool sessionPool = + new SessionPool("127.0.0.1",6667,"root","root",100); + } } ``` -- Insert multiple Tablets - -```java -void insertTablets(Map 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. - - | TSDataType | Object | - | ---------- | -------------- | - | BOOLEAN | Boolean | - | INT32 | Integer | - | DATE | LocalDate | - | INT64 | Long | - | TIMESTAMP | Long | - | FLOAT | Float | - | DOUBLE | Double | - | TEXT | String, Binary | - | STRING | String, Binary | - | BLOB | Binary | +### Perform Database Operation +The Session method list is the same as the SessionPool method list. This section uses Session as an example. If SessionPool is required, replace the Session object with SessionPool. +#### 元数据操作 ```java -void insertRecord(String deviceId, long time, List measurements, - List types, List values) +package org.example; + +import org.apache.iotdb.isession.util.Version; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.Session; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.file.metadata.enums.CompressionType; +import org.apache.tsfile.file.metadata.enums.TSEncoding; + +public class IoTDBSessionExample { + + public static void main(String[] args) { + Session session = + new Session.Builder() + .host("127.0.0.1") + .port(6667) + .username("root") + .password("root") + .version(Version.V_1_0) + .build(); + try { + session.open(); + } catch (IoTDBConnectionException e) { + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + + try { + // 1. create a database + session.createDatabase("root.sg1"); + // 2. create a time series + session.createTimeseries( + "root.sg1.d1.s1", TSDataType.INT64, TSEncoding.RLE, CompressionType.SNAPPY); + // 3. delete a time series + session.deleteTimeseries("root.sg1.d1.s1"); + } catch (IoTDBConnectionException | StatementExecutionException e) { + throw new RuntimeException(e); + } + try { + session.close(); + } catch (IoTDBConnectionException e) { + // solve exception + } + } +} ``` +#### Data Write +In industrial scenarios, data write can be classified into the following types based on the number of devices, write frequency, and data type: Single point real-time write, multiple devices write in batches, historical data write on a single device, batch data upload, and alignment data write. Different scenarios apply to different write interfaces. The following describes write interfaces in different scenarios. +##### Single Point Real-time Write +Scenario: Real-time status data of a single device is written with low update frequency. Usually, only one record is written at a time. -- Insert multiple Records +Applicable Interface: -```java -void insertRecords(List deviceIds, List times, - List> measurementsList, List> typesList, - List> 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 +| Interface name | Function description | +|-----------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------| +| `insertRecord(String deviceId, long time, List measurements, List types, List values)` | A record of a single moment when multiple measuring points are inserted into a single device | +| `insertRecord(String deviceId, long time, List measurements, List values)` | Similarly, there is no need to specify a data type and inferences are made based on the value passed in. Inference rules can be on the server configuration, detailed configuration in iotdb - system. The properties, the search in the template ` infer_type ` keyword | +| `insertAlignedRecord(String deviceId, long time, List measurements, List types, List values)` | A record of one moment of multiple measurement points inserted into a single device, which is an alignment device | +| `insertAlignedRecord(String deviceId, long time, List measurements, List values)` | Similarly, there is no need to specify a data type and inferences are made based on the value passed in. Inference rules can be on the server configuration, detailed configuration in iotdb - system. The properties, the search in the template ` infer_type ` keyword | +Code case: ```java -void insertRecordsOfOneDevice(String deviceId, List times, - List> measurementsList, List> typesList, - List> valuesList) +package org.example; + +import java.util.ArrayList; +import java.util.List; +import org.apache.iotdb.isession.util.Version; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.Session; +import org.apache.tsfile.enums.TSDataType; + +public class IoTDBSessionExample { + + public static void main(String[] args) { + Session session = + new Session.Builder() + .host("127.0.0.1") + .port(6667) + .username("root") + .password("root") + .version(Version.V_1_0) + .build(); + try { + session.open(); + } catch (IoTDBConnectionException e) { + // 连接Session异常 + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + String deviceId = "root.sg1.d1"; + List measurements = new ArrayList<>(); + List types = new ArrayList<>(); + measurements.add("s1"); + measurements.add("s2"); + measurements.add("s3"); + types.add(TSDataType.INT64); + types.add(TSDataType.INT64); + types.add(TSDataType.INT64); + + for (long time = 0; time < 100; time++) { + List values = new ArrayList<>(); + values.add(1L); + values.add(2L); + values.add(3L); + try { + session.insertRecord(deviceId, time, measurements, types, values); + } catch (IoTDBConnectionException | StatementExecutionException e) { + // solve exception + } + } + try { + session.close(); + } catch (IoTDBConnectionException e) { + // solve exception + } + } +} ``` -#### 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 - -```java -void insertRecord(String prefixPath, long time, List measurements, List values) -``` +##### Write data to multiple devices in batches +Scenario: Real-time status or sensor data written to multiple devices in batches, suitable for factory or shop floor environments. -- Insert multiple Records +Applicable interface: -```java -void insertRecords(List deviceIds, List times, - List> measurementsList, List> valuesList) -``` +| Interface name | Function description | +|-----------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------| +| `insertRecords(List deviceIds, List times, List> measurementsList, List> typesList, List> valuesList)` | Insert multiple devices and record one moment of multiple measuring points for each device | +| `insertRecords(List deviceIds, List times, List> measurementsList, List> valuesList)` | Similarly, there is no need to specify a data type and inferences are made based on the value passed in. Inference rules can be on the server configuration, detailed configuration in iotdb - system. The properties, the search in the template ` infer_type ` keyword | +| `insertAlignedRecords(List deviceIds, List times, List> measurementsList, List> typesList, List> valuesList)` | Insert multiple devices and record one moment of multiple measuring points for each device. Each device is an aligned device | +| `insertAlignedRecords(List deviceIds, List times, List> measurementsList, List> valuesList)` | Similarly, there is no need to specify a data type and inferences are made based on the value passed in. Inference rules can be on the server configuration, detailed configuration in iotdb - system. The properties, the search in the template ` infer_type ` keyword | -- Insert multiple Records that belong to the same device. +Code case: ```java -void insertStringRecordsOfOneDevice(String deviceId, List times, - List> measurementsList, List> valuesList) +package org.example; + +import java.util.ArrayList; +import java.util.List; +import org.apache.iotdb.isession.util.Version; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.Session; +import org.apache.tsfile.enums.TSDataType; + +public class IoTDBSessionExample { + + public static void main(String[] args) { + Session session = + new Session.Builder() + .host("127.0.0.1") + .port(6667) + .username("root") + .password("root") + .version(Version.V_1_0) + .build(); + try { + session.open(); + } catch (IoTDBConnectionException e) { + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + String deviceId = "root.sg1.d1.s1"; + List measurements = new ArrayList<>(); + measurements.add("s1"); + measurements.add("s2"); + measurements.add("s3"); + List deviceIds = new ArrayList<>(); + List> measurementsList = new ArrayList<>(); + List> valuesList = new ArrayList<>(); + List timestamps = new ArrayList<>(); + List> typesList = new ArrayList<>(); + + for (long time = 0; time < 500; time++) { + List values = new ArrayList<>(); + List types = new ArrayList<>(); + values.add(1L); + values.add(2L); + values.add(3L); + types.add(TSDataType.INT64); + types.add(TSDataType.INT64); + types.add(TSDataType.INT64); + + deviceIds.add(deviceId); + measurementsList.add(measurements); + valuesList.add(values); + typesList.add(types); + timestamps.add(time); + if (time != 0 && time % 100 == 0) { + try { + session.insertRecords(deviceIds, timestamps, measurementsList, typesList, valuesList); + } catch (IoTDBConnectionException | StatementExecutionException e) { + // solve exception + } + deviceIds.clear(); + measurementsList.clear(); + valuesList.clear(); + typesList.clear(); + timestamps.clear(); + } + } + + try { + session.insertRecords(deviceIds, timestamps, measurementsList, typesList, valuesList); + } catch (IoTDBConnectionException | StatementExecutionException e) { + // solve exception + } + try { + session.close(); + } catch (IoTDBConnectionException e) { + // solve exception + } + } +} ``` -#### Insert of Aligned Timeseries - -The Insert of aligned timeseries uses interfaces like insertAlignedXXX, and others are similar to the above interfaces: +##### Single device historical data write-up -- insertAlignedRecord -- insertAlignedRecords -- insertAlignedRecordsOfOneDevice -- insertAlignedStringRecordsOfOneDevice -- insertAlignedTablet -- insertAlignedTablets +Scenario: Multiple historical records need to be added at a time because data collection intervals exist on a single device. -### Data Delete API +Applicable interface: -- Delete data before or equal to a timestamp of one or several timeseries +| Interface name | Function description | +|-----------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------| +| `insertRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> typesList, List> valuesList)` | Insert multiple records for a single device | +| `insertRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> typesList, List> valuesList, boolean haveSorted)` | Insert the sorting record of a single device, and its data is sorted without any out-of-order situation | +| `insertRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> valuesList)` | Similarly, there is no need to specify a data type and inferences are made based on the value passed in. Inference rules can be on the server configuration, detailed configuration in iotdb - system. The properties, the search in the template ` infer_type ` keyword | +| `insertAlignedRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> typesList, List> valuesList)` | Insert multiple records for a single device, which is an alignment device | +| `insertAlignedRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> typesList, List> valuesList, boolean haveSorted)` | Insert multiple records of a single device. This device is an aligned device, and its data has been sorted without any out-of-order | +| `insertAlignedRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> valuesList)` | Similarly, there is no need to specify a data type and inferences are made based on the value passed in. Inference rules can be on the server configuration, detailed configuration in iotdb - system. The properties, the search in the template ` infer_type ` keyword | +Code case: ```java -void deleteData(String path, long time) -void deleteData(List paths, long time) +package org.example; + +import java.util.ArrayList; +import java.util.List; +import org.apache.iotdb.isession.util.Version; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.Session; +import org.apache.tsfile.enums.TSDataType; + +public class IoTDBSessionExample { + + public static void main(String[] args) throws IoTDBConnectionException, StatementExecutionException { + Session session = + new Session.Builder() + .host("127.0.0.1") + .port(6667) + .username("root") + .password("root") + .version(Version.V_1_0) + .build(); + try { + session.open(); + } catch (IoTDBConnectionException e) { + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + String deviceId = "root.sg1.d1.s1"; + List measurements = new ArrayList<>(); + measurements.add("s1"); + measurements.add("s2"); + measurements.add("s3"); + List> measurementsList = new ArrayList<>(); + List> valuesList = new ArrayList<>(); + List timestamps = new ArrayList<>(); + List> typesList = new ArrayList<>(); + + for (long time = 0; time < 10; time ++) { + List values = new ArrayList<>(); + List types = new ArrayList<>(); + values.add(1L); + values.add(2L); + values.add(3L); + types.add(TSDataType.INT64); + types.add(TSDataType.INT64); + types.add(TSDataType.INT64); + measurementsList.add(measurements); + valuesList.add(values); + typesList.add(types); + timestamps.add(time); + } + + session.insertRecordsOfOneDevice(deviceId, timestamps, measurementsList, typesList, valuesList); + try { + session.close(); + } catch (IoTDBConnectionException e) { + // solve exception + } + } +} ``` - -### Data Query API - -- 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. - +##### Batch data upload +Scenario: A large amount of data is uploaded from multiple devices at the same time, suitable for large-scale distributed data access. + +Applicable interface: + +| Interface name | Function description | +|-----------------------------------------------------------------------------------------|------------------------------------------| +| `insertTablet(Tablet tablet)` | Insert multiple measuring points for a single device, with data for multiple times at each measuring point | +| `insertTablet(Tablet tablet, boolean sorted)` | Insert a single device with multiple measuring points, and the data of each measuring point at multiple times have been sorted | +| `insertTablets(Map tablets)` | Insert multiple measuring points for a single device, with data for multiple times at each measuring point | +| `insertTablets(Map tablets, boolean sorted)` | Insert a single device with multiple measuring points, and the data of each measuring point at multiple times have been sorted | +| `insertAlignedTablet(Tablet tablet)` | Insert a single device with multiple measuring points, each measuring point with multiple moments of data, the device is aligned device | +| `insertAlignedTablet(Tablet tablet, boolean sorted)` | Insert a single device with multiple measuring points, each measuring point with multiple moments of data, the device is aligned device, and its data has been sorted | +| `insertAlignedTablets(Map tablets)` | Insert multiple devices and multiple measuring points, each measuring point multiple time data | +| `insertAlignedTablets(Map tablets, boolean sorted)` | Insert multiple devices and multiple measuring points, and the data of each measuring point at multiple times has been arranged | + +Code case: ```java -SessionDataSet executeRawDataQuery(List paths, long startTime, long endTime); +package org.example; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import org.apache.iotdb.isession.util.Version; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.Session; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.write.record.Tablet; +import org.apache.tsfile.write.schema.MeasurementSchema; + +public class IoTDBSessionExample { + + public static void main(String[] args) throws IoTDBConnectionException, StatementExecutionException { + Session session = + new Session.Builder() + .host("127.0.0.1") + .port(6667) + .username("root") + .password("root") + .version(Version.V_1_0) + .build(); + try { + session.open(); + } catch (IoTDBConnectionException e) { + // 连接Session异常 + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + String deviceId = "root.sg1.d1.s1"; + /* + * A Tablet example: + * device1 + * time s1, s2, s3 + * 1, 1, 1, 1 + * 2, 2, 2, 2 + * 3, 3, 3, 3 + */ + // The schema of measurements of one device + // only measurementId and data type in MeasurementSchema take effects in Tablet + List schemaList = new ArrayList<>(); + schemaList.add(new MeasurementSchema("s1", TSDataType.INT64)); + schemaList.add(new MeasurementSchema("s2", TSDataType.INT64)); + schemaList.add(new MeasurementSchema("s3", TSDataType.INT64)); + + Tablet tablet = new Tablet(deviceId, schemaList, 100); + + // Method 1 to add tablet data + long timestamp = System.currentTimeMillis(); + Random random = new Random(); + for (long row = 0; row < 100; row++) { + int rowIndex = tablet.rowSize++; + tablet.addTimestamp(rowIndex, timestamp); + for (int s = 0; s < 3; s++) { + long value = random.nextLong(); + tablet.addValue(schemaList.get(s).getMeasurementId(), rowIndex, value); + } + if (tablet.rowSize == tablet.getMaxRowNumber()) { + session.insertTablet(tablet, true); + tablet.reset(); + } + timestamp++; + } + + if (tablet.rowSize != 0) { + session.insertTablet(tablet); + tablet.reset(); + } + try { + session.close(); + } catch (IoTDBConnectionException e) { + // solve exception + } + } +} ``` -- Last query: - - - Query the last data, whose timestamp is greater than or equal LastTime. - - ```java - SessionDataSet executeLastDataQuery(List 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. - - ```java - SessionDataSet executeLastDataQueryForOneDevice( - String db, String device, List 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. - +#### Data query ```java -SessionDataSet executeAggregationQuery(List paths, List aggregations); - -SessionDataSet executeAggregationQuery( - List paths, List aggregations, long startTime, long endTime); - -SessionDataSet executeAggregationQuery( - List paths, - List aggregations, - long startTime, - long endTime, - long interval); - -SessionDataSet executeAggregationQuery( - List paths, - List aggregations, - long startTime, - long endTime, - long interval, - long slidingStep); +package org.example; + +import java.util.ArrayList; +import java.util.List; +import org.apache.iotdb.common.rpc.thrift.TAggregationType; +import org.apache.iotdb.isession.SessionDataSet; +import org.apache.iotdb.isession.util.Version; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.Session; + +public class IoTDBSessionExample { + private static final String ROOT_SG1_D1_S1 = "root.sg1.d1.s1"; + private static final String ROOT_SG1_D1_S2 = "root.sg1.d1.s2"; + private static final String ROOT_SG1_D1_S3 = "root.sg1.d1.s3"; + + public static void main(String[] args) throws IoTDBConnectionException, StatementExecutionException { + Session session = + new Session.Builder() + .host("127.0.0.1") + .port(6667) + .username("root") + .password("root") + .version(Version.V_1_0) + .build(); + try { + session.open(); + } catch (IoTDBConnectionException e) { + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + + // 1. Query raw data using sql + try (SessionDataSet dataSet = session.executeQueryStatement("select * from root.sg1.d1")) { + System.out.println(dataSet.getColumnNames()); + dataSet.setFetchSize(1024); // default is 10000 + while (dataSet.hasNext()) { + System.out.println(dataSet.next()); + } + } + + // 2. Specify the query point, start time, end time, and timeout time + List paths = new ArrayList<>(); + paths.add(ROOT_SG1_D1_S1); + paths.add(ROOT_SG1_D1_S2); + paths.add(ROOT_SG1_D1_S3); + long startTime = 10L; + long endTime = 200L; + long timeOut = 60000; + + try (SessionDataSet dataSet = session.executeRawDataQuery(paths, startTime, endTime, timeOut)) { + System.out.println(dataSet.getColumnNames()); + dataSet.setFetchSize(1024); + while (dataSet.hasNext()) { + System.out.println(dataSet.next()); + } + } + + // 3. Latest value query + try (SessionDataSet sessionDataSet = session.executeLastDataQuery(paths, 3, 60000)) { + System.out.println(sessionDataSet.getColumnNames()); + sessionDataSet.setFetchSize(1024); + while (sessionDataSet.hasNext()) { + System.out.println(sessionDataSet.next()); + } + } + + // 4. Aggregate query + List aggregations = new ArrayList<>(); + aggregations.add(TAggregationType.COUNT); + aggregations.add(TAggregationType.SUM); + aggregations.add(TAggregationType.MAX_VALUE); + try (SessionDataSet sessionDataSet = session.executeAggregationQuery(paths, aggregations)) { + System.out.println(sessionDataSet.getColumnNames()); + sessionDataSet.setFetchSize(1024); + while (sessionDataSet.hasNext()) { + System.out.println(sessionDataSet.next()); + } + } + + // 5. Group query + try (SessionDataSet sessionDataSet = + session.executeAggregationQuery(paths, aggregations, 0, 100, 10, 20)) { + System.out.println(sessionDataSet.getColumnNames()); + sessionDataSet.setFetchSize(1024); + while (sessionDataSet.hasNext()) { + System.out.println(sessionDataSet.next()); + } + } + } +} ``` -- Execute query statement - +#### Data deletion ```java -SessionDataSet executeQueryStatement(String sql) +package org.example; + +import java.util.Collections; +import org.apache.iotdb.isession.util.Version; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.Session; + +public class IoTDBSessionExample { + private static final String ROOT_SG1_D1_S1 = "root.sg1.d1.s1"; + + public static void main(String[] args) throws IoTDBConnectionException, StatementExecutionException { + Session session = + new Session.Builder() + .host("127.0.0.1") + .port(6667) + .username("root") + .password("root") + .version(Version.V_1_0) + .build(); + try { + session.open(); + } catch (IoTDBConnectionException e) { + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + + // 1. Delete data at a precise point in time + String path = ROOT_SG1_D1_S1; + long deleteTime = 99; + session.deleteData(path, deleteTime); + + // 2. The data of a certain period is deleted + long startTime = 1; + session.deleteData(Collections.singletonList(path),startTime, deleteTime); + + // 3. Delete a measurement point + session.deleteTimeseries(path); + } +} ``` -### Data Subscription - -#### 1 Topic Management +## Detailed Interface Description +### Parameter list +#### Session +| Field name | Type | description | +|--------------------------------|-------------------------------|------------------------------------------------------------| +| `nodeUrls` | `List` | URL list of database nodes, supporting multi-node connections | +| `username` | `String` | Username | +| `password` | `String` | Password | +| `fetchSize` | `int` | Default batch return size of query results | +| `useSSL` | `boolean` | Whether to enable SSL | +| `trustStore` | `String` | Trust store path | +| `trustStorePwd` | `String` | Trust store password | +| `queryTimeoutInMs` | `long` | Query timeout period, in milliseconds | +| `enableRPCCompression` | `boolean` | Whether to enable RPC compression | +| `connectionTimeoutInMs` | `int` | Connection timeout, in milliseconds | +| `zoneId` | `ZoneId` | Time zone setting of the session | +| `thriftDefaultBufferSize` | `int` | Thrift Default buffer size | +| `thriftMaxFrameSize` | `int` | Thrift Maximum frame size | +| `defaultEndPoint` | `TEndPoint` | Default database endpoint information | +| `defaultSessionConnection` | `SessionConnection` | Default session connection object | +| `isClosed` | `boolean` | Whether the current session is closed | +| `enableRedirection` | `boolean` | Whether to enable the redirection function | +| `enableRecordsAutoConvertTablet` | `boolean` | Whether to enable automatic conversion of records to Tablet | +| `deviceIdToEndpoint` | `Map` | Mapping between device ids and database endpoints | +| `endPointToSessionConnection` | `Map` | Mapping between database endpoints and session connections | +| `executorService` | `ScheduledExecutorService` | A thread pool for periodically updating the node list | +| `availableNodes` | `INodeSupplier` |Providers for available nodes | +| `enableQueryRedirection` | `boolean` | Whether to enable the query redirection function | +| `version` | `Version` | Version number of the client, which is used to determine the compatibility with the server | +| `enableAutoFetch` | `boolean` | Whether to enable the automatic obtaining function | +| `maxRetryCount` | `int` | Maximum retry | +| `retryIntervalInMs` | `long` | Retry interval, in milliseconds | +Parameters that require additional clarification + +nodeUrls: A list of multi-node urls that automatically switch to the next available node. The format is ip:port. + +queryTimeoutInMs: If negative, the default configuration on the server is used; If the value is 0, the query timeout function is disabled. + +enableRPCCompression: After this parameter is enabled, RPC data transmission is compressed. This parameter is applicable to scenarios with high bandwidth delay. + +zoneId: indicates the session time zone. The available value can refer to Java's ZoneId standard, for example, Asia/Shanghai. + +#### SessionPool +|Field name | Type | description | +|--------------------------------|-------------------------------|-------------------------------------------------------------------| +| `host` | `String` | Database host address | +| `port` | `int` | Database port | +| `user` | `String` | Database user name | +| `password` | `String` | Database password | +| `nodeUrls` | `List` | A list of multi-node urls | +| `maxSize` | `int` | The maximum number of connections in the connection pool is | +| `fetchSize` | `int` | The default batch return size of the query results is | +| `waitToGetSessionTimeoutInMs` | `long` | The wait timeout for getting a connection (ms) | +| `enableCompression` | `boolean` | Whether to enable RPC compression | +| `enableRedirection` | `boolean` | Whether to enable the redirection function | +| `enableRecordsAutoConvertTablet` | `boolean` | Whether to enable automatic Tablet conversion of records | +| `thriftDefaultBufferSize` | `int` | Thrift Default buffer size | +| `thriftMaxFrameSize` | `int` | Thrift Maximum frame size | +| `queryTimeoutInMs` | `long` | Query timeout period, expressed in milliseconds | +| `version` | `Version` | The client version | +| `connectionTimeoutInMs` | `int` | Connection timeout, in milliseconds | +| `zoneId` | `ZoneId` | Time zone Settings | +| `useSSL` | `boolean` | Whether to enable SSL | +| `trustStore` | `String` | The truststore path is | +| `trustStorePwd` | `String` | Trust store password | +| `enableQueryRedirection` | `boolean` | Whether to enable the query redirection function | +| `executorService` | `ScheduledExecutorService` | The thread pool for the node list is periodically updated | +| `availableNodes` | `INodeSupplier` | Providers for available nodes | +| `maxRetryCount` | `int` | The maximum number of retries | +| `retryIntervalInMs` | `long` | Retry interval, in milliseconds | +| `closed` | `boolean` | Whether the current connection pool is closed | +| `queue` | `ConcurrentLinkedDeque` | Queues to which sessions are available | +| `occupied` | `ConcurrentMap` | The occupied session connections are mapped to | +| `deviceIdToEndpoint` | `Map` | Mapping of device ids to database endpoints | +| `formattedNodeUrls` | `String` | The formatted node URL string | +Fields that require additional clarification + +nodeUrls: A list of multiple node addresses to support connectivity in a clustered environment. The format is ["host1:port1", "host2:port2"]. + +queue: Stores all available session connections. It is removed from the queue when a connection is needed. + +occupied: Records the occupied connection so that it can be properly reclaimed when the connection is released. + +maxRetryCount and retryIntervalInMs: control the retry policy. When an operation fails, the retrycount and RetryIntervalinMs are used to control the specified retry times. + + +### List of functions +#### Session Management +| 方法名 | Function Description | Parameter Description | +|-----------------------------------------------------------------------------------------|--------------------------------------------|-----------------------------------------------------------------------------------------------------------| +| `open()` | Open a session | No parameters | +| `open(boolean enableRPCCompression)` | Open a session and enableRPC compression | `enableRPCCompression` : Whether to enable RPC compression | +| `open(boolean enableRPCCompression, int connectionTimeoutInMs)` | Open a session and set the connection timeout | `enableRPCCompression` : Whether to enableRPC compression, `connectionTimeoutInMs` : Connection timeout (ms) | +| `open(boolean enableRPCCompression, int connectionTimeoutInMs, Map deviceIdToEndpoint, INodeSupplier nodeSupplier)` | Open a session and configure the node | `enableRPCCompression` : Whether to enableRPC compression, `connectionTimeoutInMs` : Timeout, `deviceIdToEndpoint` : device mapping | +| `close()` | Close a session | No parameter | +| `getVersion()` | Obtain the session version | No parameter is specified | +| `setVersion(Version version)` | Set session version | `version` : The version to set | +| `getTimeZone()` | Obtain the current time zone | None | +| `setTimeZone(String zoneId)` | Set the time zone | `zoneId` : time zone identifier (for example, `Asia/Shanghai`) | +| `setTimeZoneOfSession(String zoneId)` | Set the session time zone | `zoneId` : indicates the time zone identifier | +| `getFetchSize()` | Limit the number of records to be queried in batches | No parameter is specified | +| `setFetchSize(int fetchSize)` | Set the maximum number of records for batch query | `fetchSize` : specifies the maximum number of records returned in each batch of query | +| `setQueryTimeout(long timeoutInMs)` | Set the query timeout period | `timeoutInMs` : Query timeout period (milliseconds). | +| `getQueryTimeout()` | Obtain the query timeout period | No parameter | +| `isEnableQueryRedirection()` | Check whether query redirection is enabled | No parameter | +| `setEnableQueryRedirection(boolean enableQueryRedirection)` | Set query redirection | `enableQueryRedirection` : indicates whether query redirection is enabled | +| `isEnableRedirection()` | Check whether redirection is enabled | No parameter | +| `setEnableRedirection(boolean enableRedirection)` | To set redirection | `enableRedirection` : Whether to enable redirection | + +#### Metadata management +| 方法名 | Function Description | Parameter Description | +|----------------------------------------------------------|--------------------------------------------|------------------------------------------------------------------------------------------------------------| +| `createDatabase(String database)` | Create a database | `database` : the name of the database | +| `deleteDatabase(String database)` | Deletes the specified database | `database` : The name of the database to be deleted | +| `deleteDatabases(List databases)` |Batch delete databases | `databases` : list of database names to be deleted | +| `createTimeseries(String path, TSDataType dataType, TSEncoding encoding, CompressionType compressor)` | Create a single time series | `path` : time series path, `dataType` : data type, `encoding` : encoding type, and `compressor` : compression type | +| `createAlignedTimeseries(...)` | Create an alignment time series | device ID, point list, data type list, encoding list, and compression type list | +| `createMultiTimeseries(...)` | Batch create time series | with multiple paths, data types, encoders, compression types, attributes, tags, aliases, and more | +| `deleteTimeseries(String path)` | Delete time series | `path` : The time series path to delete is | +| `deleteTimeseries(List paths)` | Deletes time series in batches | `paths` : List of time series paths to delete | +| `setSchemaTemplate(String templateName, String prefixPath)`| Set the pattern template |` templateName `: prefixPath: indicates the path of the application template | +| `createSchemaTemplate(Template template)`| Creates a pattern template | `template` : The template object | +| `dropSchemaTemplate(String templateName)` | Deletes the schema template | `templateName` : | is the name of the template to be deleted +| `addAlignedMeasurementsInTemplate(...) `| Adds align points to template | template name, point path list, data type, encoding type, and compression type | +| `addUnalignedMeasurementsInTemplate(...)`| Add unaligned points to template | as above | +| `deleteNodeInTemplate(String templateName, String path)`| Deletes a node from a template |` templateName `: template name,` path `: The path to delete is | +| `countMeasurementsInTemplate (String name)` | statistical number of measuring points in the template | `name` : template name | +| `isMeasurementInTemplate(String templateName, String path)`| Check whether a measurement point exists in the template |` templateName `: template name,` path `: Measuring point path | +| `isPathExistInTemplate(String templateName, String path)`| Check whether the path | exists in the template | +| `showMeasurementsInTemplate (String templateName) ` | show that measuring point of the template | `templateName` : indicates the template name | +| `showMeasurementsInTemplate(String templateName, String pattern)`| Displays measurement points in the template by pattern |` templateName `: indicates the template name,` pattern `: Matching mode | +| `showAllTemplates()` | Displays all templates | There is no parameter | +| `showPathsTemplateSetOn(String templateName)` | Displays the path of the template application | `templateName` : indicates the template name | +| `showPathsTemplateUsingOn(String templateName)` | Displays the actual path used by the template | ibid. | +| `unsetSchemaTemplate(String prefixPath, String templateName)`| Unsets the path template |` prefixPath `: path,` templateName `: template name | + + +#### Data write +| Method name | Function Description | Parameter Description | +|-----------------------------------------------------------------------------------------|--------------------------------------------|------------------------------------------------------------------------------------------------------------| +| `insertRecord(String deviceId, long time, List measurements, List types, Object... values)` | Insert a single record | `deviceId` : device ID, `time` : timestamp, `measurements` : list of points,` types` : list of data types, `values` : list of values | +| `insertRecord(String deviceId, long time, List measurements, List values)` | Insert a single record | `deviceId` : device ID, `time` : timestamp, `measurements` : list of points,` values` : list of values | +| `insertRecords(List deviceIds, List times, List> measurementsList, List> valuesList)` | Insert multiple records | deviceIds: device ID list, times: timestamp list, measurementsList: measurement point list, valuesList: value list | +| `insertRecords(List deviceIds, List times, List> measurementsList, List> typesList, List> valuesList)` |Insert multiple records | as above, add `typesList` : list of data types | +| `insertRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> typesList, List> valuesList)` | Insert multiple records for a single device | `deviceId` : device ID, `times` : timestamp list,` measurementsList `: list of measurement points,` typesList `: Type list, `valuesList` : list of values | +| `insertRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> typesList, List> valuesList, boolean haveSorted)` | Insert sorted multiple records for a single device | as above, add `haveSorted` : whether the data is sorted | +| `insertStringRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> valuesList)` | Insert a single device record in string format | `deviceId` : device ID, `times` : timestamp list,` measurementsList `: list of points,` valuesList `: list of values| +| `insertStringRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> valuesList, boolean haveSorted)` |Insert sorted string format single-device record | as above, add `haveSorted` : whether the data is sorted | +| `insertAlignedRecord(String deviceId, long time, List measurements, List types, List values)` |Insert a single alignment record | `deviceId` : device ID, `time` : timestamp, `measurements` : list of points,` types` : type list, `values` : List of values | +| `insertAlignedRecord(String deviceId, long time, List measurements, List values) `| Inserts a single aligned record in string format |` deviceId `: device ID,` time `: timestamp,` measurements` : point list, `values` : List of values | +| `insertAlignedRecords(List deviceIds, List times, List> measurementsList, List> valuesList) `| Insert multiple alignment records |` deviceIds` : list of device ids, `times` : Timestamp list, `measurementsList` : list of measurement points, `valuesList` : list of values | +| `insertAlignedRecords(List deviceIds, List times, List> measurementsList, List> typesList, List> valuesList) `| Insert multiple aligned records | as above, Add `typesList` : list of data types | +| `insertAlignedRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> typesList, List> valuesList) `| Insert multiple alignment records for a single device | as above | +| `insertAlignedRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> typesList, List> valuesList, boolean haveSorted) `| Insert sorted single-device multiple aligned records | as above, Added `haveSorted` : Whether the data is sorted | +| `insertAlignedStringRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> valuesList) `| Inserts a single device alignment record in string format |` deviceId `: device ID,` times` : timestamp list, `measurementsList` : Point list, `valuesList` : list of values | +| `insertAlignedStringRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> valuesList, boolean haveSorted) `| Insert a sorted single-device alignment record in string format | as above, add` haveSorted `: Whether the data is sorted | +| `insertTablet(Tablet tablet)` | Inserts a single Tablet data | `tablet` : The Tablet data to be inserted | +| `insertTablet(Tablet tablet, boolean sorted) `| inserts sorted Tablet data | as above, add` sorted `: Whether the data is sorted | +| `insertAlignedTablet(Tablet tablet)` | inserts aligned Tablet data | `tablet` : The Tablet data to be inserted | +| `insertAlignedTablet(Tablet tablet, boolean sorted) `| inserts sorted aligning Tablet data | As above, add` sorted `: Whether the data is sorted | +| `insertTablets(Map tablets) `| Insert multiple Tablet data |` tablets` in batches: The mapping table for device ids to tablets | +| `insertTablets(Map tablets, boolean sorted) `| batch insert sorted Tablet data | As above, add` sorted `: Whether the data is sorted | +| `insertAlignedTablets(Map tablets) `| Batch insert multiple aligned Tablet data |` tablets` : The mapping table for device ids to tablets | +| `insertAlignedTablets(Map tablets, boolean sorted) `| batch insert sorted multiple aligned Tablet data | As above, add` sorted `: Whether the data is sorted | + +#### 数据删除 +| 方法名 | 功能描述 | 参数解释 | +|-----------------------------------------------------------------------------------------|--------------------------------------------|------------------------------------------------------------------------------------------------------------| +| `deleteTimeseries(String path)` | 删除单个时间序列 | `path`: 时间序列路径 | +| `deleteTimeseries(List paths)` | 批量删除时间序列 | `paths`: 时间序列路径列表 | +| `deleteData(String path, long endTime)` | 删除指定路径的历史数据 | `path`: 路径,`endTime`: 结束时间戳 | +| `deleteData(List paths, long endTime)` | 批量删除路径的历史数据 | `paths`: 路径列表,`endTime`: 结束时间戳 | +| `deleteData(List paths, long startTime, long endTime)` | 删除路径时间范围内的历史数据 | 同上,增加 `startTime`: 起始时间戳 | + + +#### Data query +| Method name | Function Description | Parameter Description | +|-----------------------------------------------------------------------------------------|--------------------------------------------|------------------------------------------------------------------------------------------------------------| +| `executeQueryStatement(String sql)` | Execute the query statement | `sql` : Query the SQL statement | +| `executeQueryStatement(String sql, long timeoutInMs) `| Execute a query with a timeout |` sql `: query an SQL statement,` timeoutInMs` : Query timeout period (ms) | +| `executeRawDataQuery(List paths, long startTime, long endTime) `| queries the raw data of the specified path |` paths `: queries the list of paths,` startTime `: start timestamp,` endTime `: End timestamp | +| `executeRawDataQuery(List paths, long startTime, long endTime, long timeOut) `| Queries the raw data of the specified path (with timeOut) | as above, add` timeout `: Timeout period | +| `executeLastDataQuery(List paths)` | Queries the latest data | `paths` : Query the list of paths | +| `executeLastDataQuery(List paths, long lastTime) `| to query the latest data at a specified time |` paths `: to query the list of paths,` lastTime `: The specified timestamp is | +| `executeLastDataQuery(List paths, long lastTime, long timeOut) `| Queries the latest data at the specified time (with timeOut) | as above, add` timeout `: Timeout period | +| `executeLastDataQueryForOneDevice(String db, String device, List sensors, boolean isLegalPathNodes) `| Queries the latest data on a single device |` db `: database name,` device `: device name,` sensors` : Sensor list, `isLegalPathNodes` : indicates whether a valid path node | +| `executeAggregationQuery(List paths, List aggregations) `| Execute the aggregation query |` paths `: query the list of paths,` aggregations` : List of aggregate types | +| `executeAggregationQuery(List paths, List aggregations, long startTime, long endTime) `| executes an aggregate query with a time range | as above, add` startTime `: the start timestamp,` endTime `: End timestamp | +| `executeAggregationQuery(List paths, List aggregations, long startTime, long endTime, long interval) `| Execute the aggregated query with interval | as above, add` interval `: Time interval | +| `executeAggregationQuery(List paths, List aggregations, long startTime, long endTime, long interval, long slidingStep) `| Run the sliding-window aggregate query | as above and add` slidingStep `: Slide step size | +| `fetchAllConnections()` | Get all active connection information | No parameter | + +#### System status and Backup +| Method name | Function Description | Parameter Description | +|-------------------------------------------------------------------------------------|--------------------------------------------|------------------------------------------------------------------------------------------------------------| +| `getBackupConfiguration()` | Obtain backup configuration information | No parameter is specified | +| `fetchAllConnections()` | Get all active connection information | There is no parameter | +| `getSystemStatus()` | gets the system status | is deprecated and `SystemStatus.NORMAL` is returned by default | + + + +# Data Subscription + +## 1 Topic Management The `SubscriptionSession` class in the IoTDB subscription client provides interfaces for topic management. The status changes of topics are illustrated in the diagram below: -::: center +
+ +
- - -::: - -##### 1.1 Create Topic +### 1.1 Create Topic ```Java void createTopicIfNotExists(String topicName, Properties properties) throws Exception; @@ -510,13 +925,13 @@ try (final SubscriptionSession session = new SubscriptionSession(host, port)) { } ``` -##### 1.2 Delete Topic +### 1.2 Delete Topic ```Java void dropTopicIfExists(String topicName) throws Exception; ``` -##### 1.3 View Topic +### 1.3 View Topic ```Java // Get all topics @@ -526,8 +941,7 @@ Set getTopics() throws Exception; Optional getTopic(String topicName) throws Exception; ``` -#### 2 Check Subscription Status - +## 2 Check Subscription Status The `SubscriptionSession` class in the IoTDB subscription client provides interfaces to check the subscription status: ```Java @@ -535,39 +949,43 @@ Set getSubscriptions() throws Exception; Set getSubscriptions(final String topicName) throws Exception; ``` -#### 3 Create Consumer +## 3 Create Consumer When creating a consumer using the JAVA native interface, you need to specify the parameters applied to the consumer. For both `SubscriptionPullConsumer` and `SubscriptionPushConsumer`, the following common configurations are available: -| key | **required or optional with default** | description | -| :---------------------- | :----------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| host | optional: 127.0.0.1 | `String`: The RPC host of a certain DataNode in IoTDB | -| port | optional: 6667 | Integer: The RPC port of a certain DataNode in IoTDB | -| node-urls | optional: 127.0.0.1:6667 | `List`: The RPC addresses of all DataNodes in IoTDB, can be multiple; either host:port or node-urls can be filled in. If both host:port and node-urls are filled in, the union of host:port and node-urls will be used to form a new node-urls application | -| username | optional: root | `String`: The username of a DataNode in IoTDB | -| password | optional: root | `String`: The password of a DataNode in IoTDB | -| groupId | optional | `String`: consumer group id, if not specified, a new consumer group will be randomly assigned, ensuring that different consumer groups have different consumer group ids | -| consumerId | optional | `String`: consumer client id, if not specified, it will be randomly assigned, ensuring that each consumer client id in the same consumer group is unique | -| heartbeatIntervalMs | optional: 30000 (min: 1000) | `Long`: The interval at which the consumer sends heartbeat requests to the IoTDB DataNode | -| endpointsSyncIntervalMs | optional: 120000 (min: 5000) | `Long`: The interval at which the consumer detects the expansion and contraction of IoTDB cluster nodes and adjusts the subscription connection | -| fileSaveDir | optional: Paths.get(System.getProperty("user.dir"), "iotdb-subscription").toString() | `String`: The temporary directory path where the TsFile files subscribed by the consumer are stored | -| fileSaveFsync | optional: false | `Boolean`: Whether the consumer actively calls fsync during the subscription of TsFile | - -##### 3.1 SubscriptionPushConsumer + +| key | **required or optional with default** | description | +| :---------------------- | :----------------------------------------------------------- | :----------------------------------------------------------- | +| host | optional: 127.0.0.1 | `String`: The RPC host of a certain DataNode in IoTDB | +| port | optional: 6667 | Integer: The RPC port of a certain DataNode in IoTDB | +| node-urls | optional: 127.0.0.1:6667 | `List`: The RPC addresses of all DataNodes in IoTDB, can be multiple; either host:port or node-urls can be filled in. If both host:port and node-urls are filled in, the union of host:port and node-urls will be used to form a new node-urls application | +| username | optional: root | `String`: The username of a DataNode in IoTDB | +| password | optional: root | `String`: The password of a DataNode in IoTDB | +| groupId | optional | `String`: consumer group id, if not specified, a new consumer group will be randomly assigned, ensuring that different consumer groups have different consumer group ids | +| consumerId | optional | `String`: consumer client id, if not specified, it will be randomly assigned, ensuring that each consumer client id in the same consumer group is unique | +| heartbeatIntervalMs | optional: 30000 (min: 1000) | `Long`: The interval at which the consumer sends heartbeat requests to the IoTDB DataNode | +| endpointsSyncIntervalMs | optional: 120000 (min: 5000) | `Long`: The interval at which the consumer detects the expansion and contraction of IoTDB cluster nodes and adjusts the subscription connection | +| fileSaveDir | optional: Paths.get(System.getProperty("user.dir"), "iotdb-subscription").toString() | `String`: The temporary directory path where the TsFile files subscribed by the consumer are stored | +| fileSaveFsync | optional: false | `Boolean`: Whether the consumer actively calls fsync during the subscription of TsFile | + + +### 3.1 SubscriptionPushConsumer The following are special configurations for `SubscriptionPushConsumer`: -| key | **required or optional with default** | description | -| :----------------- | :------------------------------------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | + +| key | **required or optional with default** | description | +| :----------------- | :------------------------------------ | :----------------------------------------------------------- | | ackStrategy | optional: `ACKStrategy.AFTER_CONSUME` | Consumption progress confirmation mechanism includes the following options: `ACKStrategy.BEFORE_CONSUME` (submit consumption progress immediately when the consumer receives data, before `onReceive`) `ACKStrategy.AFTER_CONSUME` (submit consumption progress after the consumer has consumed the data, after `onReceive`) | -| consumeListener | optional | Consumption data callback function, need to implement the `ConsumeListener` interface, define the consumption logic of `SessionDataSetsHandler` and `TsFileHandler` form data | -| autoPollIntervalMs | optional: 5000 (min: 500) | Long: The interval at which the consumer automatically pulls data, in ms | -| autoPollTimeoutMs | optional: 10000 (min: 1000) | Long: The timeout time for the consumer to pull data each time, in ms | +| consumeListener | optional | Consumption data callback function, need to implement the `ConsumeListener` interface, define the consumption logic of `SessionDataSetsHandler` and `TsFileHandler` form data| +| autoPollIntervalMs | optional: 5000 (min: 500) | Long: The interval at which the consumer automatically pulls data, in ms | +| autoPollTimeoutMs | optional: 10000 (min: 1000) | Long: The timeout time for the consumer to pull data each time, in ms | Among them, the ConsumerListener interface is defined as follows: + ```Java @FunctionInterface interface ConsumeListener { @@ -582,25 +1000,26 @@ enum ConsumeResult { } ``` -##### 3.2 SubscriptionPullConsumer +### 3.2 SubscriptionPullConsumer The following are special configurations for `SubscriptionPullConsumer` : -| key | **required or optional with default** | description | -| :----------------- | :------------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| key | **required or optional with default** | description | +| :----------------- | :------------------------------------ | :----------------------------------------------------------- | | autoCommit | optional: true | Boolean: Whether to automatically commit consumption progress. If this parameter is set to false, the commit method must be called to manually `commit` consumption progress. | -| autoCommitInterval | optional: 5000 (min: 500) | Long: The interval at which consumption progress is automatically committed, in milliseconds. This only takes effect when the autoCommit parameter is true. | -| | +| autoCommitInterval | optional: 5000 (min: 500) | Long: The interval at which consumption progress is automatically committed, in milliseconds. This only takes effect when the autoCommit parameter is true. +| After creating a consumer, you need to manually call the consumer's open method: + ```Java void open() throws Exception; ``` At this point, the IoTDB subscription client will verify the correctness of the consumer's configuration. After a successful verification, the consumer will join the corresponding consumer group. That is, only after opening the consumer can you use the returned consumer object to subscribe to topics, consume data, and perform other operations. -#### 4 Subscribe to Topics +## 4 Subscribe to Topics Both `SubscriptionPushConsumer` and `SubscriptionPullConsumer` provide the following JAVA native interfaces for subscribing to topics: @@ -616,21 +1035,23 @@ void subscribe(List topics) throws Exception; - If there are other consumers in the same consumer group that have subscribed to the same topics, the consumer will reuse the corresponding consumption progress. -#### 5 Consume Data + +## 5 Consume Data For both push and pull mode consumers: + - Only after explicitly subscribing to a topic will the consumer receive data for that topic. - If no topics are subscribed to after creation, the consumer will not be able to consume any data, even if other consumers in the same consumer group have subscribed to some topics. -##### 5.1 SubscriptionPushConsumer +### 5.1 SubscriptionPushConsumer After `SubscriptionPushConsumer` subscribes to topics, there is no need to manually pull data. The data consumption logic is within the `consumeListener` configuration specified when creating `SubscriptionPushConsumer`. -##### 5.2 SubscriptionPullConsumer +### 5.2 SubscriptionPullConsumer After SubscriptionPullConsumer subscribes to topics, it needs to actively call the poll method to pull data: @@ -643,8 +1064,10 @@ List poll(final Set topicNames, final long timeoutM In the poll method, you can specify the topic names to be pulled (if not specified, it defaults to pulling all topics that the consumer has subscribed to) and the timeout period. + When the SubscriptionPullConsumer is configured with the autoCommit parameter set to false, it is necessary to manually call the commitSync and commitAsync methods to synchronously or asynchronously commit the consumption progress of a batch of data: + ```Java void commitSync(final SubscriptionMessage message) throws Exception; void commitSync(final Iterable messages) throws Exception; @@ -669,7 +1092,7 @@ public interface AsyncCommitCallback { } ``` -#### 6 Unsubscribe +## 6 Unsubscribe The `SubscriptionPushConsumer` and `SubscriptionPullConsumer` provide the following JAVA native interfaces for unsubscribing and closing the consumer: @@ -686,9 +1109,10 @@ void close(); - When a consumer is closed, it will exit the corresponding consumer group and automatically unsubscribe from all topics it is currently subscribed to. - Once a consumer is closed, its lifecycle ends, and it cannot be reopened to subscribe to and consume data again. -#### 7 Code Examples -##### 7.1 Single Pull Consumer Consuming SessionDataSetsHandler Format Data +## 7 Code Examples + +### 7.1 Single Pull Consumer Consuming SessionDataSetsHandler Format Data ```Java // Create topics @@ -733,7 +1157,7 @@ consumer1.unsubscribe(TOPIC_1); consumer1.close(); ``` -##### 7.2 Multiple Push Consumers Consuming TsFileHandler Format Data +## 7.2 Multiple Push Consumers Consuming TsFileHandler Format Data ```Java // Create topics @@ -778,56 +1202,4 @@ for (int i = 0; i < 8; ++i) { for (final Thread thread : threads) { thread.join(); } -``` - -### Other Modules (Execute SQL Directly) - -- Execute non query statement - -```java -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 - -```java -void testInsertRecord(String deviceId, long time, List measurements, List values) - -void testInsertRecord(String deviceId, long time, List measurements, - List types, List values) -``` - -- Test the network and client cost of insertRecords - -```java -void testInsertRecords(List deviceIds, List times, - List> measurementsList, List> valuesList) - -void testInsertRecords(List deviceIds, List times, - List> measurementsList, List> typesList - List> valuesList) -``` - -- Test the network and client cost of insertTablet - -```java -void testInsertTablet(Tablet tablet) -``` - -- Test the network and client cost of insertTablets - -```java -void testInsertTablets(Map 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` +``` \ No newline at end of file diff --git a/src/zh/UserGuide/latest/API/Programming-Java-Native-API.md b/src/zh/UserGuide/latest/API/Programming-Java-Native-API.md index 8c68005d..5ddffc76 100644 --- a/src/zh/UserGuide/latest/API/Programming-Java-Native-API.md +++ b/src/zh/UserGuide/latest/API/Programming-Java-Native-API.md @@ -1,457 +1,891 @@ # Java 原生接口 -## 安装 +## 概述 + +IoTDB 原生 API 中的 Session 是实现与数据库交互的核心接口,它集成了丰富的方法,支持数据写入、查询以及元数据操作等功能。通过实例化 Session,能够建立与 IoTDB 服务器的连接,在该连接所构建的环境中执行各类数据库操作。 +此外,IoTDB 还提供了 Session Pool,Session Pool 是 Session 的池化形式,专门针对多线程并发场景进行了优化,在多线程并发的情形下,Session Pool 能够合理地管理和分配连接资源,以提升系统性能与资源利用效率。Session 与 Session Pool 在功能方法层面保持一致,均为开发者在不同场景下与 IoTDB 数据库进行交互提供了有力支撑,开发者可依据实际需求灵活选用。 -### 依赖 +## 步骤概览 +使用Session的核心步骤: +1. 创建会话实例:初始化一个Session对象,为与IoTDB服务器的交互做准备。 +2. 打开连接:通过Session实例建立与IoTDB服务器的连接。 +3. 执行操作:在已建立的连接上执行数据写入、查询或元数据管理等操作。 +4. 关闭连接:完成操作后,关闭与IoTDB服务器的连接,释放资源。 -* JDK >= 1.8 -* Maven >= 3.6 +使用SessionPool的核心步骤: +1. 创建会话池实例:初始化一个SessionPool对象,用于管理多个Session实例。 +2. 执行操作:直接从SessionPool中获取Session实例,并执行数据库操作,无需每次都打开和关闭连接。 +3. 关闭会话池资源:在不再需要进行数据库操作时,关闭SessionPool,释放所有相关资源。 -### 在 MAVEN 中使用原生接口 +## 详细步骤 +本章节用于说明开发的核心流程,并未演示所有的参数和接口,如需了解全部功能及参数请参见: [详细接口说明](./Programming-Java-Native-API.md#详细接口说明) 或 查阅: [源码](https://github.com/apache/iotdb/tree/master/example/session/src/main/java/org/apache/iotdb) + +### 1. 创建maven项目 +创建一个maven项目,并导入以下依赖(JDK >= 1.8, Maven >= 3.6) ```xml org.apache.iotdb iotdb-session + ${project.version} ``` - -## 语法说明 - - - 对于 IoTDB-SQL 接口:传入的 SQL 参数需要符合 [语法规范](../User-Manual/Syntax-Rule.md#字面值常量) ,并且针对 JAVA 字符串进行反转义,如双引号前需要加反斜杠。(即:经 JAVA 转义之后与命令行执行的 SQL 语句一致。) - - 对于其他接口: - - 经参数传入的路径或路径前缀中的节点: 在 SQL 语句中需要使用反引号(`)进行转义的,此处均需要进行转义。 - - 经参数传入的标识符(如模板名):在 SQL 语句中需要使用反引号(`)进行转义的,均可以不用进行转义。 - - 语法说明相关代码示例可以参考:`example/session/src/main/java/org/apache/iotdb/SyntaxConventionRelatedExample.java` - -## 基本接口说明 - -下面将给出 Session 对应的接口的简要介绍和对应参数: - -### Session管理 - -* 初始化 Session - -``` java -// 全部使用默认配置 -session = new Session.Builder.build(); - -// 指定一个可连接节点 -session = - new Session.Builder() - .host(String host) - .port(int port) - .build(); - -// 指定多个可连接节点 -session = - new Session.Builder() - .nodeUrls(List nodeUrls) - .build(); - -// 其他配置项 -session = - new Session.Builder() - .fetchSize(int fetchSize) - .username(String username) - .password(String password) - .thriftDefaultBufferSize(int thriftDefaultBufferSize) - .thriftMaxFrameSize(int thriftMaxFrameSize) - .enableRedirection(boolean enableRedirection) - .version(Version version) - .build(); -``` - -其中,version 表示客户端使用的 SQL 语义版本,用于升级 0.13 时兼容 0.12 的 SQL 语义,可能取值有:`V_0_12`、`V_0_13`、`V_1_0`等。 - - -* 开启 Session - -``` java -void open() +### 2. 创建会话实例 +#### Session +方式一:通过Builder构造器创建Session实例 +```java +package org.example; + +import org.apache.iotdb.isession.util.Version; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.session.Session; + +public class IoTDBSessionExample { + public static void main(String[] args) { + Session session = + new Session.Builder() + .host("127.0.0.1") + .port(6667) + .username("root") + .password("root") + .version(Version.V_1_0) + .build(); + try { + session.open(); + } catch (IoTDBConnectionException e) { + // 连接Session异常 + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + } +} ``` - -* 开启 Session,并决定是否开启 RPC 压缩 - -``` java -void open(boolean enableRPCCompression) +方式二:通过new Session对象创建Session实例 +```java +package org.example; + +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.session.Session; + +public class IoTDBSessionExample { + public static void main(String[] args) { + Session session = new Session("127.0.0.1", 6667); + try { + session.open(); + } catch (IoTDBConnectionException e) { + // 连接Session异常 + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + } +} ``` -注意: 客户端的 RPC 压缩开启状态需和服务端一致 - -* 关闭 Session - -``` java -void close() +#### Session Pool +方式一:通过Builder来创建Session Pool实例 +```java +package org.example; + +import org.apache.iotdb.session.pool.SessionPool; + +public class IoTDBSessionExample { + public static void main(String[] args) { + SessionPool sessionPool = + new SessionPool.Builder() + .host("127.0.0.1") + .port(6667) + .user("root") + .password("root") + .maxSize(3) + .build(); + } +} ``` -* SessionPool - -我们提供了一个针对原生接口的连接池 (`SessionPool`),使用该接口时,你只需要指定连接池的大小,就可以在使用时从池中获取连接。 -如果超过 60s 都没得到一个连接的话,那么会打印一条警告日志,但是程序仍将继续等待。 - -当一个连接被用完后,他会自动返回池中等待下次被使用; -当一个连接损坏后,他会从池中被删除,并重建一个连接重新执行用户的操作; -你还可以像创建 Session 那样在创建 SessionPool 时指定多个可连接节点的 url,以保证分布式集群中客户端的高可用性。 - -对于查询操作: - -1. 使用 SessionPool 进行查询时,得到的结果集是`SessionDataSet`的封装类`SessionDataSetWrapper`; -2. 若对于一个查询的结果集,用户并没有遍历完且不再想继续遍历时,需要手动调用释放连接的操作`closeResultSet`; -3. 若对一个查询的结果集遍历时出现异常,也需要手动调用释放连接的操作`closeResultSet`. -4. 可以调用 `SessionDataSetWrapper` 的 `getColumnNames()` 方法得到结果集列名 - -使用示例可以参见 `session/src/test/java/org/apache/iotdb/session/pool/SessionPoolTest.java` - -或 `example/session/src/main/java/org/apache/iotdb/SessionPoolExample.java` - - -### 测点管理接口 - -#### Database 管理 +方式二:通过直接new SessionPool对象创建Session Pool实例 +```java +package org.example; -* 设置 database +import org.apache.iotdb.session.pool.SessionPool; -``` java -void setStorageGroup(String storageGroupId) +public class IoTDBSessionExample { + public static void main(String[] args) { + SessionPool sessionPool = + new SessionPool("127.0.0.1",6667,"root","root",100); + } +} ``` -* 删除单个或多个 database -``` java -void deleteStorageGroup(String storageGroup) -void deleteStorageGroups(List storageGroups) +### 执行数据库操作 +Session与Session Pool中的方法列表相同,本文档中以Session进行举例说明,如需用SessionPool,将Session对象替换为SessionPool即可。 + +#### 元数据操作 +```java +package org.example; + +import org.apache.iotdb.isession.util.Version; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.Session; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.file.metadata.enums.CompressionType; +import org.apache.tsfile.file.metadata.enums.TSEncoding; + +public class IoTDBSessionExample { + + public static void main(String[] args) { + Session session = + new Session.Builder() + .host("127.0.0.1") + .port(6667) + .username("root") + .password("root") + .version(Version.V_1_0) + .build(); + try { + session.open(); + } catch (IoTDBConnectionException e) { + // 连接Session异常 + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + + try { + // 1. 创建database + session.createDatabase("root.sg1"); + // 2. 创建一个时间序列 + session.createTimeseries( + "root.sg1.d1.s1", TSDataType.INT64, TSEncoding.RLE, CompressionType.SNAPPY); + // 3. 删除一个时间序列 + session.deleteTimeseries("root.sg1.d1.s1"); + } catch (IoTDBConnectionException | StatementExecutionException e) { + throw new RuntimeException(e); + } + try { + session.close(); + } catch (IoTDBConnectionException e) { + // solve exception + } + } +} ``` -#### 时间序列管理 - -* 创建单个或多个时间序列 - -``` java -void createTimeseries(String path, TSDataType dataType, - TSEncoding encoding, CompressionType compressor, Map props, - Map tags, Map attributes, String measurementAlias) - -void createMultiTimeseries(List paths, List dataTypes, - List encodings, List compressors, - List> propsList, List> tagsList, - List> attributesList, List measurementAliasList) +#### 数据写入 +在工业场景中,数据写入可以根据设备数量、写入频率和数据类型分为以下几类:单点实时写入、多设备批量写入、单设备历史数据补写、批量数据上传、对齐数据写入。不同的场景适用于不同的写入接口。下面按不同场景对写入接口进行介绍。 +##### 单点实时写入 +场景:单台设备的实时状态数据写入,更新频率较低,通常每次只写入一条记录。 + +适用接口: + +| 接口名称 | 功能描述 | +|-----------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------| +| `insertRecord(String deviceId, long time, List measurements, List types, List values)` | 插入单个设备多个测点的一个时刻的记录 | +| `insertRecord(String deviceId, long time, List measurements, List values)` | 同上,不需要指定数据类型,会根据传入的值进行推断。推断规则可在服务端配置,详细配置在iotdb-system.properties.template中的搜索`infer_type`关键字 | +| `insertAlignedRecord(String deviceId, long time, List measurements, List types, List values)` | 插入单个设备多个测点的一个时刻的记录,该设备为对齐设备 | +| `insertAlignedRecord(String deviceId, long time, List measurements, List values)` | 同上,不需要指定数据类型,会根据传入的值进行推断。推断规则可在服务端配置,详细配置在iotdb-system.properties.template中的搜索`infer_type`关键字 | + +代码案例: +```java +package org.example; + +import java.util.ArrayList; +import java.util.List; +import org.apache.iotdb.isession.util.Version; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.Session; +import org.apache.tsfile.enums.TSDataType; + +public class IoTDBSessionExample { + + public static void main(String[] args) { + Session session = + new Session.Builder() + .host("127.0.0.1") + .port(6667) + .username("root") + .password("root") + .version(Version.V_1_0) + .build(); + try { + session.open(); + } catch (IoTDBConnectionException e) { + // 连接Session异常 + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + String deviceId = "root.sg1.d1"; + List measurements = new ArrayList<>(); + List types = new ArrayList<>(); + measurements.add("s1"); + measurements.add("s2"); + measurements.add("s3"); + types.add(TSDataType.INT64); + types.add(TSDataType.INT64); + types.add(TSDataType.INT64); + + for (long time = 0; time < 100; time++) { + List values = new ArrayList<>(); + values.add(1L); + values.add(2L); + values.add(3L); + try { + session.insertRecord(deviceId, time, measurements, types, values); + } catch (IoTDBConnectionException | StatementExecutionException e) { + // solve exception + } + } + try { + session.close(); + } catch (IoTDBConnectionException e) { + // solve exception + } + } +} ``` -* 创建对齐时间序列 - -``` -void createAlignedTimeseries(String prefixPath, List measurements, - List dataTypes, List encodings, - List compressors, List measurementAliasList); +##### 多设备批量写入 +场景:多个设备的实时状态或传感器数据批量写入,适合工厂或车间环境。 + +适用接口: + +| 接口名称 | 功能描述 | +|-----------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------| +| `insertRecords(List deviceIds, List times, List> measurementsList, List> typesList, List> valuesList)` | 插入多个设备,每个设备多个测点的一个时刻的记录 | +| `insertRecords(List deviceIds, List times, List> measurementsList, List> valuesList)` | 同上,不需要指定数据类型,会根据传入的值进行推断。推断规则可在服务端配置,详细配置在iotdb-system.properties.template中的搜索`infer_type`关键字 | +| `insertAlignedRecords(List deviceIds, List times, List> measurementsList, List> typesList, List> valuesList)` | 插入多个设备,每个设备多个测点的一个时刻的记录。每个设备为对齐设备 | +| `insertAlignedRecords(List deviceIds, List times, List> measurementsList, List> valuesList)` | 同上,不需要指定数据类型,会根据传入的值进行推断。推断规则可在服务端配置,详细配置在iotdb-system.properties.template中的搜索`infer_type`关键字 | + + +代码案例: +```java +package org.example; + +import java.util.ArrayList; +import java.util.List; +import org.apache.iotdb.isession.util.Version; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.Session; +import org.apache.tsfile.enums.TSDataType; + +public class IoTDBSessionExample { + + public static void main(String[] args) { + Session session = + new Session.Builder() + .host("127.0.0.1") + .port(6667) + .username("root") + .password("root") + .version(Version.V_1_0) + .build(); + try { + session.open(); + } catch (IoTDBConnectionException e) { + // 连接Session异常 + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + String deviceId = "root.sg1.d1.s1"; + List measurements = new ArrayList<>(); + measurements.add("s1"); + measurements.add("s2"); + measurements.add("s3"); + List deviceIds = new ArrayList<>(); + List> measurementsList = new ArrayList<>(); + List> valuesList = new ArrayList<>(); + List timestamps = new ArrayList<>(); + List> typesList = new ArrayList<>(); + + for (long time = 0; time < 500; time++) { + List values = new ArrayList<>(); + List types = new ArrayList<>(); + values.add(1L); + values.add(2L); + values.add(3L); + types.add(TSDataType.INT64); + types.add(TSDataType.INT64); + types.add(TSDataType.INT64); + + deviceIds.add(deviceId); + measurementsList.add(measurements); + valuesList.add(values); + typesList.add(types); + timestamps.add(time); + if (time != 0 && time % 100 == 0) { + try { + session.insertRecords(deviceIds, timestamps, measurementsList, typesList, valuesList); + } catch (IoTDBConnectionException | StatementExecutionException e) { + // solve exception + } + deviceIds.clear(); + measurementsList.clear(); + valuesList.clear(); + typesList.clear(); + timestamps.clear(); + } + } + + try { + session.insertRecords(deviceIds, timestamps, measurementsList, typesList, valuesList); + } catch (IoTDBConnectionException | StatementExecutionException e) { + // solve exception + } + try { + session.close(); + } catch (IoTDBConnectionException e) { + // solve exception + } + } +} ``` -注意:目前**暂不支持**使用传感器别名。 - -* 删除一个或多个时间序列 - -``` java -void deleteTimeseries(String path) -void deleteTimeseries(List paths) +##### 单设备历史数据补写 + +场景:单台设备采集数据中存在时间间隔,需要一次性补充多条历史记录。 + +适用接口: + +| 接口名称 | 功能描述 | +|-----------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------| +| `insertRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> typesList, List> valuesList)` | 插入单设备的多条记录 | +| `insertRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> typesList, List> valuesList, boolean haveSorted)` | 插入单设备的排序记录,其数据已经排好序,无乱序情况 | +| `insertRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> valuesList)` | 同上,不需要指定数据类型,会根据传入的值进行推断。推断规则可在服务端配置,详细配置在iotdb-system.properties.template中的搜索`infer_type`关键字 | +| `insertAlignedRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> typesList, List> valuesList)` | 插入单设备的多条记录,该设备为对齐设备 | +| `insertAlignedRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> typesList, List> valuesList, boolean haveSorted)` | 插入单设备的多条记录,该设备为对齐设备,其数据已经排好序,无乱序情况 | +| `insertAlignedRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> valuesList)` | 同上,不需要指定数据类型,会根据传入的值进行推断。推断规则可在服务端配置,详细配置在iotdb-system.properties.template中的搜索`infer_type`关键字 | + +代码案例: +```java +package org.example; + +import java.util.ArrayList; +import java.util.List; +import org.apache.iotdb.isession.util.Version; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.Session; +import org.apache.tsfile.enums.TSDataType; + +public class IoTDBSessionExample { + + public static void main(String[] args) throws IoTDBConnectionException, StatementExecutionException { + Session session = + new Session.Builder() + .host("127.0.0.1") + .port(6667) + .username("root") + .password("root") + .version(Version.V_1_0) + .build(); + try { + session.open(); + } catch (IoTDBConnectionException e) { + // 连接Session异常 + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + String deviceId = "root.sg1.d1.s1"; + List measurements = new ArrayList<>(); + measurements.add("s1"); + measurements.add("s2"); + measurements.add("s3"); + List> measurementsList = new ArrayList<>(); + List> valuesList = new ArrayList<>(); + List timestamps = new ArrayList<>(); + List> typesList = new ArrayList<>(); + + for (long time = 0; time < 10; time ++) { + List values = new ArrayList<>(); + List types = new ArrayList<>(); + values.add(1L); + values.add(2L); + values.add(3L); + types.add(TSDataType.INT64); + types.add(TSDataType.INT64); + types.add(TSDataType.INT64); + measurementsList.add(measurements); + valuesList.add(values); + typesList.add(types); + timestamps.add(time); + } + + session.insertRecordsOfOneDevice(deviceId, timestamps, measurementsList, typesList, valuesList); + try { + session.close(); + } catch (IoTDBConnectionException e) { + // solve exception + } + } +} ``` - -* 检测时间序列是否存在 - -``` java -boolean checkTimeseriesExists(String path) +##### 批量数据上传 +场景:多个设备的大量数据同时上传,适合大规模分布式数据接入。 + +适用接口: + +| 接口名称 | 功能描述 | +|-----------------------------------------------------------------------------------------|------------------------------------------| +| `insertTablet(Tablet tablet)` | 插入单个设备多个测点,每个测点多个时刻的数据 | +| `insertTablet(Tablet tablet, boolean sorted)` | 插入单个设备多个测点,每个测点多个时刻的数据,其数据已经排好序 | +| `insertTablets(Map tablets)` | 插入单个设备多个测点,每个测点多个时刻的数据 | +| `insertTablets(Map tablets, boolean sorted)` | 插入单个设备多个测点,每个测点多个时刻的数据,其数据已经排好序 | +| `insertAlignedTablet(Tablet tablet)` | 插入单个设备多个测点,每个测点多个时刻的数据,该设备为对齐设备 | +| `insertAlignedTablet(Tablet tablet, boolean sorted)` | 插入单个设备多个测点,每个测点多个时刻的数据,该设备为对齐设备,其数据已经排好序 | +| `insertAlignedTablets(Map tablets)` | 插入多个设备多个测点,每个测点多个时刻的数据 | +| `insertAlignedTablets(Map tablets, boolean sorted)` | 插入多个设备多个测点,每个测点多个时刻的数据,其数据已经排好序 | + +代码案例: +```java +package org.example; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import org.apache.iotdb.isession.util.Version; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.Session; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.write.record.Tablet; +import org.apache.tsfile.write.schema.MeasurementSchema; + +public class IoTDBSessionExample { + + public static void main(String[] args) throws IoTDBConnectionException, StatementExecutionException { + Session session = + new Session.Builder() + .host("127.0.0.1") + .port(6667) + .username("root") + .password("root") + .version(Version.V_1_0) + .build(); + try { + session.open(); + } catch (IoTDBConnectionException e) { + // 连接Session异常 + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + String deviceId = "root.sg1.d1.s1"; + /* + * A Tablet example: + * device1 + * time s1, s2, s3 + * 1, 1, 1, 1 + * 2, 2, 2, 2 + * 3, 3, 3, 3 + */ + // The schema of measurements of one device + // only measurementId and data type in MeasurementSchema take effects in Tablet + List schemaList = new ArrayList<>(); + schemaList.add(new MeasurementSchema("s1", TSDataType.INT64)); + schemaList.add(new MeasurementSchema("s2", TSDataType.INT64)); + schemaList.add(new MeasurementSchema("s3", TSDataType.INT64)); + + Tablet tablet = new Tablet(deviceId, schemaList, 100); + + // Method 1 to add tablet data + long timestamp = System.currentTimeMillis(); + Random random = new Random(); + for (long row = 0; row < 100; row++) { + int rowIndex = tablet.rowSize++; + tablet.addTimestamp(rowIndex, timestamp); + for (int s = 0; s < 3; s++) { + long value = random.nextLong(); + tablet.addValue(schemaList.get(s).getMeasurementId(), rowIndex, value); + } + if (tablet.rowSize == tablet.getMaxRowNumber()) { + session.insertTablet(tablet, true); + tablet.reset(); + } + timestamp++; + } + + if (tablet.rowSize != 0) { + session.insertTablet(tablet); + tablet.reset(); + } + try { + session.close(); + } catch (IoTDBConnectionException e) { + // solve exception + } + } +} ``` -#### 元数据模版 - -* 创建元数据模板,可以通过先后创建 Template、MeasurementNode 的对象,描述模板内物理量结构与类型、编码方式、压缩方式等信息,并通过以下接口创建模板 - -``` java -public void createSchemaTemplate(Template template); - -Class Template { - private String name; - private boolean directShareTime; - Map children; - public Template(String name, boolean isShareTime); +#### 数据查询 +```java +package org.example; + +import java.util.ArrayList; +import java.util.List; +import org.apache.iotdb.common.rpc.thrift.TAggregationType; +import org.apache.iotdb.isession.SessionDataSet; +import org.apache.iotdb.isession.util.Version; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.Session; + +public class IoTDBSessionExample { + private static final String ROOT_SG1_D1_S1 = "root.sg1.d1.s1"; + private static final String ROOT_SG1_D1_S2 = "root.sg1.d1.s2"; + private static final String ROOT_SG1_D1_S3 = "root.sg1.d1.s3"; - public void addToTemplate(Node node); - public void deleteFromTemplate(String name); - public void setShareTime(boolean shareTime); -} - -Abstract Class Node { - private String name; - public void addChild(Node node); - public void deleteChild(Node node); -} - -Class MeasurementNode extends Node { - TSDataType dataType; - TSEncoding encoding; - CompressionType compressor; - public MeasurementNode(String name, - TSDataType dataType, - TSEncoding encoding, - CompressionType compressor); + public static void main(String[] args) throws IoTDBConnectionException, StatementExecutionException { + Session session = + new Session.Builder() + .host("127.0.0.1") + .port(6667) + .username("root") + .password("root") + .version(Version.V_1_0) + .build(); + try { + session.open(); + } catch (IoTDBConnectionException e) { + // 连接Session异常 + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + + // 1. 使用sql查询原始数据 + try (SessionDataSet dataSet = session.executeQueryStatement("select * from root.sg1.d1")) { + System.out.println(dataSet.getColumnNames()); + dataSet.setFetchSize(1024); // default is 10000 + while (dataSet.hasNext()) { + System.out.println(dataSet.next()); + } + } + + // 2.指定测点、开始时间、结束时间、超时时间进行查询 + List paths = new ArrayList<>(); + paths.add(ROOT_SG1_D1_S1); + paths.add(ROOT_SG1_D1_S2); + paths.add(ROOT_SG1_D1_S3); + long startTime = 10L; + long endTime = 200L; + long timeOut = 60000; + + try (SessionDataSet dataSet = session.executeRawDataQuery(paths, startTime, endTime, timeOut)) { + System.out.println(dataSet.getColumnNames()); + dataSet.setFetchSize(1024); + while (dataSet.hasNext()) { + System.out.println(dataSet.next()); + } + } + + // 3. 最新值查询 + try (SessionDataSet sessionDataSet = session.executeLastDataQuery(paths, 3, 60000)) { + System.out.println(sessionDataSet.getColumnNames()); + sessionDataSet.setFetchSize(1024); + while (sessionDataSet.hasNext()) { + System.out.println(sessionDataSet.next()); + } + } + + // 4. 聚合查询 + List aggregations = new ArrayList<>(); + aggregations.add(TAggregationType.COUNT); + aggregations.add(TAggregationType.SUM); + aggregations.add(TAggregationType.MAX_VALUE); + try (SessionDataSet sessionDataSet = session.executeAggregationQuery(paths, aggregations)) { + System.out.println(sessionDataSet.getColumnNames()); + sessionDataSet.setFetchSize(1024); + while (sessionDataSet.hasNext()) { + System.out.println(sessionDataSet.next()); + } + } + + // 5. 分组查询 + try (SessionDataSet sessionDataSet = + session.executeAggregationQuery(paths, aggregations, 0, 100, 10, 20)) { + System.out.println(sessionDataSet.getColumnNames()); + sessionDataSet.setFetchSize(1024); + while (sessionDataSet.hasNext()) { + System.out.println(sessionDataSet.next()); + } + } + } } ``` -通过上述类的实例描述模板时,Template 内应当仅能包含单层的 MeasurementNode,具体可以参见如下示例: - -``` java -MeasurementNode nodeX = new MeasurementNode("x", TSDataType.FLOAT, TSEncoding.RLE, CompressionType.SNAPPY); -MeasurementNode nodeY = new MeasurementNode("y", TSDataType.FLOAT, TSEncoding.RLE, CompressionType.SNAPPY); -MeasurementNode nodeSpeed = new MeasurementNode("speed", TSDataType.DOUBLE, TSEncoding.GORILLA, CompressionType.SNAPPY); - -// This is the template we suggest to implement -Template flatTemplate = new Template("flatTemplate"); -template.addToTemplate(nodeX); -template.addToTemplate(nodeY); -template.addToTemplate(nodeSpeed); - -createSchemaTemplate(flatTemplate); -``` - -* 完成模板挂载操作后,可以通过如下的接口在给定的设备上使用模板注册序列,或者也可以直接向相应的设备写入数据以自动使用模板注册序列。 - -``` java -void createTimeseriesUsingSchemaTemplate(List devicePathList) -``` - -* 将名为'templateName'的元数据模板挂载到'prefixPath'路径下,在执行这一步之前,你需要创建名为'templateName'的元数据模板 -* **请注意,我们强烈建议您将模板设置在 database 或 database 下层的节点中,以更好地适配未来版本更新及各模块的协作** - -``` java -void setSchemaTemplate(String templateName, String prefixPath) -``` - -- 将模板挂载到 MTree 上之后,你可以随时查询所有模板的名称、某模板被设置到 MTree 的所有路径、所有正在使用某模板的所有路径,即如下接口: - -``` java -/** @return All template names. */ -public List showAllTemplates(); - -/** @return All paths have been set to designated template. */ -public List showPathsTemplateSetOn(String templateName); - -/** @return All paths are using designated template. */ -public List showPathsTemplateUsingOn(String templateName) -``` - -- 如果你需要删除某一个模板,请确保在进行删除之前,MTree 上已经没有节点被挂载了模板,对于已经被挂载模板的节点,可以用如下接口卸载模板; - - -``` java -void unsetSchemaTemplate(String prefixPath, String templateName); -public void dropSchemaTemplate(String templateName); -``` - -* 请注意,如果一个子树中有多个孩子节点需要使用模板,可以在其共同父母节点上使用 setSchemaTemplate 。而只有在已有数据点插入模板对应的物理量时,模板才会被设置为激活状态,进而被 show timeseries 等查询检测到。 -* 卸载'prefixPath'路径下的名为'templateName'的元数据模板。你需要保证给定的路径'prefixPath'下需要有名为'templateName'的元数据模板。 - -注意:目前不支持从曾经在'prefixPath'路径及其后代节点使用模板插入数据后(即使数据已被删除)卸载模板。 - - -### 数据写入接口 - -推荐使用 insertTablet 帮助提高写入效率 - -* 插入一个 Tablet,Tablet 是一个设备若干行数据块,每一行的列都相同 - * **写入效率高** - * **支持批量写入** - * **支持写入空值**:空值处可以填入任意值,然后通过 BitMap 标记空值 - -``` java -void insertTablet(Tablet tablet) - -public class Tablet { - /** deviceId of this tablet */ - public String prefixPath; - /** the list of measurement schemas for creating the tablet */ - private List schemas; - /** timestamps in this tablet */ - public long[] timestamps; - /** each object is a primitive type array, which represents values of one measurement */ - public Object[] values; - /** each bitmap represents the existence of each value in the current column. */ - public BitMap[] bitMaps; - /** the number of rows to include in this tablet */ - public int rowSize; - /** the maximum number of rows for this tablet */ - private int maxRowNumber; - /** whether this tablet store data of aligned timeseries or not */ - private boolean isAligned; +#### 数据删除 +```java +package org.example; + +import java.util.Collections; +import org.apache.iotdb.isession.util.Version; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.Session; + +public class IoTDBSessionExample { + private static final String ROOT_SG1_D1_S1 = "root.sg1.d1.s1"; + + public static void main(String[] args) throws IoTDBConnectionException, StatementExecutionException { + Session session = + new Session.Builder() + .host("127.0.0.1") + .port(6667) + .username("root") + .password("root") + .version(Version.V_1_0) + .build(); + try { + session.open(); + } catch (IoTDBConnectionException e) { + // 连接Session异常 + System.out.println("Connecting to the IoTDB failed."); + } + System.out.println("Connecting to the IoTDB succeeded."); + + // 1. 精确删除某个时间点的数据 + String path = ROOT_SG1_D1_S1; + long deleteTime = 99; + session.deleteData(path, deleteTime); + + // 2. 删除某个时间段的数据 + long startTime = 1; + session.deleteData(Collections.singletonList(path),startTime, deleteTime); + + // 3. 删除某个测点 + session.deleteTimeseries(path); + } } ``` -* 插入多个 Tablet - -``` java -void insertTablets(Map tablets) -``` - -* 插入一个 Record,一个 Record 是一个设备一个时间戳下多个测点的数据。这里的 value 是 Object 类型,相当于提供了一个公用接口,后面可以通过 TSDataType 将 value 强转为原类型 - - 其中,Object 类型与 TSDataType 类型的对应关系如下表所示: - - | TSDataType | Object | - |------------|--------------| - | BOOLEAN | Boolean | - | INT32 | Integer | - | DATE | LocalDate | - | INT64 | Long | - | TIMESTAMP | Long | - | FLOAT | Float | - | DOUBLE | Double | - | TEXT | String, Binary | - | STRING | String, Binary | - | BLOB | Binary | - -``` java -void insertRecord(String prefixPath, long time, List measurements, - List types, List values) -``` - -* 插入多个 Record - -``` java -void insertRecords(List deviceIds, - List times, - List> measurementsList, - List> typesList, - List> valuesList) -``` - -* 插入同属于一个 device 的多个 Record - -``` java -void insertRecordsOfOneDevice(String deviceId, List times, - List> measurementsList, List> typesList, - List> valuesList) -``` - -#### 带有类型推断的写入 - -当数据均是 String 类型时,我们可以使用如下接口,根据 value 的值进行类型推断。例如:value 为 "true" ,就可以自动推断为布尔类型。value 为 "3.2" ,就可以自动推断为数值类型。服务器需要做类型推断,可能会有额外耗时,速度较无需类型推断的写入慢 - -* 插入一个 Record,一个 Record 是一个设备一个时间戳下多个测点的数据 - -``` java -void insertRecord(String prefixPath, long time, List measurements, List values) -``` - -* 插入多个 Record - -``` java -void insertRecords(List deviceIds, List times, - List> measurementsList, List> valuesList) -``` - -* 插入同属于一个 device 的多个 Record - -``` java -void insertStringRecordsOfOneDevice(String deviceId, List times, - List> measurementsList, List> valuesList) -``` - -#### 对齐时间序列的写入 - -对齐时间序列的写入使用 insertAlignedXXX 接口,其余与上述接口类似: - -* insertAlignedRecord -* insertAlignedRecords -* insertAlignedRecordsOfOneDevice -* insertAlignedStringRecordsOfOneDevice -* insertAlignedTablet -* insertAlignedTablets - -### 数据删除接口 - -* 删除一个或多个时间序列在某个时间点前或这个时间点的数据 - -``` java -void deleteData(String path, long endTime) -void deleteData(List paths, long endTime) -``` - -### 数据查询接口 - -* 时间序列原始数据范围查询: - - 指定的查询时间范围为左闭右开区间,包含开始时间但不包含结束时间。 - -``` java -SessionDataSet executeRawDataQuery(List paths, long startTime, long endTime); -``` - -* 最新点查询: - - 查询最后一条时间戳大于等于某个时间点的数据。 - ``` java - SessionDataSet executeLastDataQuery(List paths, long lastTime); - ``` - - 快速查询单设备下指定序列最新点,支持重定向;如果您确认使用的查询路径是合法的,可将`isLegalPathNodes`置为true以避免路径校验带来的性能损失。 - ``` java - SessionDataSet executeLastDataQueryForOneDevice( - String db, String device, List sensors, boolean isLegalPathNodes); - ``` - -* 聚合查询: - - 支持指定查询时间范围。指定的查询时间范围为左闭右开区间,包含开始时间但不包含结束时间。 - - 支持按照时间区间分段查询。 - -``` java -SessionDataSet executeAggregationQuery(List paths, List aggregations); - -SessionDataSet executeAggregationQuery( - List paths, List aggregations, long startTime, long endTime); - -SessionDataSet executeAggregationQuery( - List paths, - List aggregations, - long startTime, - long endTime, - long interval); - -SessionDataSet executeAggregationQuery( - List paths, - List aggregations, - long startTime, - long endTime, - long interval, - long slidingStep); -``` - -* 直接执行查询语句 - -``` java -SessionDataSet executeQueryStatement(String sql) -``` - -### 数据订阅 - -#### 1 Topic 管理 +## 详细接口说明 +### 参数列表 +#### Session +| 字段名 | 类型 | 说明 | +|--------------------------------|-------------------------------|----------------------------------------------------------------------| +| `nodeUrls` | `List` | 数据库节点的 URL 列表,支持多节点连接 | +| `username` | `String` | 用户名 | +| `password` | `String` | 密码 | +| `fetchSize` | `int` | 查询结果的默认批量返回大小 | +| `useSSL` | `boolean` | 是否启用 SSL | +| `trustStore` | `String` | 信任库路径 | +| `trustStorePwd` | `String` | 信任库密码 | +| `queryTimeoutInMs` | `long` | 查询的超时时间,单位毫秒 | +| `enableRPCCompression` | `boolean` | 是否启用 RPC 压缩 | +| `connectionTimeoutInMs` | `int` | 连接超时时间,单位毫秒 | +| `zoneId` | `ZoneId` | 会话的时区设置 | +| `thriftDefaultBufferSize` | `int` | Thrift 默认缓冲区大小 | +| `thriftMaxFrameSize` | `int` | Thrift 最大帧大小 | +| `defaultEndPoint` | `TEndPoint` | 默认的数据库端点信息 | +| `defaultSessionConnection` | `SessionConnection` | 默认的会话连接对象 | +| `isClosed` | `boolean` | 当前会话是否已关闭 | +| `enableRedirection` | `boolean` | 是否启用重定向功能 | +| `enableRecordsAutoConvertTablet` | `boolean` | 是否启用记录自动转换为 Tablet 的功能 | +| `deviceIdToEndpoint` | `Map` | 设备 ID 和数据库端点的映射关系 | +| `endPointToSessionConnection` | `Map` | 数据库端点和会话连接的映射关系 | +| `executorService` | `ScheduledExecutorService` | 用于定期更新节点列表的线程池 | +| `availableNodes` | `INodeSupplier` | 可用节点的供应器 | +| `enableQueryRedirection` | `boolean` | 是否启用查询重定向功能 | +| `version` | `Version` | 客户端的版本号,用于与服务端的兼容性判断 | +| `enableAutoFetch` | `boolean` | 是否启用自动获取功能 | +| `maxRetryCount` | `int` | 最大重试次数 | +| `retryIntervalInMs` | `long` | 重试的间隔时间,单位毫秒 | +需要额外说明的参数 + +nodeUrls: 多节点 URL 列表,支持自动切换到下一个可用节点。格式为 ip:port。 + +queryTimeoutInMs: 如果为负数,则表示使用服务端默认配置;如果为 0,则禁用查询超时功能。 + +enableRPCCompression: 启用后,RPC 数据传输将启用压缩,适用于高带宽延迟场景。 + +zoneId: 会话时区,可用值参考 Java 的 ZoneId 标准,例如 Asia/Shanghai。 + +#### SessionPool +| 字段名 | 类型 | 说明 | +|--------------------------------|-------------------------------|----------------------------------------------------------------------| +| `host` | `String` | 数据库主机地址 | +| `port` | `int` | 数据库端口 | +| `user` | `String` | 数据库用户名 | +| `password` | `String` | 数据库密码 | +| `nodeUrls` | `List` | 多节点的 URL 列表 | +| `maxSize` | `int` | 连接池的最大连接数 | +| `fetchSize` | `int` | 查询结果的默认批量返回大小 | +| `waitToGetSessionTimeoutInMs` | `long` | 获取连接的等待超时时间(毫秒) | +| `enableCompression` | `boolean` | 是否启用 RPC 压缩 | +| `enableRedirection` | `boolean` | 是否启用重定向功能 | +| `enableRecordsAutoConvertTablet` | `boolean` | 是否启用记录自动转换为 Tablet 的功能 | +| `thriftDefaultBufferSize` | `int` | Thrift 默认缓冲区大小 | +| `thriftMaxFrameSize` | `int` | Thrift 最大帧大小 | +| `queryTimeoutInMs` | `long` | 查询超时时间,单位毫秒 | +| `version` | `Version` | 客户端版本号 | +| `connectionTimeoutInMs` | `int` | 连接超时时间,单位毫秒 | +| `zoneId` | `ZoneId` | 时区设置 | +| `useSSL` | `boolean` | 是否启用 SSL | +| `trustStore` | `String` | 信任库路径 | +| `trustStorePwd` | `String` | 信任库密码 | +| `enableQueryRedirection` | `boolean` | 是否启用查询重定向功能 | +| `executorService` | `ScheduledExecutorService` | 定期更新节点列表的线程池 | +| `availableNodes` | `INodeSupplier` | 可用节点的供应器 | +| `maxRetryCount` | `int` | 最大重试次数 | +| `retryIntervalInMs` | `long` | 重试间隔时间,单位毫秒 | +| `closed` | `boolean` | 当前连接池是否已关闭 | +| `queue` | `ConcurrentLinkedDeque` | 可用会话连接的队列 | +| `occupied` | `ConcurrentMap` | 已占用的会话连接映射 | +| `deviceIdToEndpoint` | `Map` | 设备 ID 到数据库端点的映射 | +| `formattedNodeUrls` | `String` | 格式化后的节点 URL 字符串 | +需要额外说明的字段 + +nodeUrls:一个包含多个节点地址的列表,用于支持集群环境的连接。格式为 ["host1:port1", "host2:port2"]。 + +queue:保存所有可用的会话连接。当需要连接时会从队列中取出。 + +occupied:用于记录正在被占用的连接,以便在释放连接时可以正确回收。 + +maxRetryCount 和 retryIntervalInMs:用于控制重试策略,当操作失败时会按设定的间隔重试指定的次数。 + + +### 函数列表 +#### 会话管理 +| 方法名 | 功能描述 | 参数解释 | +|-----------------------------------------------------------------------------------------|--------------------------------------------|------------------------------------------------------------------------------------------------------------| +| `open()` | 打开会话 | 无参数 | +| `open(boolean enableRPCCompression)` | 打开会话并启用RPC压缩 | `enableRPCCompression`: 是否启用RPC压缩 | +| `open(boolean enableRPCCompression, int connectionTimeoutInMs)` | 打开会话并设置连接超时 | `enableRPCCompression`: 是否启用RPC压缩,`connectionTimeoutInMs`: 连接超时时间(毫秒) | +| `open(boolean enableRPCCompression, int connectionTimeoutInMs, Map deviceIdToEndpoint, INodeSupplier nodeSupplier)` | 打开会话并配置节点 | `enableRPCCompression`: 是否启用RPC压缩,`connectionTimeoutInMs`: 超时时间,`deviceIdToEndpoint`: 设备映射 | +| `close()` | 关闭会话 | 无参数 | +| `getVersion()` | 获取会话版本 | 无参数 | +| `setVersion(Version version)` | 设置会话版本 | `version`: 要设置的版本 | +| `getTimeZone()` | 获取当前时区 | 无参数 | +| `setTimeZone(String zoneId)` | 设置时区 | `zoneId`: 时区标识符(例如 `Asia/Shanghai`) | +| `setTimeZoneOfSession(String zoneId)` | 设置会话时区 | `zoneId`: 时区标识符 | +| `getFetchSize()` | 获取批量查询的记录数限制 | 无参数 | +| `setFetchSize(int fetchSize)` | 设置批量查询的记录数限制 | `fetchSize`: 每批查询返回的最大记录数 | +| `setQueryTimeout(long timeoutInMs)` | 设置查询超时时间 | `timeoutInMs`: 查询的超时时间(毫秒) | +| `getQueryTimeout()` | 获取查询超时时间 | 无参数 | +| `isEnableQueryRedirection()` | 检查是否启用查询重定向 | 无参数 | +| `setEnableQueryRedirection(boolean enableQueryRedirection)` | 设置查询重定向 | `enableQueryRedirection`: 是否启用查询重定向 | +| `isEnableRedirection()` | 检查是否启用重定向 | 无参数 | +| `setEnableRedirection(boolean enableRedirection)` | 设置重定向 | `enableRedirection`: 是否启用重定向 | + + +#### 元数据管理 +| 方法名 | 功能描述 | 参数解释 | +|-----------------------------------------------------------------------------------------|--------------------------------------------|------------------------------------------------------------------------------------------------------------| +| `createDatabase(String database)` | 创建数据库 | `database`: 数据库名称 | +| `deleteDatabase(String database)` | 删除指定数据库 | `database`: 要删除的数据库名称 | +| `deleteDatabases(List databases)` | 批量删除数据库 | `databases`: 要删除的数据库名称列表 | +| `createTimeseries(String path, TSDataType dataType, TSEncoding encoding, CompressionType compressor)` | 创建单个时间序列 | `path`: 时间序列路径,`dataType`: 数据类型,`encoding`: 编码类型,`compressor`: 压缩类型 | +| `createAlignedTimeseries(...)` | 创建对齐时间序列 | 设备ID、测点列表、数据类型列表、编码列表、压缩类型列表 | +| `createMultiTimeseries(...)` | 批量创建时间序列 | 多个路径、数据类型、编码、压缩类型、属性、标签、别名等 | +| `deleteTimeseries(String path)` | 删除时间序列 | `path`: 要删除的时间序列路径 | +| `deleteTimeseries(List paths)` | 批量删除时间序列 | `paths`: 要删除的时间序列路径列表 | +| `setSchemaTemplate(String templateName, String prefixPath)` | 设置模式模板 | `templateName`: 模板名称,`prefixPath`: 应用模板的路径 | +| `createSchemaTemplate(Template template)` | 创建模式模板 | `template`: 模板对象 | +| `dropSchemaTemplate(String templateName)` | 删除模式模板 | `templateName`: 要删除的模板名称 | +| `addAlignedMeasurementsInTemplate(...)` | 添加对齐测点到模板 | 模板名称、测点路径列表、数据类型、编码类型、压缩类型 | +| `addUnalignedMeasurementsInTemplate(...)` | 添加非对齐测点到模板 | 同上 | +| `deleteNodeInTemplate(String templateName, String path)` | 删除模板中的节点 | `templateName`: 模板名称,`path`: 要删除的路径 | +| `countMeasurementsInTemplate(String name)` | 统计模板中测点数量 | `name`: 模板名称 | +| `isMeasurementInTemplate(String templateName, String path)` | 检查模板中是否存在某测点 | `templateName`: 模板名称,`path`: 测点路径 | +| `isPathExistInTemplate(String templateName, String path)` | 检查模板中路径是否存在 | 同上 | +| `showMeasurementsInTemplate(String templateName)` | 显示模板中的测点 | `templateName`: 模板名称 | +| `showMeasurementsInTemplate(String templateName, String pattern)` | 按模式显示模板中的测点 | `templateName`: 模板名称,`pattern`: 匹配模式 | +| `showAllTemplates()` | 显示所有模板 | 无参数 | +| `showPathsTemplateSetOn(String templateName)` | 显示模板应用的路径 | `templateName`: 模板名称 | +| `showPathsTemplateUsingOn(String templateName)` | 显示模板实际使用的路径 | 同上 | +| `unsetSchemaTemplate(String prefixPath, String templateName)` | 取消路径的模板设置 | `prefixPath`: 路径,`templateName`: 模板名称 | + + +#### 数据写入 +| 方法名 | 功能描述 | 参数解释 | +|-----------------------------------------------------------------------------------------|--------------------------------------------|------------------------------------------------------------------------------------------------------------| +| `insertRecord(String deviceId, long time, List measurements, List types, Object... values)` | 插入单条记录 | `deviceId`: 设备ID,`time`: 时间戳,`measurements`: 测点列表,`types`: 数据类型列表,`values`: 值列表 | +| `insertRecord(String deviceId, long time, List measurements, List values)` | 插入单条记录 | `deviceId`: 设备ID,`time`: 时间戳,`measurements`: 测点列表,`values`: 值列表 | +| `insertRecords(List deviceIds, List times, List> measurementsList, List> valuesList)` | 插入多条记录 | `deviceIds`: 设备ID列表,`times`: 时间戳列表,`measurementsList`: 测点列表列表,`valuesList`: 值列表 | +| `insertRecords(List deviceIds, List times, List> measurementsList, List> typesList, List> valuesList)` | 插入多条记录 | 同上,增加 `typesList`: 数据类型列表 | +| `insertRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> typesList, List> valuesList)` | 插入单设备的多条记录 | `deviceId`: 设备ID,`times`: 时间戳列表,`measurementsList`: 测点列表列表,`typesList`: 类型列表,`valuesList`: 值列表 | +| `insertRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> typesList, List> valuesList, boolean haveSorted)` | 插入排序后的单设备多条记录 | 同上,增加 `haveSorted`: 数据是否已排序 | +| `insertStringRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> valuesList)` | 插入字符串格式的单设备记录 | `deviceId`: 设备ID,`times`: 时间戳列表,`measurementsList`: 测点列表,`valuesList`: 值列表 | +| `insertStringRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> valuesList, boolean haveSorted)` | 插入排序的字符串格式单设备记录 | 同上,增加 `haveSorted`: 数据是否已排序 | +| `insertAlignedRecord(String deviceId, long time, List measurements, List types, List values)` | 插入单条对齐记录 | `deviceId`: 设备ID,`time`: 时间戳,`measurements`: 测点列表,`types`: 类型列表,`values`: 值列表 | +| `insertAlignedRecord(String deviceId, long time, List measurements, List values)` | 插入字符串格式的单条对齐记录 | `deviceId`: 设备ID,`time`: 时间戳,`measurements`: 测点列表,`values`: 值列表 | +| `insertAlignedRecords(List deviceIds, List times, List> measurementsList, List> valuesList)` | 插入多条对齐记录 | `deviceIds`: 设备ID列表,`times`: 时间戳列表,`measurementsList`: 测点列表,`valuesList`: 值列表 | +| `insertAlignedRecords(List deviceIds, List times, List> measurementsList, List> typesList, List> valuesList)` | 插入多条对齐记录 | 同上,增加 `typesList`: 数据类型列表 | +| `insertAlignedRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> typesList, List> valuesList)` | 插入单设备的多条对齐记录 | 同上 | +| `insertAlignedRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> typesList, List> valuesList, boolean haveSorted)` | 插入排序的单设备多条对齐记录 | 同上,增加 `haveSorted`: 数据是否已排序 | +| `insertAlignedStringRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> valuesList)` | 插入字符串格式的单设备对齐记录 | `deviceId`: 设备ID,`times`: 时间戳列表,`measurementsList`: 测点列表,`valuesList`: 值列表 | +| `insertAlignedStringRecordsOfOneDevice(String deviceId, List times, List> measurementsList, List> valuesList, boolean haveSorted)` | 插入排序的字符串格式单设备对齐记录 | 同上,增加 `haveSorted`: 数据是否已排序 | +| `insertTablet(Tablet tablet)` | 插入单个Tablet数据 | `tablet`: 要插入的Tablet数据 | +| `insertTablet(Tablet tablet, boolean sorted)` | 插入排序的Tablet数据 | 同上,增加 `sorted`: 数据是否已排序 | +| `insertAlignedTablet(Tablet tablet)` | 插入对齐的Tablet数据 | `tablet`: 要插入的Tablet数据 | +| `insertAlignedTablet(Tablet tablet, boolean sorted)` | 插入排序的对齐Tablet数据 | 同上,增加 `sorted`: 数据是否已排序 | +| `insertTablets(Map tablets)` | 批量插入多个Tablet数据 | `tablets`: 设备ID到Tablet的映射表 | +| `insertTablets(Map tablets, boolean sorted)` | 批量插入排序的多个Tablet数据 | 同上,增加 `sorted`: 数据是否已排序 | +| `insertAlignedTablets(Map tablets)` | 批量插入多个对齐Tablet数据 | `tablets`: 设备ID到Tablet的映射表 | +| `insertAlignedTablets(Map tablets, boolean sorted)` | 批量插入排序的多个对齐Tablet数据 | 同上,增加 `sorted`: 数据是否已排序 | + +#### 数据删除 +| 方法名 | 功能描述 | 参数解释 | +|-----------------------------------------------------------------------------------------|--------------------------------------------|------------------------------------------------------------------------------------------------------------| +| `deleteTimeseries(String path)` | 删除单个时间序列 | `path`: 时间序列路径 | +| `deleteTimeseries(List paths)` | 批量删除时间序列 | `paths`: 时间序列路径列表 | +| `deleteData(String path, long endTime)` | 删除指定路径的历史数据 | `path`: 路径,`endTime`: 结束时间戳 | +| `deleteData(List paths, long endTime)` | 批量删除路径的历史数据 | `paths`: 路径列表,`endTime`: 结束时间戳 | +| `deleteData(List paths, long startTime, long endTime)` | 删除路径时间范围内的历史数据 | 同上,增加 `startTime`: 起始时间戳 | + + +#### 数据查询 +| 方法名 | 功能描述 | 参数解释 | +|-----------------------------------------------------------------------------------------|--------------------------------------------|------------------------------------------------------------------------------------------------------------| +| `executeQueryStatement(String sql)` | 执行查询语句 | `sql`: 查询SQL语句 | +| `executeQueryStatement(String sql, long timeoutInMs)` | 执行带超时的查询语句 | `sql`: 查询SQL语句,`timeoutInMs`: 查询超时时间(毫秒) | +| `executeRawDataQuery(List paths, long startTime, long endTime)` | 查询指定路径的原始数据 | `paths`: 查询路径列表,`startTime`: 起始时间戳,`endTime`: 结束时间戳 | +| `executeRawDataQuery(List paths, long startTime, long endTime, long timeOut)` | 查询指定路径的原始数据(带超时) | 同上,增加 `timeOut`: 超时时间 | +| `executeLastDataQuery(List paths)` | 查询最新数据 | `paths`: 查询路径列表 | +| `executeLastDataQuery(List paths, long lastTime)` | 查询指定时间的最新数据 | `paths`: 查询路径列表,`lastTime`: 指定的时间戳 | +| `executeLastDataQuery(List paths, long lastTime, long timeOut)` | 查询指定时间的最新数据(带超时) | 同上,增加 `timeOut`: 超时时间 | +| `executeLastDataQueryForOneDevice(String db, String device, List sensors, boolean isLegalPathNodes)` | 查询单个设备的最新数据 | `db`: 数据库名,`device`: 设备名,`sensors`: 传感器列表,`isLegalPathNodes`: 是否合法路径节点 | +| `executeAggregationQuery(List paths, List aggregations)` | 执行聚合查询 | `paths`: 查询路径列表,`aggregations`: 聚合类型列表 | +| `executeAggregationQuery(List paths, List aggregations, long startTime, long endTime)` | 执行带时间范围的聚合查询 | 同上,增加 `startTime`: 起始时间戳,`endTime`: 结束时间戳 | +| `executeAggregationQuery(List paths, List aggregations, long startTime, long endTime, long interval)` | 执行带时间间隔的聚合查询 | 同上,增加 `interval`: 时间间隔 | +| `executeAggregationQuery(List paths, List aggregations, long startTime, long endTime, long interval, long slidingStep)` | 执行滑动窗口聚合查询 | 同上,增加 `slidingStep`: 滑动步长 | +| `fetchAllConnections()` | 获取所有活动连接信息 | 无参数 | + +#### 系统状态与备份 +| 方法名 | 功能描述 | 参数解释 | +|-----------------------------------------------------------------------------------------|--------------------------------------------|------------------------------------------------------------------------------------------------------------| +| `getBackupConfiguration()` | 获取备份配置信息 | 无参数 | +| `fetchAllConnections()` | 获取所有活动的连接信息 | 无参数 | +| `getSystemStatus()` | 获取系统状态 | 已废弃,默认返回 `SystemStatus.NORMAL` | + + + +# 数据订阅 + +## 1 Topic 管理 IoTDB 订阅客户端中的 `SubscriptionSession` 类提供了 Topic 管理的相关接口。Topic状态变化如下图所示: @@ -459,7 +893,7 @@ IoTDB 订阅客户端中的 `SubscriptionSession` 类提供了 Topic 管理的 -##### 1.1 创建 Topic +### 1.1 创建 Topic ```Java void createTopicIfNotExists(String topicName, Properties properties) throws Exception; @@ -476,13 +910,13 @@ try (final SubscriptionSession session = new SubscriptionSession(host, port)) { } ``` -##### 1.2 删除 Topic +### 1.2 删除 Topic ```Java void dropTopicIfExists(String topicName) throws Exception; ``` -##### 1.3 查看 Topic +### 1.3 查看 Topic ```Java // 获取所有 topics @@ -492,7 +926,7 @@ Set getTopics() throws Exception; Optional getTopic(String topicName) throws Exception; ``` -#### 2 查看订阅状态 +## 2 查看订阅状态 IoTDB 订阅客户端中的 `SubscriptionSession` 类提供了获取订阅状态的相关接口: @@ -501,7 +935,7 @@ Set getSubscriptions() throws Exception; Set getSubscriptions(final String topicName) throws Exception; ``` -#### 3 创建 Consumer +## 3 创建 Consumer 在使用 JAVA 原生接口创建 consumer 时,需要指定 consumer 所应用的参数。 @@ -522,7 +956,7 @@ Set getSubscriptions(final String topicName) throws Exception; | fileSaveFsync | optional: false | `Boolean`: consumer 订阅 TsFile 的过程中是否主动调用 fsync | -##### 3.1 SubscriptionPushConsumer +### 3.1 SubscriptionPushConsumer 以下为 `SubscriptionPushConsumer` 中的特殊配置: | 参数 | 是否必填(默认值) | 参数含义 | @@ -548,7 +982,7 @@ enum ConsumeResult { } ``` -##### 3.2 SubscriptionPullConsumer +### 3.2 SubscriptionPullConsumer 以下为 `SubscriptionPullConsumer` 中的特殊配置: @@ -565,7 +999,7 @@ void open() throws Exception; 此时,IoTDB 订阅客户端才会校验 consumer 的配置正确性,在校验成功后 consumer 就会加入对应的 consumer group。也就是说,在打开 consumer 后,才可以使用返回的 consumer 对象进行订阅 Topic,消费数据等操作。 -#### 4 订阅 Topic +## 4 订阅 Topic `SubscriptionPushConsumer` 和 `SubscriptionPullConsumer` 提供了下述 JAVA 原生接口用于订阅 Topics: @@ -579,18 +1013,18 @@ void subscribe(List topics) throws Exception; - 一个 consumer 在已经订阅了某个 topic 的情况下再次订阅这个 topic,不会报错 - 如果该 consumer 所在的 consumer group 中已经有 consumers 订阅了相同的 topics,那么该 consumer 将会复用对应的消费进度 -#### 5 消费数据 +## 5 消费数据 无论是 push 模式还是 pull 模式的 consumer: - 只有显式订阅了某个 topic,才会收到对应 topic 的数据 - 若在创建后没有订阅任何 topics,此时该 consumer 无法消费到任何数据,即使该 consumer 所在的 consumer group 中其它的 consumers 订阅了一些 topics -##### 5.1 SubscriptionPushConsumer +### 5.1 SubscriptionPushConsumer SubscriptionPushConsumer 在订阅 topics 后,无需手动拉取数据,其消费数据的逻辑在创建 SubscriptionPushConsumer 指定的 `consumeListener` 配置中。 -##### 5.2 SubscriptionPullConsumer +### 5.2 SubscriptionPullConsumer SubscriptionPullConsumer 在订阅 topics 后,需要主动调用 `poll` 方法拉取数据: @@ -629,7 +1063,7 @@ public interface AsyncCommitCallback { } ``` -#### 6 取消订阅 +## 6 取消订阅 `SubscriptionPushConsumer` 和 `SubscriptionPullConsumer` 提供了下述 JAVA 原生接口用于取消订阅并关闭 consumer: @@ -646,9 +1080,9 @@ void close(); - consumer close 时会退出对应的 consumer group,同时自动 unsubscribe 该 consumer 现存订阅的所有 topics - consumer 在 close 后生命周期即结束,无法再重新 open 订阅并消费数据 -#### 7 代码示例 +## 7 代码示例 -##### 7.1 单 Pull Consumer 消费 SessionDataSetsHandler 形式的数据 +### 7.1 单 Pull Consumer 消费 SessionDataSetsHandler 形式的数据 ```Java // Create topics @@ -693,7 +1127,7 @@ consumer1.unsubscribe(TOPIC_1); consumer1.close(); ``` -##### 7.2 多 Push Consumer 消费 TsFileHandler 形式的数据 +## 7.2 多 Push Consumer 消费 TsFileHandler 形式的数据 ```Java // Create topics @@ -738,55 +1172,4 @@ for (int i = 0; i < 8; ++i) { for (final Thread thread : threads) { thread.join(); } -``` - - -### 其他功能(直接执行SQL语句) - -``` java -void executeNonQueryStatement(String sql) -``` - -### 写入测试接口 (用于分析网络带宽) - -不实际写入数据,只将数据传输到 server 即返回 - -* 测试 insertRecord - -``` java -void testInsertRecord(String deviceId, long time, List measurements, List values) - -void testInsertRecord(String deviceId, long time, List measurements, - List types, List values) -``` - -* 测试 testInsertRecords - -``` java -void testInsertRecords(List deviceIds, List times, - List> measurementsList, List> valuesList) - -void testInsertRecords(List deviceIds, List times, - List> measurementsList, List> typesList, - List> valuesList) -``` - -* 测试 insertTablet - -``` java -void testInsertTablet(Tablet tablet) -``` - -* 测试 insertTablets - -``` java -void testInsertTablets(Map tablets) -``` - -### 示例代码 - -浏览上述接口的详细信息,请参阅代码 ```session/src/main/java/org/apache/iotdb/session/Session.java``` - -使用上述接口的示例代码在 ```example/session/src/main/java/org/apache/iotdb/SessionExample.java``` - -使用对齐时间序列和元数据模板的示例可以参见 `example/session/src/main/java/org/apache/iotdb/AlignedTimeseriesSessionExample.java` \ No newline at end of file +``` \ No newline at end of file