如何在timecaledb上无需顺序扫描的情况下有效获取每个资产的最后时间戳?

问题描述 投票:1回答:3

我有一张桌子

| Asset |   timestamp   | open | high | low | close | volume |
|-------|---------------|------|------|-----|-------|--------|
| AAPL  | 1551274920000 | 200  | 300  | 200 | 250   | 10240  |
| AAPL  | 1551274980000 | 201.4| 299.5| 200 | 244.5 | 11871  |
| GOOG  | 1551274980000 | 471.2| 488.2|464.6| 474.84| 5476.58|

如何获取每个资产的最新时间戳。这是我到目前为止所尝试的

方法1

SELECT symbol, max(ts) from ohlc_60 group by symbol;

This seems to scan all the chunks
explain select symbol, max(ts) from ohlc_60 group by symbol;
                                      QUERY PLAN                                      
--------------------------------------------------------------------------------------
 HashAggregate  (cost=1199.37..1201.37 rows=200 width=16)
   Group Key: ohlc_60.symbol
   ->  Append  (cost=0.00..1014.27 rows=37019 width=16)
         ->  Seq Scan on binance_ohlc_60  (cost=0.00..0.00 rows=1 width=40)
         ->  Seq Scan on _hyper_67_199_chunk  (cost=0.00..197.81 rows=8681 width=15)
         ->  Seq Scan on _hyper_67_200_chunk  (cost=0.00..284.32 rows=13032 width=15)
         ->  Seq Scan on _hyper_67_201_chunk  (cost=0.00..281.14 rows=12414 width=15)
         ->  Seq Scan on _hyper_67_202_chunk  (cost=0.00..48.41 rows=2141 width=15)
         ->  Seq Scan on _hyper_67_203_chunk  (cost=0.00..17.50 rows=750 width=40)
(9 rows)

我目前将1m数据存储到1小时块中,但可能会将它们变成1天块。我需要获取每个资产的最后时间戳而不进行顺序扫描,任何建议都非常受欢迎?

sql postgresql greatest-n-per-group timescaledb
3个回答
2
投票

来自TimescaleDB的文档的最后一点查询:

https://docs.timescale.com/v1.2/using-timescaledb/reading-data#last-point


2
投票

您的查询应该从以下索引中受益:

CREATE INDEX idx ON ohlc_60 (symbol, ts);

这应该起作用的原因是你要求每个symbol组的时间戳的最大值。这可以通过扫描B树轻松获得。


1
投票

使用相关子查询

select t1.* from table_name t1
where t1.timestamp=(select max(timestamp) from table_name t2 where t2.Asset=t1.Asset)

为了加快扫描速度,您需要在@Tim的其他答案中已经建议的相应列中调整索引

© www.soinside.com 2019 - 2024. All rights reserved.