Commit cabf413d by 林冲

_batch_update_settle_rule_goods_type_group_id 优化,使用临时表关联更新,优化大数据量场景性能

1 parent cad39fb6
...@@ -803,72 +803,84 @@ class SceneSplitProcessor: ...@@ -803,72 +803,84 @@ class SceneSplitProcessor:
def _batch_update_settle_rule_goods_type_group_id(self, insert_batch): def _batch_update_settle_rule_goods_type_group_id(self, insert_batch):
""" """
批量更新表2(dj_car_life_merchant_goods_type_group_settle_rule)中的 goods_type_group_id 批量更新表2(dj_car_life_merchant_goods_type_group_settle_rule)中的 goods_type_group_id
使用临时表关联更新,优化大数据量场景性能
""" """
self.logger.info(" 开始批量更新表2中的 goods_type_group_id...") self.logger.info(" 开始批量更新表2中的 goods_type_group_id...")
settle_rule_table = 'dj_car_life_merchant_goods_type_group_settle_rule' settle_rule_table = 'dj_car_life_merchant_goods_type_group_settle_rule'
goods_type_group_table = 'dj_car_life_goods_type_group' goods_type_group_table = 'dj_car_life_goods_type_group'
temp_table = 'tmp_settle_rule_update_batch'
# 准备批量查询的参数:收集所有 (old_id, base_scene_code) 对 total_count = len(insert_batch)
old_id_scene_pairs = [] self.logger.info(f" 待更新数据量: {total_count} 条")
item_map = {} # 用于后续匹配:key=(old_id, base_scene_code), value=new_settle_rule_group_id
try:
for item in insert_batch: # 1. 创建临时表
old_id = item['old_id'] create_temp_sql = f"""
base_scene_code = item['base_scene_code'] CREATE TEMPORARY TABLE {temp_table} (
new_settle_rule_group_id = item['new_settle_rule_group_id'] old_id BIGINT NOT NULL COMMENT '原goods_type_group的ID',
base_scene_code VARCHAR(20) NOT NULL COMMENT '场景编码',
pair = (old_id, base_scene_code) new_settle_rule_group_id BIGINT NOT NULL COMMENT '新的settle_rule记录ID',
old_id_scene_pairs.append(pair) INDEX idx_old_scene (old_id, base_scene_code),
item_map[pair] = new_settle_rule_group_id INDEX idx_settle_rule (new_settle_rule_group_id)
) ENGINE=MEMORY DEFAULT CHARSET=utf8mb4 COMMENT='临时表:用于批量更新settle_rule的goods_type_group_id';
"""
self.db.execute_update(create_temp_sql)
self.logger.info(f" 临时表 {temp_table} 创建成功")
# 批量查询所有新ID # 2. 分批插入临时表(每批1万条,避免SQL过长)
new_id_mapping = self.id_mapper.batch_get_new_ids_by_scene( insert_batch_size = 10000
goods_type_group_table, old_id_scene_pairs total_batches = (total_count + insert_batch_size - 1) // insert_batch_size
) self.logger.info(f" 开始插入临时表,共 {total_batches} 个批次")
# 构建更新批次 for batch_idx in range(total_batches):
update_batch = [] start_idx = batch_idx * insert_batch_size
for pair, new_settle_rule_group_id in item_map.items(): end_idx = min(start_idx + insert_batch_size, total_count)
new_goods_type_group_id = new_id_mapping.get(pair) batch = insert_batch[start_idx:end_idx]
if new_goods_type_group_id:
update_batch.append({
'settle_rule_id': new_settle_rule_group_id,
'new_goods_type_group_id': new_goods_type_group_id
})
# 批量更新 # 构建批量插入SQL
batch_size = 100000 values = []
total_count = len(update_batch) for item in batch:
total_batches = (total_count + batch_size - 1) // batch_size old_id = item['old_id']
self.logger.info(f" 开始批量更新表2,共 {total_batches} 个批次,每批 {batch_size} 条") base_scene_code = item['base_scene_code']
new_settle_rule_group_id = item['new_settle_rule_group_id']
values.append(f"({old_id}, '{base_scene_code}', {new_settle_rule_group_id})")
update_count = 0 insert_sql = f"""
for batch_idx in range(total_batches): INSERT INTO {temp_table} (old_id, base_scene_code, new_settle_rule_group_id)
start_idx = batch_idx * batch_size VALUES {','.join(values)};
end_idx = min(start_idx + batch_size, total_count) """
batch = update_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建 CASE WHEN 批量更新SQL self.db.execute_update(insert_sql)
case_when = [] self.logger.info(f" 临时表插入进度: {batch_idx + 1}/{total_batches},本批 {len(batch)} 条")
ids = []
for item in batch:
case_when.append(f"WHEN id = {item['settle_rule_id']} THEN {item['new_goods_type_group_id']}")
ids.append(str(item['settle_rule_id']))
# 3. 一次性关联更新(核心优化:避免大量OR条件和CASE WHEN)
update_sql = f""" update_sql = f"""
UPDATE {settle_rule_table} UPDATE {settle_rule_table} sr
SET goods_type_group_id = CASE INNER JOIN {temp_table} tmp ON sr.id = tmp.new_settle_rule_group_id
{' '.join(case_when)} INNER JOIN tmp_rule_id_mapping map ON
END map.table_name = '{goods_type_group_table}'
WHERE id IN ({','.join(ids)}); AND map.old_id = tmp.old_id
AND map.base_scene_code = tmp.base_scene_code
SET sr.goods_type_group_id = map.new_id;
""" """
self.logger.info(" 开始执行关联更新...")
if self.db.execute_update(update_sql): if self.db.execute_update(update_sql):
update_count += len(batch) self.logger.info(f" 表2更新完成,共更新 {total_count} 条记录")
self.logger.info(f" 批次 {batch_num}/{total_batches} 更新完成,本批 {len(batch)} 条,累计 {update_count} 条") else:
self.logger.error(" 表2更新失败")
self.logger.info(f" 表2更新完成,共更新 {update_count} 条记录")
except Exception as e:
self.logger.error(f" 批量更新表2失败: {e}")
raise
finally:
# 4. 清理临时表
try:
drop_sql = f"DROP TEMPORARY TABLE IF EXISTS {temp_table};"
self.db.execute_update(drop_sql)
self.logger.info(f" 临时表 {temp_table} 已清理")
except Exception as e:
self.logger.warning(f" 清理临时表失败: {e}")
def _update_division_rule_group_goods_type_group_id(self): def _update_division_rule_group_goods_type_group_id(self):
""" """
...@@ -1260,7 +1272,7 @@ class SceneSplitProcessor: ...@@ -1260,7 +1272,7 @@ class SceneSplitProcessor:
self.logger.info(f" 收集到 {total_count} 条需要插入的记录") self.logger.info(f" 收集到 {total_count} 条需要插入的记录")
# 批量插入 # 批量插入
batch_size = 100000 batch_size = 200000
total_batches = (total_count + batch_size - 1) // batch_size total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量插入,共 {total_batches} 个批次,每批 {batch_size} 条") self.logger.info(f" 开始批量插入,共 {total_batches} 个批次,每批 {batch_size} 条")
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!