1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
1
2
3
|
"""
SPU data transformer for Shoplazza products.
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
4
|
Transforms SPU and SKU data from MySQL into SPU-level ES documents with nested skus.
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
"""
import pandas as pd
import numpy as np
from typing import Dict, Any, List, Optional
from sqlalchemy import create_engine, text
from utils.db_connector import create_db_connection
class SPUTransformer:
"""Transform SPU and SKU data into SPU-level ES documents."""
def __init__(
self,
db_engine: Any,
tenant_id: str
):
"""
Initialize SPU transformer.
Args:
db_engine: SQLAlchemy database engine
tenant_id: Tenant ID for filtering data
"""
self.db_engine = db_engine
self.tenant_id = tenant_id
def load_spu_data(self) -> pd.DataFrame:
"""
Load SPU data from MySQL.
Returns:
DataFrame with SPU data
"""
query = text("""
SELECT
id, shop_id, shoplazza_id, handle, title, brief, description,
spu, vendor, vendor_url, seo_title, seo_description, seo_keywords,
image_src, image_width, image_height, image_path, image_alt,
tags, note, category,
shoplazza_created_at, shoplazza_updated_at, tenant_id,
creator, create_time, updater, update_time, deleted
FROM shoplazza_product_spu
WHERE tenant_id = :tenant_id AND deleted = 0
""")
with self.db_engine.connect() as conn:
df = pd.read_sql(query, conn, params={"tenant_id": self.tenant_id})
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
# Debug: Check if there's any data for this tenant_id
if len(df) == 0:
debug_query = text("""
SELECT
COUNT(*) as total_count,
SUM(CASE WHEN deleted = 0 THEN 1 ELSE 0 END) as active_count,
SUM(CASE WHEN deleted = 1 THEN 1 ELSE 0 END) as deleted_count
FROM shoplazza_product_spu
WHERE tenant_id = :tenant_id
""")
with self.db_engine.connect() as conn:
debug_df = pd.read_sql(debug_query, conn, params={"tenant_id": self.tenant_id})
if not debug_df.empty:
total = debug_df.iloc[0]['total_count']
active = debug_df.iloc[0]['active_count']
deleted = debug_df.iloc[0]['deleted_count']
print(f"DEBUG: tenant_id={self.tenant_id}: total={total}, active={active}, deleted={deleted}")
# Check what tenant_ids exist in the table
tenant_check_query = text("""
SELECT tenant_id, COUNT(*) as count, SUM(CASE WHEN deleted = 0 THEN 1 ELSE 0 END) as active
FROM shoplazza_product_spu
GROUP BY tenant_id
ORDER BY tenant_id
LIMIT 10
""")
with self.db_engine.connect() as conn:
tenant_df = pd.read_sql(tenant_check_query, conn)
if not tenant_df.empty:
print(f"DEBUG: Available tenant_ids in shoplazza_product_spu:")
for _, row in tenant_df.iterrows():
print(f" tenant_id={row['tenant_id']}: total={row['count']}, active={row['active']}")
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
return df
def load_sku_data(self) -> pd.DataFrame:
"""
Load SKU data from MySQL.
Returns:
DataFrame with SKU data
"""
query = text("""
SELECT
id, spu_id, shop_id, shoplazza_id, shoplazza_product_id,
shoplazza_image_id, title, sku, barcode, position,
price, compare_at_price, cost_price,
option1, option2, option3,
inventory_quantity, weight, weight_unit, image_src,
wholesale_price, note, extend,
shoplazza_created_at, shoplazza_updated_at, tenant_id,
creator, create_time, updater, update_time, deleted
FROM shoplazza_product_sku
WHERE tenant_id = :tenant_id AND deleted = 0
""")
with self.db_engine.connect() as conn:
df = pd.read_sql(query, conn, params={"tenant_id": self.tenant_id})
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
113
114
|
print(f"DEBUG: Loaded {len(df)} SKU records for tenant_id={self.tenant_id}")
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
|
return df
def transform_batch(self) -> List[Dict[str, Any]]:
"""
Transform SPU and SKU data into ES documents.
Returns:
List of SPU-level ES documents
"""
# Load data
spu_df = self.load_spu_data()
sku_df = self.load_sku_data()
if spu_df.empty:
return []
# Group SKUs by SPU
sku_groups = sku_df.groupby('spu_id')
documents = []
for _, spu_row in spu_df.iterrows():
spu_id = spu_row['id']
# Get SKUs for this SPU
skus = sku_groups.get_group(spu_id) if spu_id in sku_groups.groups else pd.DataFrame()
# Transform to ES document
doc = self._transform_spu_to_doc(spu_row, skus)
if doc:
documents.append(doc)
return documents
def _transform_spu_to_doc(
self,
spu_row: pd.Series,
skus: pd.DataFrame
) -> Optional[Dict[str, Any]]:
"""
Transform a single SPU row and its SKUs into an ES document.
Args:
spu_row: SPU row from database
skus: DataFrame with SKUs for this SPU
Returns:
ES document or None if transformation fails
"""
doc = {}
# Tenant ID (required)
doc['tenant_id'] = str(self.tenant_id)
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
168
169
|
# SPU ID
doc['spu_id'] = str(spu_row['id'])
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
|
# Handle
if pd.notna(spu_row.get('handle')):
doc['handle'] = str(spu_row['handle'])
# Title
if pd.notna(spu_row.get('title')):
doc['title'] = str(spu_row['title'])
# Brief
if pd.notna(spu_row.get('brief')):
doc['brief'] = str(spu_row['brief'])
# Description
if pd.notna(spu_row.get('description')):
doc['description'] = str(spu_row['description'])
# SEO fields
if pd.notna(spu_row.get('seo_title')):
doc['seo_title'] = str(spu_row['seo_title'])
if pd.notna(spu_row.get('seo_description')):
doc['seo_description'] = str(spu_row['seo_description'])
if pd.notna(spu_row.get('seo_keywords')):
doc['seo_keywords'] = str(spu_row['seo_keywords'])
# Vendor
if pd.notna(spu_row.get('vendor')):
doc['vendor'] = str(spu_row['vendor'])
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
198
199
200
|
# Tags
if pd.notna(spu_row.get('tags')):
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
201
|
doc['tags'] = str(spu_row['tags'])
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
202
203
204
205
|
# Category
if pd.notna(spu_row.get('category')):
doc['category'] = str(spu_row['category'])
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
206
207
208
209
210
211
212
213
|
# Image URL
if pd.notna(spu_row.get('image_src')):
image_src = str(spu_row['image_src'])
if not image_src.startswith('http'):
image_src = f"//{image_src}" if image_src.startswith('//') else image_src
doc['image_url'] = image_src
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
214
215
|
# Process SKUs
skus_list = []
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
216
217
218
219
|
prices = []
compare_prices = []
for _, sku_row in skus.iterrows():
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
220
221
222
223
|
sku_data = self._transform_sku_row(sku_row)
if sku_data:
skus_list.append(sku_data)
if 'price' in sku_data and sku_data['price'] is not None:
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
224
|
try:
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
225
|
prices.append(float(sku_data['price']))
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
226
227
|
except (ValueError, TypeError):
pass
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
228
|
if 'compare_at_price' in sku_data and sku_data['compare_at_price'] is not None:
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
229
|
try:
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
230
|
compare_prices.append(float(sku_data['compare_at_price']))
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
231
232
233
|
except (ValueError, TypeError):
pass
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
234
|
doc['skus'] = skus_list
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
235
236
237
238
239
240
241
242
243
244
245
246
247
248
|
# Calculate price ranges
if prices:
doc['min_price'] = float(min(prices))
doc['max_price'] = float(max(prices))
else:
doc['min_price'] = 0.0
doc['max_price'] = 0.0
if compare_prices:
doc['compare_at_price'] = float(max(compare_prices))
else:
doc['compare_at_price'] = None
|
cd3799c6
tangwang
tenant2 1w测试数据 mo...
|
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
|
# Time fields - convert datetime to ISO format string for ES DATE type
if pd.notna(spu_row.get('create_time')):
create_time = spu_row['create_time']
if hasattr(create_time, 'isoformat'):
doc['create_time'] = create_time.isoformat()
else:
doc['create_time'] = str(create_time)
if pd.notna(spu_row.get('update_time')):
update_time = spu_row['update_time']
if hasattr(update_time, 'isoformat'):
doc['update_time'] = update_time.isoformat()
else:
doc['update_time'] = str(update_time)
if pd.notna(spu_row.get('shoplazza_created_at')):
shoplazza_created_at = spu_row['shoplazza_created_at']
if hasattr(shoplazza_created_at, 'isoformat'):
doc['shoplazza_created_at'] = shoplazza_created_at.isoformat()
else:
doc['shoplazza_created_at'] = str(shoplazza_created_at)
if pd.notna(spu_row.get('shoplazza_updated_at')):
shoplazza_updated_at = spu_row['shoplazza_updated_at']
if hasattr(shoplazza_updated_at, 'isoformat'):
doc['shoplazza_updated_at'] = shoplazza_updated_at.isoformat()
else:
doc['shoplazza_updated_at'] = str(shoplazza_updated_at)
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
278
279
|
return doc
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
280
|
def _transform_sku_row(self, sku_row: pd.Series) -> Optional[Dict[str, Any]]:
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
281
|
"""
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
282
|
Transform a SKU row into a SKU object.
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
283
284
285
286
287
|
Args:
sku_row: SKU row from database
Returns:
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
288
|
SKU dictionary or None
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
289
|
"""
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
290
|
sku_data = {}
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
291
|
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
292
293
|
# SKU ID
sku_data['sku_id'] = str(sku_row['id'])
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
294
295
296
|
# Title
if pd.notna(sku_row.get('title')):
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
297
|
sku_data['title'] = str(sku_row['title'])
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
298
299
300
301
|
# Price
if pd.notna(sku_row.get('price')):
try:
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
302
|
sku_data['price'] = float(sku_row['price'])
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
303
|
except (ValueError, TypeError):
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
304
|
sku_data['price'] = None
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
305
|
else:
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
306
|
sku_data['price'] = None
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
307
308
309
310
|
# Compare at price
if pd.notna(sku_row.get('compare_at_price')):
try:
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
311
|
sku_data['compare_at_price'] = float(sku_row['compare_at_price'])
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
312
|
except (ValueError, TypeError):
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
313
|
sku_data['compare_at_price'] = None
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
314
|
else:
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
315
|
sku_data['compare_at_price'] = None
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
316
317
318
|
# SKU
if pd.notna(sku_row.get('sku')):
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
319
|
sku_data['sku'] = str(sku_row['sku'])
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
320
321
322
323
|
# Stock
if pd.notna(sku_row.get('inventory_quantity')):
try:
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
324
|
sku_data['stock'] = int(sku_row['inventory_quantity'])
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
325
|
except (ValueError, TypeError):
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
326
|
sku_data['stock'] = 0
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
327
|
else:
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
328
|
sku_data['stock'] = 0
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
329
330
331
332
333
334
335
336
337
338
339
|
# Options (from option1, option2, option3)
options = {}
if pd.notna(sku_row.get('option1')):
options['option1'] = str(sku_row['option1'])
if pd.notna(sku_row.get('option2')):
options['option2'] = str(sku_row['option2'])
if pd.notna(sku_row.get('option3')):
options['option3'] = str(sku_row['option3'])
if options:
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
340
|
sku_data['options'] = options
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
341
|
|
cadc77b6
tangwang
索引字段名、变量名、API数据结构...
|
342
|
return sku_data
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
|
|