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