

1
前言
MatrixDB 4.2版本发布后,MatrixGate推出了一个新特性—UPSERT。
本文将详细介绍UPSERT语义及MatrixGate新特性的使用方法。
什么是UPSERT?
UPSERT 就是 UPDATE 和 INSERT 的结合。
实现一条SQL内自动插入或者更新:如果记录不存在则插入,如果记录存在则更新。
设备数据不是一次性发送全部,而是分批次发送,需要按设备号和时间戳为主键进行合并
设备数据可能会重复发送,对于重复数据要做更新而不是重复插入

而UPSERT语义则直接实现了该逻辑。下面演示一下UPSERT的用法。
2
UPSERT的使用方法
准备数据表
DROP TABLE IF EXISTS upsert_demo;CREATE TABLE upsert_demo (ts timestamp, tagid int, c1 int, c2 float4, UNIQUE(ts, tagid)) DISTRIBUTED BY (tagid);
使用UPSERT语义接入数据
SQL方式
INSERT INTO upsert_demo VALUES ('2020-11-11', 1, 10, NULL)ON CONFLICT (ts, tagid)DO UPDATE SETc1 = coalesce(EXCLUDED.c1, upsert_demo.c1),c2 = coalesce(EXCLUDED.c2, upsert_demo.c2);INSERT INTO upsert_demo VALUES ('2020-11-11', 1, NULL, 20.1)ON CONFLICT (ts, tagid)DO UPDATE SETc1 = coalesce(EXCLUDED.c1, upsert_demo.c1),c2 = coalesce(EXCLUDED.c2, upsert_demo.c2);
通过这种方式,实现了相同设备、相同时间的指标数据合并。
test=# select * from upsert_demo ;ts | tagid | c1 | c2---------------------+-------+----+------2020-11-11 00:00:00 | 1 | 10 | 20.1(1 row)
查询upsert_demo可以看到,c1和c2的数据是期望的结果。

MatrixGate方式
相比使用SQL方式来接入,MatrixGate作为MatrixDB高性能数据接入工具,在4.2版本中也加入了对UPSERT语义的支持,所以在生产环境中,更加推荐用户选择使用MatrixGate方式接入,性能可以提升百倍。
下面演示如何使用MatrixGate的UPSERT语义:
ts|tagid|c1|c22020-11-11|1|10|
ts|tagid|c1|c22020-11-11|1||20.12020-11-11|2||100.52020-11-11|2|200|
2. 执行Gate
tail -n +2 tmp/upsert_demo1.dat | mxgated --source stdin \--db-database test \--db-master-host localhost \--db-master-port 5432 \--db-user mxadmin \--time-format raw \--delimiter "|" \--target upsert_demo \--upsert-key ts \--upsert-key tagid
结果
test=# select * from upsert_demo ;ts | tagid | c1 | c2---------------------+-------+----+----2020-11-11 00:00:00 | 1 | 10 |(1 row)
载入第二个文件
tail -n +2 tmp/upsert_demo2.dat | mxgated --source stdin \--db-database test \--db-master-host localhost \--db-master-port 5432 \--db-user mxadmin \--time-format raw \--delimiter "|" \--target upsert_demo \--upsert-key ts \--upsert-key tagid
结果
test=# select * from upsert_demo;ts | tagid | c1 | c2---------------------+-------+-----+-------2020-11-11 00:00:00 | 1 | 10 | 20.12020-11-11 00:00:00 | 2 | 200 | 100.5(2 rows)
3. Q&A

3
总结
官网下载地址:
https://ymatrix.cn/download
推 荐 阅 读







转发,点赞,在看,安排一下?
文章转载自 yMatrix,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。







