【发布时间】:2022-01-15 21:42:24
【问题描述】:
我在 postgresql 数据库中有一个启用了 timescaledb 扩展的表,如下所示:
+------------+--------------------------+-------------+
| Column | Type | Modifiers |
|------------+--------------------------+-------------|
| time | timestamp with time zone | not null |
| value | double precision | not null |
| being | metric_being | not null |
| device | integer | not null |
+------------+--------------------------+-------------+
还有一个索引在桌子上:
"metrics_device_time_idx" btree (device, "time" DESC)
但是当我使用 Group By 查询表时:
explain select max(time), device from metrics group by device;
它不使用索引:
+----------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------+
| QUERY PLAN |
|-------------------------------------------------------------------------------------------------------------------|
| Finalize GroupAggregate (cost=104577.41..104588.61 rows=22 width=12) |
| Group Key: _hyper_9_95_chunk.device |
| -> Gather Merge (cost=104577.41..104587.95 rows=88 width=12) |
| Workers Planned: 4 |
| -> Sort (cost=103577.35..103577.41 rows=22 width=12) |
| Sort Key: _hyper_9_95_chunk.device |
| -> Partial HashAggregate (cost=103576.64..103576.86 rows=22 width=12) |
| Group Key: _hyper_9_95_chunk.device |
| -> Parallel Append (cost=0.00..95035.06 rows=1708317 width=12) |
| -> Parallel Seq Scan on _hyper_9_95_chunk (cost=0.00..44602.70 rows=1122370 width=12) |
| -> Parallel Seq Scan on _hyper_9_92_chunk (cost=0.00..24807.61 rows=756061 width=12) |
+-------------------------------------------------------------------------------------------------------------------+
最后开始有点慢。另一方面,真正快 10 倍的是
select max(time), 29 from metrics where device = 29
union
select max(time), 30 from metrics where device = 30
union
...
为什么会这样?我可以使用group by 更改我的索引或查询以加快查询速度吗?为什么union 这么快?
【问题讨论】:
-
你是如何在 timescaledb 中对表进行分区的?
-
没有空间分区,超表创建时使用:
select create_hypertable ('metrics', 'time'); -
那么,一个设备的时间是跨多个时间序列交错的?对于您的查询,这似乎不是最佳选择。
标签: sql postgresql timescaledb