创建 TimescaleDB 规则

创建 TimescaleDB 规则

  1. 搭建 TimescaleDB 数据库环境,以 MaxOS X 为例:
$ docker pull timescale/timescaledb

$ docker run -d --name timescaledb -p 5432:5432 -e POSTGRES_PASSWORD=password timescale/timescaledb:latest-pg11

$ docker exec -it timescaledb psql -U postgres

## 创建并连接 tutorial 数据库
CREATE database tutorial;

\c tutorial

CREATE EXTENSION IF NOT EXISTS timescaledb CASCADE;
  1. 初始化 TimescaleDB 表:
$ docker exec -it timescaledb psql -U postgres -d tutorial

创建 conditions 表:

``` CREATE TABLE conditions ( time TIMESTAMPTZ NOT NULL, location TEXT NOT NULL, temperature DOUBLE PRECISION NULL, humidity DOUBLE PRECISION NULL );

SELECT create_hypertable('conditions', 'time');


  1. 创建规则:

> 打开 [emqx dashboard ![创建 TimescaleDB 规则 - 图1](https://static.bookstack.cn/projects/emqx-enterprise-3.0-zh/42ef9bddde97e5626891f292670e4d69.svg) (opens new window)](<http://127.0.0.1:18083/#/rules>) ,选择左侧的 “规则” 选项卡。
> 
> 选择触发事件 “消息发布”,然后填写规则 SQL:
> 
> 3.4.0 以及更老版本:
> 
> ```
SELECT
  payload.temp as temp,
  payload.humidity as humidity,
  payload.location as location
FROM
  "message.publish"

3.4.1 以及以后版本:

``` SELECT json_decode(payload) as p, p.temp as temp, p.humidity as humidity, p.location as location FROM "message.publish"

> 
> ![image](https://static.bookstack.cn/projects/emqx-enterprise-3.0-zh/caa111ebcb066adb6a8a367b852bc610.png) 

  1. 关联动作:

> 在 “响应动作” 界面选择 “添加”,然后在 “动作” 下拉框里选择 “保存数据到 TimescaleDB”。
> 
> ![image](https://static.bookstack.cn/projects/emqx-enterprise-3.0-zh/3bb94f7bc502b6111c38e9427d925d0c.png) 

  1. 填写动作参数:

> “保存数据到 TimescaleDB” 动作需要两个参数:
> 
> 1). SQL 模板。这个例子里我们向 TimescaleDB 插入一条数据,SQL 模板为:
> 
> ```
insert into conditions(time, location, temperature, humidity) values (NOW(), ${location}, ${temp}, ${humidity})

插入数据之前,SQL 模板里的 ${key} 占位符会被替换为相应的值。

2). 关联资源。现在资源下拉框为空,可以点击右上角的 “新建资源” 来创建一个 TimescaleDB 资源:

image

选择 “TimescaleDB 资源”。

image

  1. 填写资源配置:

数据库名填写 “tutorial”,用户名填写 “postgres”,密码填写 “password”,其他配置保持默认值,然后点击 “测试连接” 按钮,确保连接测试成功。

最后点击 “新建” 按钮。

image

  1. 返回响应动作界面,点击 “确认”。

image

  1. 返回规则创建界面,点击 “新建”。

image

  1. 规则已经创建完成,现在发一条数据:

Topic: “t/1”

QoS: 0

Retained: false

Payload: “{“temp”:24,”humidity”:30,”location”:”hangzhou”}”

然后检查 TimescaleDB 表,新的 record 是否添加成功:

tutorial=# SELECT * FROM conditions LIMIT 100; time | location | temperature | humidity -------------------------------+----------+-------------+---------- 2019-06-27 01:41:08.752103+00 | hangzhou | 24 | 30

在规则列表里,可以看到刚才创建的规则的命中次数已经增加了 1:

image