加速PostgreSQL查询,其中数据在两个日期之间

Rog*_*ger 6 sql postgresql performance spatial-index

我有一个大表(> 50米行),其中包含一些带有ID和时间戳的数据:

id, timestamp, data1, ..., dataN
Run Code Online (Sandbox Code Playgroud)

...打开多列索引(id, timestamp).

我需要查询表以选择具有特定ID的所有行,其中时间戳在两个日期之间,我目前正在使用:

SELECT * FROM mytable WHERE id = x AND timestamp BETWEEN y AND z
Run Code Online (Sandbox Code Playgroud)

目前在高端机器上需要2分钟(2x 3Ghz双核Xeons w/HT,16GB RAM,RAID 0中2x 1TB驱动器),我真的很想加速它.

我发现这个提示建议使用空间索引,但它提供的示例是IP地址.然而,速度增加(436s到3s)令人印象深刻.

我如何使用时间戳?

Kon*_*rus 6

该提示仅适用于您有两列A和B并使用以下查询:

where 'a' between A and B
Run Code Online (Sandbox Code Playgroud)

那不是:

where A between 'a' and 'b'
Run Code Online (Sandbox Code Playgroud)

使用索引date(column)而不是column可以加快它的速度.


KM.*_*KM. 0

确保索引是 TableID+TableTimestamp,然后执行如下查询:

SELECT
    ....
    FROM YourTable
    WHERE TableID=..YourID.. 
        AND TableTimestamp>=..startrange.. 
        AND TableTimestamp<=..endrange..
Run Code Online (Sandbox Code Playgroud)

如果您在 WHERE 中将函数应用于表的 TableTimestamp 列,您将无法完全使用索引。

如果您已经执行了所有这些操作,那么您的硬件可能无法胜任该任务。

如果您使用的是 8.2 或更高版本,您应该尝试:

WHERE (TableID, TableTimestamp) >= (..YourID.., ..startrange.. ) 
    and (TableID, TableTimestamp) <= (..YourID.., ..endrange..)
Run Code Online (Sandbox Code Playgroud)