feat: 实现父表索引策略,确保仅在父表创建索引,避免子表重复索引维护

This commit is contained in:
2026-03-03 18:22:17 +08:00
parent cf61e8dac6
commit 0bd10dbc1e
4 changed files with 68 additions and 2 deletions

View File

@@ -38,7 +38,9 @@ ALTER TABLE rcu_action.rcu_action_events
ALTER TABLE rcu_action.rcu_action_events
ADD COLUMN IF NOT EXISTS loop_name VARCHAR(255);
-- Indexes for performance
-- Indexes for performance (ONLY on parent partitioned table)
-- PostgreSQL will create/attach corresponding child-partition indexes automatically.
-- Do not create duplicated indexes on partition child tables.
CREATE INDEX IF NOT EXISTS idx_rcu_action_hotel_id ON rcu_action.rcu_action_events (hotel_id);
CREATE INDEX IF NOT EXISTS idx_rcu_action_room_id ON rcu_action.rcu_action_events (room_id);
CREATE INDEX IF NOT EXISTS idx_rcu_action_device_id ON rcu_action.rcu_action_events (device_id);

View File

@@ -1,7 +1,24 @@
import { logger } from '../utils/logger.js';
import dbManager from './databaseManager.js';
const PARENT_TABLE = 'rcu_action.rcu_action_events';
const PARENT_INDEX_STATEMENTS = [
'CREATE INDEX IF NOT EXISTS idx_rcu_action_hotel_id ON rcu_action.rcu_action_events (hotel_id);',
'CREATE INDEX IF NOT EXISTS idx_rcu_action_room_id ON rcu_action.rcu_action_events (room_id);',
'CREATE INDEX IF NOT EXISTS idx_rcu_action_device_id ON rcu_action.rcu_action_events (device_id);',
'CREATE INDEX IF NOT EXISTS idx_rcu_action_direction ON rcu_action.rcu_action_events (direction);',
'CREATE INDEX IF NOT EXISTS idx_rcu_action_cmd_word ON rcu_action.rcu_action_events (cmd_word);',
'CREATE INDEX IF NOT EXISTS idx_rcu_action_action_type ON rcu_action.rcu_action_events (action_type);',
'CREATE INDEX IF NOT EXISTS idx_rcu_action_query_main ON rcu_action.rcu_action_events (hotel_id, room_id, ts_ms DESC);'
];
class PartitionManager {
async ensureParentIndexes(client) {
for (const sql of PARENT_INDEX_STATEMENTS) {
await client.query(sql);
}
}
/**
* Calculate the start and end timestamps (milliseconds) for a given date.
* @param {Date} date - The date to calculate for.
@@ -33,6 +50,7 @@ class PartitionManager {
const client = await dbManager.pool.connect();
try {
logger.info(`Starting partition check for the next ${daysAhead} days...`);
await this.ensureParentIndexes(client);
const now = new Date();
for (let i = 0; i < daysAhead; i++) {
@@ -52,7 +70,7 @@ class PartitionManager {
logger.info(`Creating partition ${partitionName} for range [${startMs}, ${endMs})`);
const createSql = `
CREATE TABLE IF NOT EXISTS ${partitionName}
PARTITION OF rcu_action.rcu_action_events
PARTITION OF ${PARENT_TABLE}
FOR VALUES FROM (${startMs}) TO (${endMs});
`;
await client.query(createSql);