### Java: Initialize and Setup IoTDB SessionPool Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/java_examples_priority.md Demonstrates how to initialize a SessionPool for connecting to IoTDB and subsequently create a database with multiple timeseries. This example is intended for production applications and emphasizes efficient memory usage through iterator-based data reading. ```java import org.apache.iotdb.session.pool.SessionPool; import org.apache.iotdb.session.SessionDataSet; import org.apache.iotdb.tsfile.read.common.DataIterator; import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType; import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding; import org.apache.iotdb.tsfile.file.metadata.enums.CompressionType; public class IoTDBSessionPoolExample { private SessionPool sessionPool; public void initializeSessionPool() { // RECOMMENDED: SessionPool for production applications sessionPool = new SessionPool.Builder() .host("127.0.0.1") .port(6667) .user("root") .password("root") .maxSize(10) // Connection pool size .build(); System.out.println("SessionPool initialized successfully"); } public void setupDatabase() throws Exception { // Create database sessionPool.createDatabase("root.production"); // Create multiple timeseries sessionPool.createTimeseries( "root.production.factory1.temperature", TSDataType.FLOAT, TSEncoding.RLE, CompressionType.SNAPPY ); sessionPool.createTimeseries( "root.production.factory1.humidity", TSDataType.FLOAT, TSEncoding.RLE, CompressionType.SNAPPY ); sessionPool.createTimeseries( "root.production.factory1.pressure", TSDataType.FLOAT, TSEncoding.RLE, CompressionType.SNAPPY ); System.out.println("Database and timeseries created"); } public void closeSessionPool() { if (sessionPool != null) { sessionPool.close(); System.out.println("SessionPool closed"); } } } ``` -------------------------------- ### Install IoTDB Python Client and Dependencies (Bash) Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/python_examples.md A bash script to install the IoTDB Python client and its required and optional dependencies using pip. It covers the base package, common libraries like numpy and pandas, and development tools such as SQLAlchemy and testcontainers. ```bash #!/bin/bash # install_iotdb_python.sh echo "Installing IoTDB Python client and dependencies..." # Install base package pip install apache-iotdb # Install optional dependencies pip install numpy pandas # Install development dependencies (optional) pip install sqlalchemy testcontainers echo "Installation complete!" echo "Test connection with: python -c 'from iotdb.Session import Session; print(\"IoTDB Python client installed successfully\")'" ``` -------------------------------- ### Python Installation and Tree Model Connection Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/SKILL.md Provides instructions for installing the Apache IoTDB Python client using pip and demonstrates how to establish a connection to the IoTDB server. It also shows how to set the timezone for the session. ```bash pip install apache-iotdb ``` ```python from iotdb.Session import Session from iotdb.thrift.common.ttypes import TSDataType, TSEncoding, Compressor from iotdb.session.IoTDB :Tablet # Tree Model Connection session = Session("127.0.0.1", "6667", "root", "root") session.open(False) # Set timezone (optional) session.set_time_zone("Asia/Shanghai") ``` -------------------------------- ### Setup HikariCP Connection Pool in Java Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/jdbc_examples.md Demonstrates how to manually configure and set up a HikariCP connection pool for a database, specifically shown with IoTDB. It includes setting JDBC URL, credentials, and pool properties like maximum pool size and timeouts. ```java import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.sql.ResultSet; public class IoTDBConnectionPool { private HikariDataSource dataSource; public void setupConnectionPool() { HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:iotdb://127.0.0.1:6667/"); config.setUsername("root"); config.setPassword("root"); config.setDriverClassName("org.apache.iotdb.jdbc.IoTDBDriver"); // Pool configuration config.setMaximumPoolSize(20); config.setMinimumIdle(5); config.setConnectionTimeout(30000); config.setIdleTimeout(600000); config.setMaxLifetime(1800000); // IoTDB specific settings config.addDataSourceProperty("fetchSize", "10000"); dataSource = new HikariDataSource(config); } public Connection getConnection() throws SQLException { return dataSource.getConnection(); } public void performPooledOperations() { try (Connection conn = getConnection()) { // Use connection from pool queryWithIterator(conn); } catch (SQLException e) { System.err.println("Pooled operation failed: " + e.getMessage()); } } private void queryWithIterator(Connection conn) throws SQLException { String sql = "SELECT * FROM root.jdbc_example.device1 LIMIT 100"; try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { while (rs.next()) { System.out.println("Timestamp: " + rs.getLong(1) + ", Values: " + rs.getString(2)); } } } public void closePool() { if (dataSource != null && !dataSource.isClosed()) { dataSource.close(); } } } ``` -------------------------------- ### SQLAlchemy Integration with IoTDB (Python) Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/python_examples.md Demonstrates how to use SQLAlchemy to interact with IoTDB. This example requires SQLAlchemy to be installed. It sets up an engine, defines a model for sensor data, and performs a query using the ORM. ```python from sqlalchemy import create_engine, Column, Float, BigInteger, MetaData from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker # Create engine engine = create_engine("iotdb://root:root@127.0.0.1:6667") # Define model metadata = MetaData(schema='root.factory') Base = declarative_base(metadata=metadata) class SensorData(Base): __tablename__ = "workshop1.device1" Time = Column(BigInteger, primary_key=True) temperature = Column(Float) humidity = Column(Float) # Create session Session = sessionmaker(bind=engine) session = Session() # Query using ORM results = session.query(SensorData.temperature).filter( SensorData.temperature > 25 ).limit(10).all() print("SQLAlchemy ORM results:") for result in results: print(result) session.close() ``` -------------------------------- ### IoTDB JDBC Application: Setup, Insert, and Query Data in Java Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/jdbc_examples.md This Java code demonstrates a complete application using the IoTDB JDBC driver. It connects to an IoTDB instance, sets up a database and timeseries, inserts sample data, and then queries and displays the latest records. It requires the IoTDB JDBC driver as a dependency. ```java public class IoTDBJDBCApplication { private static final String JDBC_URL = "jdbc:iotdb://127.0.0.1:6667/"; private static final String USERNAME = "root"; private static final String PASSWORD = "root"; public static void main(String[] args) { IoTDBJDBCApplication app = new IoTDBJDBCApplication(); app.run(); } public void run() { try (Connection connection = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD)) { // Setup setupDatabase(connection); // Insert test data insertTestData(connection); // Query and display results queryAndDisplay(connection); } catch (SQLException e) { System.err.println("Application error: " + e.getMessage()); } } private void setupDatabase(Connection connection) throws SQLException { try (Statement stmt = connection.createStatement()) { stmt.execute("CREATE DATABASE root.application"); stmt.execute("CREATE TIMESERIES root.application.sensor1.temperature WITH DATATYPE=FLOAT, ENCODING=RLE"); stmt.execute("CREATE TIMESERIES root.application.sensor1.humidity WITH DATATYPE=FLOAT, ENCODING=RLE"); System.out.println("Database setup completed"); } } private void insertTestData(Connection connection) throws SQLException { String sql = "INSERT INTO root.application.sensor1(timestamp, temperature, humidity) VALUES(?, ?, ?)"; try (PreparedStatement pstmt = connection.prepareStatement(sql)) { long baseTime = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { pstmt.setLong(1, baseTime + i * 60000); // Every minute pstmt.setFloat(2, 20.0f + (float) Math.random() * 10); pstmt.setFloat(3, 50.0f + (float) Math.random() * 30); pstmt.executeUpdate(); } System.out.println("Inserted 100 test records"); } } private void queryAndDisplay(Connection connection) throws SQLException { String sql = "SELECT timestamp, temperature, humidity FROM root.application.sensor1 ORDER BY timestamp DESC LIMIT 10"; try (Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { System.out.println("\nLatest 10 readings:"); System.out.println("Timestamp\t\t\tTemperature\tHumidity"); System.out.println("-".repeat(60)); while (rs.next()) { System.out.printf("%d\t%.2f\t\t%.2f%n", rs.getLong("timestamp"), rs.getFloat("temperature"), rs.getFloat("humidity")); } } } } ``` -------------------------------- ### Main Execution Flow Example in Python Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/python_examples.md This function serves as the main entry point for executing various Timecho client examples. It initializes the client, connects to the database, and then calls individual example functions for basic operations, data insertion, query examples, and connection pool demonstration. It includes error handling and ensures the client disconnects upon completion. ```python def main(): """Main example function""" client = IoTDBPythonClient() try: client.connect() print("=== Basic Operations Example ===") client.basic_operations_example() print("\n=== Tablet Insertion Example ===") client.tablet_insertion_example() print("\n=== Numpy Tablet Example ===") client.numpy_tablet_example() print("\n=== Pandas Integration Example ===") client.pandas_integration_example() print("\n=== Aligned Timeseries Example ===") client.aligned_timeseries_example() print("\n=== Advanced Query Examples ===") client.advanced_query_examples() print("\n=== Session Configuration Example ===") client.session_configuration_example() except Exception as e: print(f"Error in main execution: {e}") finally: client.disconnect() print("\n=== Connection Pool Example ===") connection_pool_example() if __name__ == "__main__": main() ``` -------------------------------- ### Dockerfile for IoTDB C++ Client Deployment on Linux Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/cpp_examples.md A Dockerfile to set up a Linux environment for deploying the IoTDB C++ client. It installs necessary build tools, libraries (build-essential, cmake, libthrift-dev, libboost-all-dev), copies the application code, builds it using CMake and make, and sets the default command to run the client. ```dockerfile # Dockerfile for C++ client deployment FROM ubuntu:20.04 RUN apt-get update && apt-get install -y \ build-essential \ cmake \ libthrift-dev \ libboost-all-dev \ && rm -rf /var/lib/apt/lists/* COPY . /app WORKDIR /app RUN mkdir build && cd build && \ cmake .. && \ make CMD ["./build/iotdb_client"] ``` -------------------------------- ### Session Configuration - Python Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/python_examples.md Shows how to configure session parameters for Timecho client. This example demonstrates setting the fetch size for query results and specifying the time zone for session operations. ```Python self.session.set_fetch_size(5000) self.session.set_time_zone("Asia/Shanghai") ``` -------------------------------- ### Compile IoTDB C++ Client and Application Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/SKILL.md This section provides bash commands for installing dependencies and compiling the IoTDB C++ client. It also includes a clang++ command for compiling a C++ application that uses the IoTDB client library, specifying necessary include and library paths. ```bash # Install dependencies (Ubuntu/Debian) sudo apt-get install libthrift-dev libboost-dev # Compile IoTDB C++ client mvn clean package -P with-cpp -pl iotdb-client/client-cpp -am -DskipTests # Compile application clang++ -O2 your-code.cpp -liotdb_session \ -L/path/to/iotdb-client/lib \ -Wl,-rpath /path/to/iotdb-client/lib \ -std=c++11 ``` -------------------------------- ### Execute Query (POST /rest/v1/query) Examples (Bash) Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/rest_api.md Provides examples of executing various SQL queries using the POST /rest/v1/query endpoint. It covers basic queries, time range queries, and aggregation queries, demonstrating the required request body format and authentication headers. ```bash # Basic Query curl -H "Content-Type: application/json" \ -H "Authorization: Basic cm9vdDpyb290" \ -X POST \ --data '{"sql": "SELECT * FROM root.factory.workshop1 LIMIT 10"}' \ http://127.0.0.1:18080/rest/v1/query # Time Range Query curl -H "Content-Type: application/json" \ -H "Authorization: Basic cm9vdDpyb290" \ -X POST \ --data '{"sql": "SELECT temperature, humidity FROM root.factory.workshop1 WHERE time >= now() - 1h"}' \ http://127.0.0.1:18080/rest/v1/query # Aggregation Query curl -H "Content-Type: application/json" \ -H "Authorization: Basic cm9vdDpyb290" \ -X POST \ --data '{"sql": "SELECT AVG(temperature), MAX(temperature) FROM root.factory.workshop1 GROUP BY ([now() - 1d, now()), 1h)"}' \ http://127.0.0.1:18080/rest/v1/query ``` -------------------------------- ### IoTDB JDBC Example Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/java_examples_updated.md Demonstrates how to connect to an IoTDB instance using JDBC, create databases and timeseries, insert data, and query data using a ResultSet. It handles potential exceptions during these operations. ```java public static void jdbcExample() { System.out.println("\n=== JDBC Example ==="); String jdbcUrl = "jdbc:iotdb://127.0.0.1:6667/"; String username = "root"; String password = "root"; try (java.sql.Connection connection = java.sql.DriverManager.getConnection( jdbcUrl, username, password)) { // Create database and timeseries try (java.sql.Statement stmt = connection.createStatement()) { stmt.execute("CREATE DATABASE root.jdbc_example"); stmt.execute("CREATE TIMESERIES root.jdbc_example.device.temperature " + "WITH DATATYPE=FLOAT, ENCODING=RLE"); // Insert data stmt.execute("INSERT INTO root.jdbc_example.device(timestamp, temperature) " + "VALUES(" + System.currentTimeMillis() + ", 25.5)"); System.out.println("JDBC operations completed"); } // Query with JDBC ResultSet (iterator-based) try (java.sql.Statement stmt = connection.createStatement(); java.sql.ResultSet rs = stmt.executeQuery( "SELECT * FROM root.jdbc_example.device")) { System.out.println("JDBC Query Results:"); while (rs.next()) { System.out.println("Time: " + rs.getLong("Time") + ", Temperature: " + rs.getFloat("root.jdbc_example.device.temperature")); } } } catch (Exception e) { System.err.println("JDBC error: " + e.getMessage()); } } ``` -------------------------------- ### Session Configuration and Query Example in Python Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/python_examples.md Demonstrates how to check session configuration, specifically the current timezone, and execute a query to list available timeseries. It includes basic error handling for session operations. This snippet requires an active IoTDB session. ```python # Check configuration print(f"Current timezone: {self.session.get_time_zone()}") # Test connection result = self.session.execute_query_statement("SHOW TIMESERIES") print("Available timeseries:") count = 0 while result.has_next() and count < 10: print(result.next()) count += 1 except Exception as e: print(f"Error in session configuration: {e}") ``` -------------------------------- ### Establish Basic IoTDB JDBC Connection and Perform Operations Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/jdbc_examples.md Provides a Java example for establishing a basic JDBC connection to IoTDB using DriverManager. It includes sample code for creating a database, timeseries, and inserting a single data point. ```java import java.sql.*; public class IoTDBJDBCBasic { private static final String JDBC_URL = "jdbc:iotdb://127.0.0.1:6667/"; private static final String USERNAME = "root"; private static final String PASSWORD = "root"; public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD)) { System.out.println("Connected to IoTDB via JDBC"); // Basic operations basicOperations(connection); } catch (SQLException e) { System.err.println("JDBC Connection failed: " + e.getMessage()); } } private static void basicOperations(Connection connection) throws SQLException { try (Statement stmt = connection.createStatement()) { // Create database stmt.execute("CREATE DATABASE root.jdbc_example"); // Create timeseries stmt.execute( "CREATE TIMESERIES root.jdbc_example.device1.temperature " + "WITH DATATYPE=FLOAT, ENCODING=RLE" ); stmt.execute( "CREATE TIMESERIES root.jdbc_example.device1.humidity " + "WITH DATATYPE=FLOAT, ENCODING=RLE" ); // Insert data stmt.execute( "INSERT INTO root.jdbc_example.device1(timestamp, temperature, humidity) " + "VALUES(" + System.currentTimeMillis() + ", 25.5, 60.0)" ); System.out.println("Data inserted successfully"); } } } ``` -------------------------------- ### Tree Model Path Design Best Practices (SQL) Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/data_models.md Illustrates recommended practices for designing hierarchical paths in a Tree model. It shows examples of logical, shorter paths and advises against overly deep nesting. ```sql -- Good: Logical hierarchy root.factory.building1.floor2.room201.temperature -- Better: Shorter, still logical root.factory.b1f2r201.temperature -- Avoid: Too deep nesting root.company.site.building.floor.room.zone.sensor.temperature ``` -------------------------------- ### Tablet Insert Example with C++ Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/cpp_examples.md Illustrates inserting data using the Tablet API in Timecho. It defines a device ID and schema, then fills a Tablet object with generated temperature, humidity, and pressure data. Data is inserted in batches of maxRowNumber. Error handling is included. ```cpp void tabletInsertExample() { try { std::cout << "=== Tablet Insert Example ===" << std::endl; std::string deviceId = "root.factory.workshop2"; std::vector> schemaList = { {"temperature", TSDataType::FLOAT}, {"humidity", TSDataType::FLOAT}, {"pressure", TSDataType::FLOAT} }; int maxRowNumber = 1024; int rowSize = 0; // Create tablet Tablet tablet(deviceId, schemaList, maxRowNumber); // Fill tablet with data std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<> tempDist(20.0, 30.0); std::uniform_real_distribution<> humidDist(40.0, 80.0); std::uniform_real_distribution<> pressureDist(990.0, 1050.0); long long baseTime = std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch() ).count(); for (int i = 0; i < 500; ++i) { tablet.timestamps.push_back(baseTime + i * 1000); tablet.values[0].push_back(std::to_string(tempDist(gen))); tablet.values[1].push_back(std::to_string(humidDist(gen))); tablet.values[2].push_back(std::to_string(pressureDist(gen))); rowSize++; if (rowSize == maxRowNumber) { tablet.rowSize = rowSize; session->insertTablet(tablet); // Reset tablet tablet.timestamps.clear(); for (auto& valueVector : tablet.values) { valueVector.clear(); } rowSize = 0; } } // Insert remaining data if (rowSize > 0) { tablet.rowSize = rowSize; session->insertTablet(tablet); } std::cout << "Inserted 500 records using tablet" << std::endl; } catch (const std::exception& e) { std::cerr << "Error in tablet insert: " << e.what() << std::endl; } } ``` -------------------------------- ### Install TsFile Python API Source: https://github.com/timecholab/timecho-skills/blob/main/tsfile/references/api_reference.md Instructions for installing the TsFile Python API, which requires a C++ TsFile build. It provides two common methods using Maven or `setup.py`. ```bash mvn -P with-cpp,with-python clean verify # or python setup.py build_ext --inplace ``` -------------------------------- ### Execute Non-Query (POST /rest/v1/nonQuery) Examples (Bash) Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/rest_api.md Illustrates how to execute Data Definition Language (DDL) and Data Manipulation Language (DML) statements that do not return data using the POST /rest/v1/nonQuery endpoint. Examples include creating databases, timeseries, and inserting data. ```bash # Create Database curl -H "Content-Type: application/json" \ -H "Authorization: Basic cm9vdDpyb290" \ -X POST \ --data '{"sql": "CREATE DATABASE root.factory"}' \ http://127.0.0.1:18080/rest/v1/nonQuery # Create Timeseries curl -H "Content-Type: application/json" \ -H "Authorization: Basic cm9vdDpyb290" \ -X POST \ --data '{"sql": "CREATE TIMESERIES root.factory.workshop1.temperature WITH DATATYPE=FLOAT, ENCODING=RLE"}' \ http://127.0.0.1:18080/rest/v1/nonQuery # Insert Data curl -H "Content-Type: application/json" \ -H "Authorization: Basic cm9vdDpyb290" \ -X POST \ --data '{"sql": "INSERT INTO root.factory.workshop1(timestamp, temperature, humidity) VALUES(1635232143960, 25.5, 60.0)"}' \ http://127.0.0.1:18080/rest/v1/nonQuery ``` -------------------------------- ### Manage Timeseries with C++ IoTDB Client Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/cpp_examples.md This example demonstrates timeseries management operations using the C++ IoTDB client. It includes checking if a timeseries exists, creating a new timeseries with tags and attributes, and provides commented-out code for deleting a timeseries. Error handling is included. ```cpp void timeseriesManagementExample() { try { std::cout << "=== Timeseries Management Example ===" << std::endl; // Check if timeseries exists bool exists = session->checkTimeseriesExists("root.factory.workshop1.temperature"); std::cout << "Temperature timeseries exists: " << (exists ? "Yes" : "No") << std::endl; // Create timeseries with tags and attributes std::map tags; tags["location"] = "workshop1"; tags["type"] = "sensor"; std::map attributes; attributes["manufacturer"] = "ACME"; attributes["model"] = "T1000"; if (!session->checkTimeseriesExists("root.factory.workshop1.tagged_sensor")) { session->createTimeseries( "root.factory.workshop1.tagged_sensor", TSDataType::FLOAT, TSEncoding::RLE, CompressionType::SNAPPY, nullptr, // props &tags, &attributes, "temperature_sensor" // alias ); std::cout << "Created tagged timeseries" << std::endl; } // Delete timeseries (uncomment to test) // std::vector paths = {"root.factory.workshop1.tagged_sensor"}; // session->deleteTimeseries(paths); // std::cout << "Deleted tagged timeseries" << std::endl; } catch (const std::exception& e) { std::cerr << "Error in timeseries management: " << e.what() << std::endl; } } ``` -------------------------------- ### IoTDB SessionPool Setup and Basic Operations (Java) Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/java_examples_updated.md Demonstrates how to initialize and use the IoTDB SessionPool for creating databases, timeseries, inserting single records, and performing batch inserts. It utilizes the SessionPool for managing connections efficiently. ```java package org.apache.iotdb; import org.apache.iotdb.isession.SessionDataSet; import org.apache.iotdb.isession.SessionDataSet.DataIterator; import org.apache.iotdb.rpc.IoTDBConnectionException; import org.apache.iotdb.rpc.StatementExecutionException; import org.apache.iotdb.session.SessionPool; import org.apache.tsfile.enums.TSDataType; import org.apache.tsfile.file.metadata.enums.CompressionType; import org.apache.tsfile.file.metadata.enums.TSEncoding; import org.apache.tsfile.write.record.Tablet; import org.apache.tsfile.write.schema.IMeasurementSchema; import org.apache.tsfile.write.schema.MeasurementSchema; import java.util.*; public class IoTDBSessionPoolExample { private static final String HOST = "127.0.0.1"; private static final int PORT = 6667; private static final String USERNAME = "root"; private static final String PASSWORD = "root"; public static void main(String[] args) { // Primary recommendation: SessionPool sessionPoolExample(); // Advanced operations advancedSessionPoolOperations(); // JDBC Example jdbcExample(); } public static void sessionPoolExample() { SessionPool sessionPool = new SessionPool.Builder() .host(HOST) .port(PORT) .user(USERNAME) .password(PASSWORD) .maxSize(10) // Connection pool size .build(); try { System.out.println("=== SessionPool Example ==="); // Create database and timeseries sessionPool.createDatabase("root.factory"); sessionPool.createTimeseries( "root.factory.workshop1.temperature", TSDataType.FLOAT, TSEncoding.RLE, CompressionType.SNAPPY ); sessionPool.createTimeseries( "root.factory.workshop1.humidity", TSDataType.FLOAT, TSEncoding.RLE, CompressionType.SNAPPY ); System.out.println("Created database and timeseries using SessionPool"); // Insert single record sessionPool.insertRecord( "root.factory.workshop1", System.currentTimeMillis(), Arrays.asList("temperature", "humidity"), Arrays.asList(TSDataType.FLOAT, TSDataType.FLOAT), Arrays.asList(25.5f, 60.0f) ); // Insert multiple records insertMultipleRecords(sessionPool); // Query data with iterator (RECOMMENDED) queryWithIterator(sessionPool); } catch (IoTDBConnectionException | StatementExecutionException e) { System.err.println("SessionPool operation failed: " + e.getMessage()); } finally { sessionPool.close(); } } private static void insertMultipleRecords(SessionPool sessionPool) throws IoTDBConnectionException, StatementExecutionException { List deviceIds = Arrays.asList( "root.factory.workshop1", "root.factory.workshop1", "root.factory.workshop1" ); List timestamps = Arrays.asList( System.currentTimeMillis() + 1000, System.currentTimeMillis() + 2000, System.currentTimeMillis() + 3000 ); List> measurementsList = Arrays.asList( Arrays.asList("temperature", "humidity"), Arrays.asList("temperature", "humidity"), Arrays.asList("temperature", "humidity") ); List> typesList = Arrays.asList( Arrays.asList(TSDataType.FLOAT, TSDataType.FLOAT), Arrays.asList(TSDataType.FLOAT, TSDataType.FLOAT), Arrays.asList(TSDataType.FLOAT, TSDataType.FLOAT) ); List> valuesList = Arrays.asList( Arrays.asList(26.0f, 61.0f), Arrays.asList(24.5f, 58.5f), Arrays.asList(27.2f, 62.3f) ); sessionPool.insertRecords(deviceIds, timestamps, measurementsList, typesList, valuesList); System.out.println("Inserted multiple records using SessionPool"); } private static void queryWithIterator(SessionPool sessionPool) throws IoTDBConnectionException, StatementExecutionException { // Query with iterator - RECOMMENDED approach try (SessionDataSet dataSet = sessionPool.executeQueryStatement( "SELECT temperature, humidity FROM root.factory.workshop1")) { System.out.println("\nQuery Results (Iterator-based):"); System.out.println("Column Names: " + dataSet.getColumnNames()); // Use DataIterator for memory-efficient reading DataIterator iterator = dataSet.iterator(); int count = 0; ``` -------------------------------- ### GET /api/sensors/readings/range Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/spring_boot_integration.md Retrieves sensor readings within a specified time range. The start and end times are required query parameters. ```APIDOC ## GET /api/sensors/readings/range ### Description Retrieves sensor readings within a specified time range. The start and end times are required query parameters. ### Method GET ### Endpoint /api/sensors/readings/range ### Parameters #### Query Parameters - **startTime** (long) - Required - The start timestamp of the range (inclusive). - **endTime** (long) - Required - The end timestamp of the range (exclusive). ### Response #### Success Response (200) - **readings** (List) - A list of sensor readings within the specified time range. #### Response Example ```json [ { "sensorId": "sensor123", "timestamp": 1678886400000, "value": 25.5 }, { "sensorId": "sensor456", "timestamp": 1678886460000, "value": 26.0 } ] ``` #### Error Response (400) - Returns a 400 status code if `startTime` is greater than or equal to `endTime`. #### Error Response (500) - Returns an empty response with a 500 status code if an internal error occurs. ``` -------------------------------- ### Add IoTDB JDBC Maven Dependency Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/jdbc_examples.md This snippet shows how to add the IoTDB JDBC driver as a Maven dependency to your project. Ensure you use the correct version compatible with your IoTDB installation. ```xml org.apache.iotdb iotdb-jdbc 2.0.6 ``` -------------------------------- ### Java Basic Session Connection to IoTDB Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/SKILL.md Provides an example of a basic Session connection to IoTDB in Java. This method is noted as an alternative and is recommended only for simple testing or single-threaded applications, with SessionPool being the preferred choice for production. ```java Session session = new Session.Builder() .host("127.0.0.1") .port(6667) .username("root") .password("root") .build(); session.open(false); // Remember to close when done session.close(); ``` -------------------------------- ### Tree Model Query Patterns in SQL Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/data_models.md Demonstrates common query patterns for the Tree model in TimechoDB. These examples cover device-centric, measurement-centric, and time-series analysis queries, highlighting the use of wildcards and time grouping. ```SQL -- Device-centric queries SELECT * FROM root.factory.device001.* -- Measurement-centric queries SELECT temperature FROM root.factory.** -- Time-series analysis SELECT avg(temperature) FROM root.factory.** GROUP BY ([NOW()-1d, NOW()), 1h) ``` -------------------------------- ### Table Model Efficient Filtering (SQL) Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/data_models.md Illustrates efficient filtering strategies for Table models, emphasizing the use of TAGs for optimal performance. It shows an example of efficient filtering by TAGs and contrasts it with less efficient filtering by FIELDS alone. ```sql -- Efficient: Filter by TAGs first SELECT * FROM sensors WHERE region = 'north' AND building = 'A' AND time > NOW() - 1h -- Less efficient: Filter by FIELDS without TAG filters SELECT * FROM sensors WHERE temperature > 25.0 -- Should combine with TAG filters ``` -------------------------------- ### IoTDB Table Model Basic Example in Java Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/java_examples.md This snippet demonstrates the basic usage of the IoTDB Table Session API. It covers creating a database, creating a table with different column types (TAG, ATTRIBUTE, FIELD), inserting data using a Tablet object, and performing basic and aggregation queries. It requires IoTDB to be running locally on the default port. ```java package org.apache.iotdb; import org.apache.iotdb.isession.ITableSession; import org.apache.iotdb.isession.SessionDataSet; import org.apache.iotdb.rpc.IoTDBConnectionException; import org.apache.iotdb.rpc.StatementExecutionException; import org.apache.iotdb.session.TableSessionBuilder; import org.apache.tsfile.enums.ColumnCategory; import org.apache.tsfile.enums.TSDataType; import org.apache.tsfile.write.record.Tablet; import java.util.Arrays; import java.util.Collections; import java.util.List; public class IoTDBTableModelExample { private static final String LOCAL_URL = "127.0.0.1:6667"; public static void main(String[] args) { tableModelBasicExample(); tableModelAdvancedExample(); } public static void tableModelBasicExample() { try (ITableSession session = new TableSessionBuilder() .nodeUrls(Collections.singletonList(LOCAL_URL)) .username("root") .password("root") .build()) { // Create database session.executeNonQueryStatement("CREATE DATABASE factory"); session.executeNonQueryStatement("USE factory"); // Create table with different column categories session.executeNonQueryStatement( "CREATE TABLE sensors(" + "region_id STRING TAG, " + "plant_id STRING TAG, " + "device_id STRING TAG, " + "device_type STRING ATTRIBUTE, " + "manufacturer STRING ATTRIBUTE, " + "temperature FLOAT FIELD, " + "humidity DOUBLE FIELD, " + "pressure FLOAT FIELD" + ") WITH (TTL=7200000)" ); // Insert data using tablet insertTableData(session); // Query data queryTableData(session); } catch (IoTDBConnectionException | StatementExecutionException e) { e.printStackTrace(); } } private static void insertTableData(ITableSession session) throws IoTDBConnectionException, StatementExecutionException { List columnNames = Arrays.asList( "region_id", "plant_id", "device_id", "device_type", "manufacturer", "temperature", "humidity", "pressure" ); List dataTypes = Arrays.asList( TSDataType.STRING, TSDataType.STRING, TSDataType.STRING, TSDataType.STRING, TSDataType.STRING, TSDataType.FLOAT, TSDataType.DOUBLE, TSDataType.FLOAT ); List columnCategories = Arrays.asList( ColumnCategory.TAG, ColumnCategory.TAG, ColumnCategory.TAG, ColumnCategory.ATTRIBUTE, ColumnCategory.ATTRIBUTE, ColumnCategory.FIELD, ColumnCategory.FIELD, ColumnCategory.FIELD ); Tablet tablet = new Tablet("sensors", columnNames, dataTypes, columnCategories, 100); // Add sample data for (int i = 0; i < 50; i++) { int rowIndex = tablet.getRowSize(); tablet.addTimestamp(rowIndex, System.currentTimeMillis() + i * 1000); tablet.addValue("region_id", rowIndex, "region_" + (i % 3)); tablet.addValue("plant_id", rowIndex, "plant_" + (i % 5)); tablet.addValue("device_id", rowIndex, "device_" + i); tablet.addValue("device_type", rowIndex, i % 2 == 0 ? "temperature_sensor" : "humidity_sensor"); tablet.addValue("manufacturer", rowIndex, i % 3 == 0 ? "ACME" : "TechCorp"); tablet.addValue("temperature", rowIndex, 20.0f + (float)(Math.random() * 15)); tablet.addValue("humidity", rowIndex, 40.0 + (Math.random() * 30)); tablet.addValue("pressure", rowIndex, 1000.0f + (float)(Math.random() * 100)); if (tablet.getRowSize() == tablet.getMaxRowNumber()) { session.insert(tablet); tablet.reset(); } } if (tablet.getRowSize() != 0) { session.insert(tablet); } } private static void queryTableData(ITableSession session) throws IoTDBConnectionException, StatementExecutionException { // Basic query try (SessionDataSet dataSet = session.executeQueryStatement( "SELECT * FROM sensors WHERE region_id = 'region_0' LIMIT 10")) { System.out.println("Basic Query Results:"); printDataSet(dataSet); } // Aggregation query try (SessionDataSet dataSet = session.executeQueryStatement( "SELECT region_id, AVG(temperature), MAX(humidity) " + "FROM sensors " + "GROUP BY region_id")) { System.out.println("Aggregation Query Results:"); printDataSet(dataSet); } // Time range query ``` -------------------------------- ### Tree Model Measurement Naming Best Practices (SQL) Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/data_models.md Demonstrates best practices for naming measurements within a Tree model, emphasizing clear and consistent naming conventions. It provides examples of good naming and contrasts them with inconsistent naming. ```sql -- Good: Clear, consistent naming root.factory.workshop01.temperature root.factory.workshop01.humidity root.factory.workshop01.pressure -- Avoid: Inconsistent naming root.factory.workshop01.temp root.factory.workshop01.humid_level root.factory.workshop01.air_pressure_reading ``` -------------------------------- ### Bash Script for Building IoTDB C++ Client Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/cpp_examples.md A bash script to automate the build process of the IoTDB C++ client using CMake. It sets up necessary paths, creates a build directory, configures CMake with release type and custom paths, and then compiles the project using make. ```bash #!/bin/bash # build_cpp_client.sh set -e echo "Building IoTDB C++ Client Example..." # Set paths (modify according to your setup) IOTDB_CLIENT_PATH="/path/to/iotdb/iotdb-client/client-cpp/target/client-cpp-*-cpp-*" BOOST_ROOT="/usr/local" # Create build directory mkdir -p build cd build # Configure CMake cmake .. \ -DCMAKE_BUILD_TYPE=Release \ -DBOOST_ROOT=${BOOST_ROOT} \ -DIoTDB_CLIENT_PATH=${IOTDB_CLIENT_PATH} # Build make -j$(nproc) echo "Build completed successfully!" echo "Run with: ./iotdb_client" ``` -------------------------------- ### Table Model Column Category Selection (SQL) Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/data_models.md Shows how to select appropriate column categories (TAG, ATTRIBUTE, FIELD) when creating a table schema. It provides an example of a `sensors` table with explanations for each category and highlights what to avoid, such as high cardinality TAGs. ```sql CREATE TABLE sensors ( -- TAGs: Low cardinality, used for filtering region STRING TAG, -- Good: Few regions building STRING TAG, -- Good: Limited buildings -- ATTRIBUTEs: Metadata, rarely changes sensor_model STRING ATTRIBUTE, installation_date DATE ATTRIBUTE, -- FIELDs: Actual measurements temperature FLOAT FIELD, humidity FLOAT FIELD -- Avoid: High cardinality TAGs -- sensor_serial STRING TAG -- Bad: Too many unique values ) ``` -------------------------------- ### Manage IoTDB Tables and Execute Complex Queries Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/java_examples.md Demonstrates advanced table management using `ITableSession`. It shows how to list tables, create a new table with specified schema and TTL, and execute a complex query with filtering and ordering. This example utilizes `TableSessionBuilder` for session creation and includes error handling. ```java try (ITableSession session = new TableSessionBuilder() .nodeUrls(Collections.singletonList(LOCAL_URL)) .username("root") .password("root") .database("factory") // Set default database .build()) { // Show tables try (SessionDataSet dataSet = session.executeQueryStatement("SHOW TABLES")) { System.out.println("Available Tables:"); printDataSet(dataSet); } // Create another table session.executeNonQueryStatement( "CREATE TABLE events(" + "device_id STRING TAG, " + "event_type STRING TAG, " + "severity STRING ATTRIBUTE, " + "message STRING FIELD, " + "value DOUBLE FIELD" + ") WITH (TTL=86400000)" ); // Complex query with JOIN (if supported) try (SessionDataSet dataSet = session.executeQueryStatement( "SELECT s.device_id, s.temperature, s.humidity " + "FROM sensors s " + "WHERE s.temperature > 30.0 " + "ORDER BY s.temperature DESC " + "LIMIT 5")) { System.out.println("High Temperature Devices:"); printDataSet(dataSet); } } catch (Exception e) { e.printStackTrace(); } ``` -------------------------------- ### Basic and Advanced Queries on Sensors Table (SQL) Source: https://github.com/timecholab/timecho-skills/blob/main/iotdb/references/data_models.md Provides examples of basic and advanced SQL queries for the sensors table. This includes selecting all or specific columns, filtering by tags and multiple conditions, time range queries, aggregation, time window aggregation, and join-like operations. ```sql -- Select all data SELECT * FROM sensors -- Select specific columns SELECT time, region_id, temperature, humidity FROM sensors -- Filter by tags (most efficient) SELECT * FROM sensors WHERE region_id = 'region_1' -- Filter by multiple conditions SELECT * FROM sensors WHERE region_id = 'region_1' AND device_type = 'temperature_sensor' -- Time range queries SELECT * FROM sensors WHERE time >= '2021-11-01T00:00:00' AND time < '2021-11-02T00:00:00' -- Aggregation queries SELECT region_id, avg(temperature), max(humidity) FROM sensors WHERE time > NOW() - 1h GROUP BY region_id -- Time window aggregation SELECT region_id, date_bin(INTERVAL '1' HOUR, time) as hour_window, avg(temperature) as avg_temp, count(*) as sample_count FROM sensors WHERE time > NOW() - 1d GROUP BY region_id, hour_window ORDER BY hour_window -- Join-like operations (using tags) SELECT s1.region_id, s1.temperature, s2.humidity FROM sensors s1, sensors s2 WHERE s1.region_id = s2.region_id AND s1.device_id = s2.device_id AND s1.time = s2.time ``` -------------------------------- ### IoTDB Table Model SQL Syntax for Database and Table Operations Source: https://context7.com/timecholab/timecho-skills/llms.txt Demonstrates SQL commands for creating databases, creating tables with specified column types (TAG, ATTRIBUTE, FIELD) and configurations like TTL and partitioning, and querying table schemas. ```sql CREATE DATABASE factory USE factory CREATE TABLE sensors ( region_id STRING TAG, device_id STRING TAG, device_type STRING ATTRIBUTE, manufacturer STRING ATTRIBUTE, temperature FLOAT FIELD, humidity DOUBLE FIELD, pressure FLOAT FIELD ) WITH (TTL=7200000) CREATE TABLE weather_data ( station_id STRING TAG, city STRING TAG, country STRING ATTRIBUTE, temperature FLOAT FIELD, humidity FLOAT FIELD, wind_speed FLOAT FIELD ) WITH ( TTL=2592000000, partition_interval='1d' ) SHOW TABLES DESCRIBE sensors SHOW CREATE TABLE sensors ```