Save data to TimescaleDB
Initiate the TimescaleDB table:
CREATE TABLE conditions (
time TIMESTAMPTZ NOT NULL,
humidity DOUBLE PRECISION NULL
);
Create a rule:
Go to EMQX Dashboard (opens new window), select the “rule” tab on the menu to the left.
Select “message.publish”, then type in the following SQL:
Bind an action:
Click on the “+ Add” button under “Action Handler”, and then select “Data to TimescaleDB” in the pop-up dialog window.
Fill in the parameters required by the action:
1). SQL template. SQL template is the sql command you’d like to run when the action is triggered. In this example we’ll insert a message into timescaledb, so type in the following sql template:
Before data is inserted into the table, placeholders like ${key} will be replaced by the corresponding values.
2). Bind a resource to the action. Since the dropdown list “Resource” is empty for now, we create a new resource by clicking on the “New Resource” to the top right, and then select “TimescaleDB”:
Configure the resource:
Set “TimescaleDB Database” to “tutorial”, “TimescaleDB User” to “postgres”, “TimescaleDB Password” to “password”, and keep all other configs as default, and click on the “Testing Connection” button to make sure the connection can be created successfully, and then click on the “Create” button.
Back to the “Actions” dialog, and then click on the “Confirm” button.
Back to the creating rule page, then click on “Create” button. The rule we created will be show in the rule list:
We have finished, testing the rule by sending an MQTT message to emqx:
Then inspect the TimescaleDB table, verify a new record has been inserted:
tutorial=# SELECT * FROM conditions LIMIT 100;
The output data could look like
this:
time | location | temperature | humidity
\------------------------------+----------+-------------+----------2019-06-27
And from the rule list, verify that the “Matched” column has increased to 1: