优化超表分片逻辑, 一天一片
This commit is contained in:
@@ -124,7 +124,7 @@ func (ps *PostgresStorage) Migrate(models ...interface{}) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// 如果是 TimescaleDB, 则将 sensor_data 转换为 hypertable
|
||||
// 如果是 TimescaleDB, 则将部分表转换为 hypertable
|
||||
if ps.isTimescaleDB {
|
||||
ps.logger.Info("检测到 TimescaleDB, 准备进行超表转换")
|
||||
if err := ps.creatingHyperTable(); err != nil {
|
||||
@@ -139,16 +139,18 @@ func (ps *PostgresStorage) creatingHyperTable() error {
|
||||
// 将 sensor_data 转换为超表
|
||||
// 使用 if_not_exists => TRUE 保证幂等性
|
||||
// 'time' 是 SensorData 模型中定义的时间列
|
||||
sqlSensorData := "SELECT create_hypertable('sensor_data', 'time', if_not_exists => TRUE);"
|
||||
// 设置 chunk_time_interval 为 1 天, 以优化按天查询的性能
|
||||
sqlSensorData := "SELECT create_hypertable('sensor_data', 'time', chunk_time_interval => INTERVAL '1 day', if_not_exists => TRUE);"
|
||||
if err := ps.db.Exec(sqlSensorData).Error; err != nil {
|
||||
ps.logger.Errorw("将 sensor_data 转换为超表失败", "error", err)
|
||||
return fmt.Errorf("将 sensor_data 转换为超表失败: %w", err)
|
||||
}
|
||||
ps.logger.Info("成功将 sensor_data 转换为超表 (或已转换)")
|
||||
ps.logger.Info("成功将 sensor_data 转换为超表 (或已转换), chunk 间隔为 1 天")
|
||||
|
||||
// 将 device_command_log 转换为超表
|
||||
// 'sent_at' 是 DeviceCommandLog 模型中定义的时间列
|
||||
sqlDeviceCommandLogs := "SELECT create_hypertable('device_command_log', 'sent_at', if_not_exists => TRUE);"
|
||||
// 设置 chunk_time_interval 为 1 天
|
||||
sqlDeviceCommandLogs := "SELECT create_hypertable('device_command_log', 'sent_at', chunk_time_interval => INTERVAL '1 day', if_not_exists => TRUE);"
|
||||
if err := ps.db.Exec(sqlDeviceCommandLogs).Error; err != nil {
|
||||
ps.logger.Errorw("将 device_command_log 转换为超表失败", "error", err)
|
||||
return fmt.Errorf("将 device_command_log 转换为超表失败: %w", err)
|
||||
|
||||
Reference in New Issue
Block a user