Files
bianlidian/render/render数据回合到中间表.py
T
2026-11-29 13:07:10 +08:00

162 lines
5.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import json
import pandas as pd
import newsetting
from collections import defaultdict
# 1. 初始化数据库连接
tent = newsetting.All_Setting(host='192.168.5.2',port=3307, db='mt_newretail')
# 2. 计划有、结果无:expand.spu_id 对应 productslist.product_id(同 workid、同店)
# 补跑请优先用 render补跑_计划未落地.py(写入 target_rendet)
# WORKID_FILTER = '20260409'
WORKID_FILTER = '20261116'
query_sql = f'''
SELECT
t.shop_name,
t.mt_org_id,
t.poi_id_str,
t.address,
t.spu_id,
t.workid,
c.parent_id,
c.prox_data,
c.lat,
c.lng,
c.business_code
FROM temp_category_spu_expand AS t
LEFT JOIN productslist AS p
ON t.spu_id = p.product_id
AND t.poi_id_str = p.poi_id_str
LEFT JOIN (
SELECT poi_id_str, MAX(parent_id) as parent_id, MAX(prox_data) as prox_data, MAX(lat) as lat, MAX(lng) as lng, MAX(business_code) as business_code
FROM categorylist
GROUP BY poi_id_str
) AS c ON t.poi_id_str = c.poi_id_str
WHERE p.skus_id IS NULL
AND t.workid like '%{WORKID_FILTER}%'
ORDER BY t.shop_name
'''
print("正在查询缺失的 SPU 数据并关联坐标信息...")
data = tent.get_shoppingmalls(query_sql)
print(f"共发现 {len(data)} 条缺失的 SPU 记录")
# 3. 按店铺进行聚合
# Key 使用 (mt_org_id, poi_id_str, shop_name, address, workid, parent_id, prox, lat, lng, business_code)
grouped_data = defaultdict(list)
for i in data:
shop_name, mt_org_id, poi_id_str, address, spu_id, workid, parent_id, prox, lat, lng ,business_code = i
key = (mt_org_id, poi_id_str, shop_name, address, workid, parent_id, prox, lat, lng, business_code)
grouped_data[key].append(spu_id)
# 4. 创建符合 target_rendet 结构的新表
# 这里表名设为 temp_render_retry_tasks,但结构参考 target_rendet
NEW_TABLE = 'temp_render_retry_tasks'
CREATE_TABLE_SQL = f'''
CREATE TABLE IF NOT EXISTS `{NEW_TABLE}` (
`id` int NOT NULL AUTO_INCREMENT,
`parent_id` int DEFAULT 0,
`mt_org_id` varchar(255) DEFAULT NULL,
`poi_id_str` varchar(255) DEFAULT NULL,
`rank` int DEFAULT 0,
`spu_list` longtext,
`is__ok` int DEFAULT 0,
`prox` varchar(255) DEFAULT NULL,
`lat` varchar(255) DEFAULT NULL,
`lng` varchar(255) DEFAULT NULL,
`workid` varchar(255) DEFAULT NULL,
`business_code` varchar(255) DEFAULT NULL,
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `idx_org` (`mt_org_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
'''
print(f"正在创建/检查新表: {NEW_TABLE} (结构参考 target_rendet)...")
tent.update_data(CREATE_TABLE_SQL)
# 清空旧数据
tent.update_data(f"TRUNCATE TABLE `{NEW_TABLE}`")
insert_rows = []
for (mt_org_id,poi_id_str, shop_name, address, workid, parent_id, prox, lat, lng, business_code), spu_list in grouped_data.items():
# 将 spu_list 按 30 个一组进行切分 (chunking)
chunk_size = 30
for idx, i in enumerate(range(0, len(spu_list), chunk_size)):
chunk = spu_list[i : i + chunk_size]
rank = idx
spu_list_str = f"[{', '.join(map(str, chunk))}]"
if len(insert_rows) < 3:
print(f"店名: {shop_name}, Rank: {rank}, 合成后的 spu_list 示例: {spu_list_str[:100]}...")
insert_rows.append((
parent_id or 0, # parent_id
mt_org_id, # mt_org_id
poi_id_str, # poi_id_str
rank, # rank (分段索引)
spu_list_str, # spu_list (不带引号)
None, # is__ok
prox, # prox
lat, # lat
lng, # lng
workid, # workid
business_code # business_code
))
# 5. 批量插入聚合后的数据
if insert_rows:
print(f"正在将 {len(insert_rows)} 个任务的聚合数据插入到 {NEW_TABLE}...")
insert_sql = f'''
INSERT INTO `{NEW_TABLE}`
(parent_id, mt_org_id, poi_id_str, `rank`, spu_list, is__ok, prox, lat, lng, workid, business_code)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
'''
tent.write_data(insert_sql, insert_rows)
print(f"数据库插入完成!表名: {NEW_TABLE}")
else:
print("没有发现需要补抓的数据。")
input('状态进行确认数据条数是否出错')
insert_sql = f'''
INSERT INTO target_rendet (
parent_id,
mt_org_id,
poi_id_str,
`rank`,
spu_list,
is__ok,
prox,
lat,
lng,
workid,
business_code
)
SELECT
parent_id,
mt_org_id,
poi_id_str,
`rank`,
spu_list,
is__ok,
prox,
lat,
lng,
workid,
business_code
FROM temp_render_retry_tasks;
'''
tent.update_data(insert_sql)
print('render的数据已经回到主任务表')
# 6. 备份到 Excel
# if insert_rows:
# cols = ['parent_id', 'mt_org_id', 'poi_id_str', 'rank', 'spu_list', 'is__ok', 'prox', 'lat', 'lng', 'workid', 'business_code']
# df = pd.DataFrame(insert_rows, columns=cols)
# output_file = '二次合成_补抓任务_标准格式.xlsx'
# try:
# df.to_excel(output_file, index=False)
# print(f"Excel 备份已保存至: {output_file}")
# except Exception as e:
# print(f"Excel 保存失败: {e}")