Ingest MQTT Data into TDengine
TDengine is a big data platform, designed and optimized specifically for the Internet of Things (IoT) and Industrial Internet of Things (IIoT) scenarios. At its heart lies a high-performance time-series database, characterized by its cluster-oriented architecture, cloud-native design, and minimalistic approach. EMQX supports integration with TDengine, enabling massive data transmission, storage, analysis, and distribution from a large number of devices and data collectors. It provides real-time monitoring and early warning of business operation states, offering real-time business insights.
This page provides a comprehensive introduction to the data integration between EMQX and TDengine with practical instructions on creating and validating the data integration.
How It Works
TDengine data integration is a built-in feature in EMQX. With a built-in rule engine component, the integration simplifies the process of ingesting data from EMQX to TDengine, eliminating the need for complex coding. EMQX forwards device data to TDengine through the rule engine and Sink. Through the TDengine data integration, MQTT messages and client events can be stored in TDengine. Additionally, data updates or deletions in TDengine can be triggered by events, thereby enabling the recording of information such as device online status and historical online/offline events.
The diagram below illustrates the typical architecture of EMQX and TDengine data integration in the industrial IoT:
Taking the industrial energy consumption management scenario as an example, the workflow is as follows:
- Message publication and reception: Industrial devices establish successful connections to EMQX through the MQTT protocol and regularly publish energy consumption data using the MQTT protocol. This data includes production line identifiers and energy consumption values. When EMQX receives these messages, it initiates the matching process within its rules engine.
- Rule Engine Processes Messages: The built-in rule engine processes messages from specific sources based on topic matching. When a message arrives, it passes through the rule engine, which matches it with corresponding rules and processes the message data. This can include transforming data formats, filtering specific information, or enriching messages with context information.
- Data ingestion into TDengine: Rules defined in the rule engine trigger operations to write messages to TDengine. The TDengine Sink provides SQL templates that allow flexible definitions of the data format to write specific message fields to the corresponding tables and columns in TDengine.
After energy consumption data is written to TDengine, you can analyze your data in real-time using standard SQL and powerful time-series extensions, seamlessly integrating with numerous third-party batch analyses, real-time analysis, reporting tools, AI/ML tools, and visualization tools. For example:
- Connect to visualization tools such as Grafana to generate charts and display energy consumption data.
- Connect to application systems such as ERP or Power BI for production analysis and production plan adjustments.
- Connect to business systems to perform real-time energy usage analysis, facilitating data-driven energy management.
Features and Benefits
The TDengine data integration brings the following features and advantages to your business:
- Efficient Data Handling: EMQX can handle a large number of IoT device connections and message throughput efficiently. TDengine excels in data writing, storage, and querying, meeting the data processing needs of IoT scenarios without overwhelming the system.
- Message Transformation: Messages can undergo rich processing and transformation within EMQX rules before being written to TDengine.
- Cluster and Scalability: EMQX and TDengine support clustering capabilities and are built on cloud-native architecture, enabling full utilization of the cloud platform's elastic storage, computing, and network resources, allowing for flexible horizontal scaling as your business grows to meet expanding demands.
- Advanced Querying Capabilities: TDengine provides optimized functions, operators, and indexing techniques for efficient querying and analysis of timestamp data, enabling precise insights to be extracted from IoT time-series data.
Before You Start
This section describes the preparations you must complete before you start creating the TDengine data integration, including how to set up the TDengine server and create data tables.
Prerequisites
- Knowledge about EMQX data integration rules
- Knowledge about data integration
Install TDengine
Install TDengine via Docker, and then run the docker image.
# To start the TDengine docker image
docker run --name TDengine -p 6041:6041 tdengine/tdengine
# Access the container
docker exec -it TDengine bash
# Locate the TDengine server in the container
taos
# Create and then select the database
CREATE DATABASE mqtt;
use mqtt;
Create Data Tables in TDengine
Before you create data bridges for TDengine, you need to create two data tables in TDengine database for message storage and status recording.
- Use the following SQL statements to create data table
t_mqtt_msg
in TDengine database. The data table stores the client ID, topic, payload, and creation time of every message.
CREATE TABLE t_mqtt_msg (
ts timestamp,
msgid NCHAR(64),
mqtt_topic NCHAR(255),
qos TINYINT,
payload BINARY(1024),
arrived timestamp
);
- Use the following SQL statements to create data table
emqx_client_events
in TDengine database. This data table stores the client ID, event type, and creation time of every event.
CREATE TABLE emqx_client_events (
ts timestamp,
clientid VARCHAR(255),
event VARCHAR(255)
);
Create a Rule for TDengine Sink
This section demonstrates how to create two different rules for specifying the data to be saved into TDengine and recording client's online/offline status.
It assumes that you run both EMQX and TDengine on the local machine. If you have Microsoft SQL Server and EMQX running remotely, adjust the settings accordingly.
Go to EMQX Dashboard, and click Integration -> Rules.
Click Create on the top right corner of the page.
Enter
my_rule
as the rule ID, and set the rules in the SQL Editor based on the feature to use:To create a rule for message storage, input the following statement, which means the MQTT messages under topic
t/#
will be saved to TDengine.Note: If you want to specify your own SQL syntax, make sure that you have included all fields required by the Sink in the
SELECT
part.sqlSELECT *, now_timestamp('millisecond') as ts FROM "t/#"
To create a rule for online/offline status recording, input the following statement:
sqlSELECT *, now_timestamp('millisecond') as ts FROM "$events/client_connected", "$events/client_disconnected"
TIP
If you are a beginner user, click SQL Examples and Enable Test to learn and test the SQL rule.
Click the + Add Action button to define an action that will be triggered by the rule. With this action, EMQX sends the data processed by the rule to TDengine.
Select
TDengine
from the Type of Action dropdown list. Keep the Action dropdown with the defaultCreate Action
value. You can also select a TDengine Sink if you have created one. This demonstration will create a new Sink.Enter a name for the Sink. The name should combine upper/lower case letters and numbers.
Enter the connection information.
- Server Host: Enter
http://127.0.0.1:6041
, or the actual URL if the TDengine server is running remotely. - Database Name: Enter
mqtt
. - Username: Enter
root
. - Password: Enter
taosdata
.
- Server Host: Enter
Configure the SQL Template based on the feature to use.
TIP
There is a breaking change in EMQX 5.1.1. Earlier than this version, string-type values were automatically quoted. However, starting from EMQX 5.1.1, users are required to manually quote these values.
To create a Sink for message storage, use the statement below:
sqlINSERT INTO t_mqtt_msg(ts, msgid, mqtt_topic, qos, payload, arrived) VALUES (${ts}, '${id}', '${topic}', ${qos}, '${payload}', ${timestamp})
To create a Sink for online/offline status recording, use the statement below:
sqlINSERT INTO emqx_client_events(ts, clientid, event) VALUES ( ${ts}, '${clientid}', '${event}' )
Advanced settings (optional): Choose whether to use sync or async query mode as needed.
Before clicking Create, you can click Test Connectivity to test that the Sink can be connected to the TDengine. For details, see Features of Sink.
Click the Create button to complete the Sink configuration. A new Sink will be added to the Action Outputs.
Back on the Create Rule page, verify the configured information. Click the Create button to generate the rule.
You have now successfully created the rule for the TDengine Sink. You can see the newly created rule on the Integration -> Rules page. Click the Actions(Sink) tab and you can see the new TDengine Sink.
You can also click Integration -> Flow Designer to view the topology and you can see that the messages under topic t/#
are sent and saved to TDengine after parsing by rule my_rule
.
Test the Rule
Use MQTTX to send a message to topic t/1
to trigger an online/offline event.
mqttx pub -i emqx_c -t t/1 -m '{ "msg": "hello TDengine" }'
Check the running status of the two Sinks, there should be one new incoming and one new outgoing message.
Check whether the data is written into the t_mqtt_msg
data table.
taos> select * from t_mqtt_msg;
ts | msgid | mqtt_topic | qos | payload | arrived |
==============================================================================================================================================================
2023-02-13 06:10:53.787 | 0005F48EB5A83865F440000014F... | t/1 | 0 | { "msg": "hello TDengine" } | 2023-02-13 06:10:53.787 |
Query OK, 1 row(s) in set (0.002968s)
emqx_client_events
table:
taos> select * from emqx_client_events;
ts | clientid | event |
============================================================================================
2023-02-13 06:10:53.777 | emqx_c | client.connected |
2023-02-13 06:10:53.791 | emqx_c | client.disconnected |
Query OK, 2 row(s) in set (0.002327s)