Blame view

indexer/document_transformer.py 32.1 KB
0064e946   tangwang   feat: 增量索引服务、租户配置...
1
2
3
4
  """
  SPU文档转换器 - 公共转换逻辑。
  
  提取全量和增量索引共用的文档转换逻辑,避免代码冗余。
2e48a32d   tangwang   doc
5
6
7
  输出文档结构与 mappings/search_products.json  索引字段说明v2 一致,
   search/searcher  search/es_query_builder 使用。
  - 多语言字段:title, brief, description, vendor, category_path, category_name_text
e7a2c0b7   tangwang   img encode
8
  - 嵌套:specifications, skus;向量:title_embeddingimage_embedding(可选,需提供 image_encoder
0064e946   tangwang   feat: 增量索引服务、租户配置...
9
10
11
  """
  
  import pandas as pd
b2e50710   tangwang   BgeEncoder.encode...
12
  import numpy as np
0064e946   tangwang   feat: 增量索引服务、租户配置...
13
  import logging
0064e946   tangwang   feat: 增量索引服务、租户配置...
14
  from typing import Dict, Any, Optional, List
d350861f   tangwang   索引结构修改
15
  from indexer.product_enrich import build_index_content_fields
0064e946   tangwang   feat: 增量索引服务、租户配置...
16
17
18
  
  logger = logging.getLogger(__name__)
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
19
20
21
22
23
24
25
26
27
  class SPUDocumentTransformer:
      """SPU文档转换器,将SPU、SKU、Option数据转换为ES文档格式。"""
  
      def __init__(
          self,
          category_id_to_name: Dict[str, str],
          searchable_option_dimensions: List[str],
          tenant_config: Optional[Dict[str, Any]] = None,
          translator: Optional[Any] = None,
453992a8   tangwang   需求:
28
          encoder: Optional[Any] = None,
e7a2c0b7   tangwang   img encode
29
30
31
          enable_title_embedding: bool = True,
          image_encoder: Optional[Any] = None,
          enable_image_embedding: bool = False,
0064e946   tangwang   feat: 增量索引服务、租户配置...
32
33
34
35
36
37
38
39
40
      ):
          """
          初始化文档转换器。
  
          Args:
              category_id_to_name: 分类ID到名称的映射
              searchable_option_dimensions: 可搜索的option维度列表
              tenant_config: 租户配置(包含主语言和翻译配置)
              translator: 翻译器实例(可选,如果提供则启用翻译功能)
453992a8   tangwang   需求:
41
42
              encoder: 文本编码器实例(可选,用于生成title_embedding
              enable_title_embedding: 是否启用标题向量化(默认True
e7a2c0b7   tangwang   img encode
43
44
              image_encoder: 图片编码器实例(可选,需实现 encode_image_urls(urls) -> List[Optional[np.ndarray]]
              enable_image_embedding: 是否启用图片向量化(默认False
0064e946   tangwang   feat: 增量索引服务、租户配置...
45
46
47
48
49
          """
          self.category_id_to_name = category_id_to_name
          self.searchable_option_dimensions = searchable_option_dimensions
          self.tenant_config = tenant_config or {}
          self.translator = translator
453992a8   tangwang   需求:
50
51
          self.encoder = encoder
          self.enable_title_embedding = enable_title_embedding
e7a2c0b7   tangwang   img encode
52
53
          self.image_encoder = image_encoder
          self.enable_image_embedding = bool(enable_image_embedding and image_encoder is not None)
0064e946   tangwang   feat: 增量索引服务、租户配置...
54
  
d4cadc13   tangwang   翻译重构
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
      def _translate_index_languages(
          self,
          text: str,
          source_lang: str,
          index_languages: List[str],
          scene: str,
      ) -> Dict[str, Optional[str]]:
          translations: Dict[str, Optional[str]] = {}
          if not self.translator or not text or not str(text).strip():
              return translations
          for lang in index_languages:
              if lang == source_lang:
                  translations[lang] = text
                  continue
              translations[lang] = self.translator.translate(
                  text=text,
                  target_lang=lang,
                  source_lang=source_lang,
0fd2f875   tangwang   translate
73
                  scene=scene,
d4cadc13   tangwang   翻译重构
74
75
76
              )
          return translations
  
d350861f   tangwang   索引结构修改
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
      def _build_core_language_text_object(
          self,
          text: Optional[str],
          source_lang: str,
          scene: str = "general",
      ) -> Dict[str, str]:
          """
          构建与 mapping  core_language_text(_with_keyword) 对齐的对象。
          当前核心语言固定为 zh/en
          """
          if not text or not str(text).strip():
              return {}
  
          source_text = str(text).strip()
          obj: Dict[str, str] = {}
  
          if source_lang in CORE_INDEX_LANGUAGES:
              obj[source_lang] = source_text
  
          if self.translator:
              translations = self._translate_index_languages(
                  text=source_text,
                  source_lang=source_lang,
                  index_languages=CORE_INDEX_LANGUAGES,
                  scene=scene,
              )
              for lang in CORE_INDEX_LANGUAGES:
                  val = translations.get(lang)
                  if val and str(val).strip():
                      obj[lang] = str(val).strip()
  
          return obj
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
110
111
112
113
114
      def transform_spu_to_doc(
          self,
          tenant_id: str,
          spu_row: pd.Series,
          skus: pd.DataFrame,
be3f0d46   tangwang   /indexer/enrich-c...
115
116
          options: pd.DataFrame,
          fill_llm_attributes: bool = True,
0064e946   tangwang   feat: 增量索引服务、租户配置...
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
      ) -> Optional[Dict[str, Any]]:
          """
          将单个SPU行和其SKUs转换为ES文档。
  
          Args:
              tenant_id: 租户ID
              spu_row: SPU行数据
              skus: SKU数据DataFrame
              options: Option数据DataFrame
  
          Returns:
              ES文档字典
          """
          doc = {}
  
          # Tenant ID (required)
          doc['tenant_id'] = str(tenant_id)
  
          # SPU ID
          spu_id = spu_row['id']
          doc['spu_id'] = str(spu_id)
          
          # Validate required fields
          if pd.isna(spu_row.get('title')) or not str(spu_row['title']).strip():
              logger.error(f"SPU {spu_id} has no title, this may cause search issues")
  
          # 获取租户配置
2739b281   tangwang   多语言索引调整
144
          primary_lang = self.tenant_config.get('primary_language', 'en')
0064e946   tangwang   feat: 增量索引服务、租户配置...
145
  
453992a8   tangwang   需求:
146
147
148
149
150
151
          # 文本字段处理(使用translator的内部逻辑自动处理多语言翻译)
          self._fill_text_fields(doc, spu_row, primary_lang)
          
          # 标题向量化处理(如果启用)
          if self.enable_title_embedding and self.encoder:
              self._fill_title_embedding(doc)
0064e946   tangwang   feat: 增量索引服务、租户配置...
152
  
d350861f   tangwang   索引结构修改
153
          # Tags:统一转成与 mapping 一致的 core-language object
e50924ed   tangwang   1. tags -> enrich...
154
155
          if pd.notna(spu_row.get('enriched_tags')):
              tags_str = str(spu_row['enriched_tags'])
d350861f   tangwang   索引结构修改
156
157
158
159
160
161
              tags_obj = self._build_core_language_text_object(
                  tags_str,
                  source_lang=primary_lang,
                  scene="general",
              )
              if tags_obj:
e50924ed   tangwang   1. tags -> enrich...
162
                  doc['enriched_tags'] = tags_obj
0064e946   tangwang   feat: 增量索引服务、租户配置...
163
164
165
166
167
168
169
170
171
172
  
          # Category相关字段
          self._fill_category_fields(doc, spu_row)
  
          # Option名称(从option表获取)
          self._fill_option_names(doc, options)
  
          # Image URL
          self._fill_image_url(doc, spu_row)
  
e7a2c0b7   tangwang   img encode
173
174
175
176
          # Image embedding(与 mappings/search_products.json 中 image_embedding 嵌套结构一致)
          if self.enable_image_embedding:
              self._fill_image_embedding(doc, spu_row, skus)
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
          # Sales (fake_sales)
          if pd.notna(spu_row.get('fake_sales')):
              try:
                  doc['sales'] = int(spu_row['fake_sales'])
              except (ValueError, TypeError):
                  doc['sales'] = 0
          else:
              doc['sales'] = 0
  
          # Process SKUs and build specifications
          skus_list, prices, compare_prices, sku_prices, sku_weights, sku_weight_units, total_inventory, specifications = \
              self._process_skus(skus, options)
  
          doc['skus'] = skus_list
          doc['specifications'] = specifications
  
          # 提取option值(根据配置的searchable_option_dimensions)
          self._fill_option_values(doc, skus)
  
          # 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
  
89638140   tangwang   重构 indexer 文档构建接口...
204
205
          # SPU 不再读取 compare_at_price 字段;ES 的 compare_at_price 使用所有 SKU 中的最大对比价
          if compare_prices:
0064e946   tangwang   feat: 增量索引服务、租户配置...
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
              doc['compare_at_price'] = float(max(compare_prices))
          else:
              doc['compare_at_price'] = None
  
          # SKU扁平化字段
          doc['sku_prices'] = sku_prices
          doc['sku_weights'] = sku_weights
          doc['sku_weight_units'] = list(set(sku_weight_units))  # 去重
          doc['total_inventory'] = total_inventory
  
          # 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)
  
d54b0467   tangwang   feat: 为商品索引补充 qan...
231
          # 基于 LLM 的锚文本与语义属性(默认开启,失败时仅记录日志)
be3f0d46   tangwang   /indexer/enrich-c...
232
233
234
235
          # 注意:批处理场景(build-docs / bulk / incremental)应优先在外层攒批,
          # 再调用 fill_llm_attributes_batch(),避免逐条调用 LLM。
          if fill_llm_attributes:
              self._fill_llm_attributes(doc, spu_row)
d54b0467   tangwang   feat: 为商品索引补充 qan...
236
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
237
238
          return doc
  
be3f0d46   tangwang   /indexer/enrich-c...
239
240
241
242
      def fill_llm_attributes_batch(self, docs: List[Dict[str, Any]], spu_rows: List[pd.Series]) -> None:
          """
          批量调用 LLM,为一批 doc 填充:
          - qanchors.{lang}
e50924ed   tangwang   1. tags -> enrich...
243
          - enriched_tags.{lang}
d350861f   tangwang   索引结构修改
244
          - enriched_attributes[].value.{lang}
36516857   tangwang   feat(product_enri...
245
          - enriched_taxonomy_attributes[].value.{lang}
be3f0d46   tangwang   /indexer/enrich-c...
246
247
248
249
250
251
252
253
  
          设计目标:
          - 尽可能攒批调用 LLM
          - 单次 LLM 调用最多 20 条(由 analyze_products 内部强制 cap 并自动拆批)。
          """
          if not docs or not spu_rows or len(docs) != len(spu_rows):
              return
  
be3f0d46   tangwang   /indexer/enrich-c...
254
          id_to_idx: Dict[str, int] = {}
d350861f   tangwang   索引结构修改
255
          items: List[Dict[str, str]] = []
be3f0d46   tangwang   /indexer/enrich-c...
256
257
258
259
260
261
          for i, row in enumerate(spu_rows):
              raw_id = row.get("id")
              spu_id = "" if raw_id is None else str(raw_id).strip()
              title = str(row.get("title") or "").strip()
              if not spu_id or not title:
                  continue
be3f0d46   tangwang   /indexer/enrich-c...
262
              id_to_idx[spu_id] = i
d350861f   tangwang   索引结构修改
263
264
265
266
267
268
269
              items.append(
                  {
                      "id": spu_id,
                      "title": title,
                      "brief": str(row.get("brief") or "").strip(),
                      "description": str(row.get("description") or "").strip(),
                      "image_url": str(row.get("image_src") or "").strip(),
d350861f   tangwang   索引结构修改
270
271
272
                  }
              )
          if not items:
be3f0d46   tangwang   /indexer/enrich-c...
273
274
275
              return
  
          tenant_id = str(docs[0].get("tenant_id") or "").strip() or None
d350861f   tangwang   索引结构修改
276
          try:
048631be   tangwang   1. 新增说明文档《product...
277
278
279
280
281
282
              # TODO: 从数据库读取该 tenant 的真实行业,并据此替换当前默认的 apparel profile。
              results = build_index_content_fields(
                  items=items,
                  tenant_id=tenant_id,
                  category_taxonomy_profile="apparel",
              )
d350861f   tangwang   索引结构修改
283
284
285
          except Exception as e:
              logger.warning("LLM batch attribute fill failed: %s", e)
              return
be3f0d46   tangwang   /indexer/enrich-c...
286
  
d350861f   tangwang   索引结构修改
287
288
289
          for result in results:
              spu_id = str(result.get("id") or "").strip()
              if not spu_id:
be3f0d46   tangwang   /indexer/enrich-c...
290
                  continue
d350861f   tangwang   索引结构修改
291
292
293
294
              idx = id_to_idx.get(spu_id)
              if idx is None:
                  continue
              self._apply_content_enrichment(docs[idx], result)
be3f0d46   tangwang   /indexer/enrich-c...
295
  
d350861f   tangwang   索引结构修改
296
297
      def _apply_content_enrichment(self, doc: Dict[str, Any], enrichment: Dict[str, Any]) -> None:
          """将 product_enrich 产出的 ES-ready 内容字段写入 doc。"""
be3f0d46   tangwang   /indexer/enrich-c...
298
          try:
d350861f   tangwang   索引结构修改
299
300
              if enrichment.get("qanchors"):
                  doc["qanchors"] = enrichment["qanchors"]
e50924ed   tangwang   1. tags -> enrich...
301
302
              if enrichment.get("enriched_tags"):
                  doc["enriched_tags"] = enrichment["enriched_tags"]
d350861f   tangwang   索引结构修改
303
304
              if enrichment.get("enriched_attributes"):
                  doc["enriched_attributes"] = enrichment["enriched_attributes"]
36516857   tangwang   feat(product_enri...
305
306
              if enrichment.get("enriched_taxonomy_attributes"):
                  doc["enriched_taxonomy_attributes"] = enrichment["enriched_taxonomy_attributes"]
be3f0d46   tangwang   /indexer/enrich-c...
307
          except Exception as e:
d350861f   tangwang   索引结构修改
308
              logger.warning("Failed to apply enrichment to doc (spu_id=%s): %s", doc.get("spu_id"), e)
be3f0d46   tangwang   /indexer/enrich-c...
309
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
310
311
312
313
      def _fill_text_fields(
          self,
          doc: Dict[str, Any],
          spu_row: pd.Series,
453992a8   tangwang   需求:
314
          primary_lang: str
0064e946   tangwang   feat: 增量索引服务、租户配置...
315
      ):
453992a8   tangwang   需求:
316
          """
038e4e2f   tangwang   refactor(i18n): t...
317
318
          填充文本字段(根据租户 index_languages 处理多语言翻译)。
          仅写入 primary_language  index_languages 中配置的语言。
453992a8   tangwang   需求:
319
          """
038e4e2f   tangwang   refactor(i18n): t...
320
321
322
323
          index_langs = self.tenant_config.get("index_languages") or ["en", "zh"]
  
          def _set_lang_obj(field_name: str, source_text: Optional[str], translations: Optional[Dict[str, Optional[str]]] = None):
              """写入多语言对象 doc[field_name] = {"zh": "...", "en": "...", ...},仅包含 index_languages。"""
d7d48f52   tangwang   改动(mapping + 灌入结构)
324
325
              if not source_text or not str(source_text).strip():
                  return
d7d48f52   tangwang   改动(mapping + 灌入结构)
326
327
328
              obj: Dict[str, str] = {}
              src = str(source_text)
              obj[primary_lang] = src
d7d48f52   tangwang   改动(mapping + 灌入结构)
329
              tr = translations or {}
038e4e2f   tangwang   refactor(i18n): t...
330
331
332
333
334
335
              for lang in index_langs:
                  if lang == primary_lang:
                      continue
                  val = tr.get(lang)
                  if val and str(val).strip():
                      obj[lang] = str(val)
d7d48f52   tangwang   改动(mapping + 灌入结构)
336
337
338
              if obj:
                  doc[field_name] = obj
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
339
340
341
          # Title
          if pd.notna(spu_row.get('title')):
              title_text = str(spu_row['title'])
038e4e2f   tangwang   refactor(i18n): t...
342
              translations: Dict[str, Optional[str]] = {}
453992a8   tangwang   需求:
343
              if self.translator:
d4cadc13   tangwang   翻译重构
344
345
                  translations = self._translate_index_languages(
                      text=title_text,
453992a8   tangwang   需求:
346
                      source_lang=primary_lang,
038e4e2f   tangwang   refactor(i18n): t...
347
                      index_languages=index_langs,
af827ce9   tangwang   rerank
348
                      scene="sku_name",
d4cadc13   tangwang   翻译重构
349
                  )
d7d48f52   tangwang   改动(mapping + 灌入结构)
350
              _set_lang_obj("title", title_text, translations)
0064e946   tangwang   feat: 增量索引服务、租户配置...
351
352
353
354
  
          # Brief
          if pd.notna(spu_row.get('brief')):
              brief_text = str(spu_row['brief'])
038e4e2f   tangwang   refactor(i18n): t...
355
              translations = {}
453992a8   tangwang   需求:
356
              if self.translator:
d4cadc13   tangwang   翻译重构
357
358
                  translations = self._translate_index_languages(
                      text=brief_text,
453992a8   tangwang   需求:
359
                      source_lang=primary_lang,
038e4e2f   tangwang   refactor(i18n): t...
360
                      index_languages=index_langs,
0fd2f875   tangwang   translate
361
                      scene="general",
d4cadc13   tangwang   翻译重构
362
                  )
d7d48f52   tangwang   改动(mapping + 灌入结构)
363
              _set_lang_obj("brief", brief_text, translations)
0064e946   tangwang   feat: 增量索引服务、租户配置...
364
365
366
367
  
          # Description
          if pd.notna(spu_row.get('description')):
              desc_text = str(spu_row['description'])
038e4e2f   tangwang   refactor(i18n): t...
368
              translations = {}
453992a8   tangwang   需求:
369
              if self.translator:
d4cadc13   tangwang   翻译重构
370
371
                  translations = self._translate_index_languages(
                      text=desc_text,
453992a8   tangwang   需求:
372
                      source_lang=primary_lang,
038e4e2f   tangwang   refactor(i18n): t...
373
                      index_languages=index_langs,
0fd2f875   tangwang   translate
374
                      scene="general",
d4cadc13   tangwang   翻译重构
375
                  )
d7d48f52   tangwang   改动(mapping + 灌入结构)
376
              _set_lang_obj("description", desc_text, translations)
0064e946   tangwang   feat: 增量索引服务、租户配置...
377
378
379
380
  
          # Vendor
          if pd.notna(spu_row.get('vendor')):
              vendor_text = str(spu_row['vendor'])
038e4e2f   tangwang   refactor(i18n): t...
381
              translations = {}
453992a8   tangwang   需求:
382
              if self.translator:
d4cadc13   tangwang   翻译重构
383
384
                  translations = self._translate_index_languages(
                      text=vendor_text,
453992a8   tangwang   需求:
385
                      source_lang=primary_lang,
038e4e2f   tangwang   refactor(i18n): t...
386
                      index_languages=index_langs,
0fd2f875   tangwang   translate
387
                      scene="general",
d4cadc13   tangwang   翻译重构
388
                  )
d7d48f52   tangwang   改动(mapping + 灌入结构)
389
              _set_lang_obj("vendor", vendor_text, translations)
0064e946   tangwang   feat: 增量索引服务、租户配置...
390
391
392
  
      def _fill_category_fields(self, doc: Dict[str, Any], spu_row: pd.Series):
          """填充类目相关字段。"""
92d5eb07   tangwang   fix:前端直接显示了类目ID。 ...
393
394
395
396
          # 数据质量兜底:
          # - 当商品的类目ID在映射中不存在时,视为“不合法类目”,整条类目相关字段都不写入(当成没有类目)
          # - 仅记录错误日志,不阻塞索引流程
  
2739b281   tangwang   多语言索引调整
397
          primary_lang = self.tenant_config.get('primary_language', 'en')
d7d48f52   tangwang   改动(mapping + 灌入结构)
398
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
399
400
401
402
403
          if pd.notna(spu_row.get('category_path')):
              category_path = str(spu_row['category_path'])
              
              # 解析category_path - 这是逗号分隔的类目ID列表
              category_ids = [cid.strip() for cid in category_path.split(',') if cid.strip()]
92d5eb07   tangwang   fix:前端直接显示了类目ID。 ...
404
              # 将ID映射为名称,如果找不到映射则记录错误并跳过
0064e946   tangwang   feat: 增量索引服务、租户配置...
405
              category_names = []
92d5eb07   tangwang   fix:前端直接显示了类目ID。 ...
406
              missing_ids = []
0064e946   tangwang   feat: 增量索引服务、租户配置...
407
408
409
410
              for cid in category_ids:
                  if cid in self.category_id_to_name:
                      category_names.append(self.category_id_to_name[cid])
                  else:
92d5eb07   tangwang   fix:前端直接显示了类目ID。 ...
411
412
413
414
415
416
417
418
419
420
                      missing_ids.append(cid)
              
              # 如果有缺失的类目ID,记录错误日志,不写入类目字段(当成没有类目)
              if missing_ids:
                  logger.error(
                      f"Category ID(s) not found in mapping for SPU {spu_row.get('id')} "
                      f"(title: {spu_row.get('title', 'N/A')}), missing_ids={missing_ids}, "
                      f"category_path={category_path}. Treating as no-category."
                  )
                  return
0064e946   tangwang   feat: 增量索引服务、租户配置...
421
422
423
424
              
              # 构建类目路径字符串(用于搜索)
              if category_names:
                  category_path_str = '/'.join(category_names)
d7d48f52   tangwang   改动(mapping + 灌入结构)
425
                  doc['category_path'] = {primary_lang: category_path_str}
2e48a32d   tangwang   doc
426
427
                  # 与查询使用的 category_name_text.zh/en 对齐,便于类目搜索
                  doc['category_name_text'] = {primary_lang: category_path_str}
0064e946   tangwang   feat: 增量索引服务、租户配置...
428
429
430
431
432
433
434
435
436
437
438
                  
                  # 填充分层类目名称
                  if len(category_names) > 0:
                      doc['category1_name'] = category_names[0]
                  if len(category_names) > 1:
                      doc['category2_name'] = category_names[1]
                  if len(category_names) > 2:
                      doc['category3_name'] = category_names[2]
          elif pd.notna(spu_row.get('category')):
              # 如果category_path为空,使用category字段作为category1_name的备选
              category = str(spu_row['category'])
d7d48f52   tangwang   改动(mapping + 灌入结构)
439
              doc['category_name_text'] = {primary_lang: category}
0064e946   tangwang   feat: 增量索引服务、租户配置...
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
              doc['category_name'] = category
              
              # 尝试从category字段解析多级分类
              if '/' in category:
                  path_parts = category.split('/')
                  if len(path_parts) > 0:
                      doc['category1_name'] = path_parts[0].strip()
                  if len(path_parts) > 1:
                      doc['category2_name'] = path_parts[1].strip()
                  if len(path_parts) > 2:
                      doc['category3_name'] = path_parts[2].strip()
              else:
                  # 如果category不包含"/",直接作为category1_name
                  doc['category1_name'] = category.strip()
  
          if pd.notna(spu_row.get('category')):
              # 确保category相关字段都被设置(如果前面没有设置)
              category_name = str(spu_row['category'])
d7d48f52   tangwang   改动(mapping + 灌入结构)
458
459
              if 'category_name_text' not in doc:
                  doc['category_name_text'] = {primary_lang: category_name}
0064e946   tangwang   feat: 增量索引服务、租户配置...
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
              if 'category_name' not in doc:
                  doc['category_name'] = category_name
  
          if pd.notna(spu_row.get('category_id')):
              doc['category_id'] = str(int(spu_row['category_id']))
  
          if pd.notna(spu_row.get('category_level')):
              doc['category_level'] = int(spu_row['category_level'])
  
      def _fill_option_names(self, doc: Dict[str, Any], options: pd.DataFrame):
          """填充Option名称字段。"""
          if not options.empty:
              # 按position排序获取option名称
              sorted_options = options.sort_values('position')
              if len(sorted_options) > 0 and pd.notna(sorted_options.iloc[0].get('name')):
                  doc['option1_name'] = str(sorted_options.iloc[0]['name'])
              if len(sorted_options) > 1 and pd.notna(sorted_options.iloc[1].get('name')):
                  doc['option2_name'] = str(sorted_options.iloc[1]['name'])
              if len(sorted_options) > 2 and pd.notna(sorted_options.iloc[2].get('name')):
                  doc['option3_name'] = str(sorted_options.iloc[2]['name'])
  
      def _fill_image_url(self, doc: Dict[str, Any], spu_row: pd.Series):
          """填充图片URL字段。"""
          if pd.notna(spu_row.get('image_src')):
              image_src = str(spu_row['image_src'])
              if not image_src.startswith('http'):
cd6d887e   tangwang   reranker doc
486
487
                  # 仅当尚未是协议相对 URL 时才补 "//",避免 "//host" 变成 "////host"
                  image_src = f"//{image_src}" if not image_src.startswith('//') else image_src
0064e946   tangwang   feat: 增量索引服务、租户配置...
488
489
              doc['image_url'] = image_src
  
e7a2c0b7   tangwang   img encode
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
      def _fill_image_embedding(
          self, doc: Dict[str, Any], spu_row: pd.Series, skus: pd.DataFrame
      ) -> None:
          """
          填充 image_embedding 嵌套字段,与 mappings/search_products.json 一致:
          [{ "vector": [float, ...], "url": "..." }, ...]
          收集 SPU 主图 + SKU 图片 URL,去重后调用 image_encoder 生成向量。
          """
          urls: List[str] = []
          seen: set = set()
  
          def _add(url: str) -> None:
              if not url or not str(url).strip():
                  return
              u = str(url).strip()
              if u.startswith("//"):
                  u = "https:" + u
              if u not in seen:
                  seen.add(u)
                  urls.append(u)
  
          if doc.get("image_url"):
              _add(doc["image_url"])
          if pd.notna(spu_row.get("image_src")):
              _add(str(spu_row["image_src"]))
          if not skus.empty and "image_src" in skus.columns:
              for _, row in skus.iterrows():
                  if pd.notna(row.get("image_src")):
                      _add(str(row["image_src"]))
  
          if not urls:
              return
ed948666   tangwang   tidy
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
          vectors = self.image_encoder.encode_image_urls(urls, batch_size=8)
          if not vectors or len(vectors) != len(urls):
              raise RuntimeError(
                  f"image_embedding response length mismatch for SPU {doc.get('spu_id')}: "
                  f"expected {len(urls)}, got {0 if vectors is None else len(vectors)}"
              )
          out = []
          for url, vec in zip(urls, vectors):
              arr = np.asarray(vec, dtype=np.float32)
              if arr.ndim != 1 or arr.size == 0 or not np.isfinite(arr).all():
                  raise RuntimeError(
                      f"Invalid image embedding for SPU {doc.get('spu_id')} and URL {url}"
                  )
              out.append({"vector": arr.tolist(), "url": url})
          doc["image_embedding"] = out
e7a2c0b7   tangwang   img encode
537
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
      def _process_skus(
          self,
          skus: pd.DataFrame,
          options: pd.DataFrame
      ) -> tuple:
          """处理SKU数据,返回处理结果。"""
          skus_list = []
          prices = []
          compare_prices = []
          sku_prices = []
          sku_weights = []
          sku_weight_units = []
          total_inventory = 0
          specifications = []
  
          # 构建option名称映射(position -> name)
          option_name_map = {}
          if not options.empty:
              for _, opt_row in options.iterrows():
                  position = opt_row.get('position')
                  name = opt_row.get('name')
                  if pd.notna(position) and pd.notna(name):
                      option_name_map[int(position)] = str(name)
  
d350861f   tangwang   索引结构修改
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
          primary_lang = self.tenant_config.get('primary_language', 'en')
  
          def _build_specification(name: str, raw_value: Any, sku_id: str) -> Optional[Dict[str, Any]]:
              value = "" if raw_value is None else str(raw_value).strip()
              if not value:
                  return None
              return {
                  'sku_id': sku_id,
                  'name': name,
                  'value_keyword': value,
                  'value_text': self._build_core_language_text_object(
                      value,
                      source_lang=primary_lang,
                      scene="general",
                  ) or normalize_core_text_field_value(value, primary_lang),
              }
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
          for _, sku_row in skus.iterrows():
              sku_data = self._transform_sku_row(sku_row, option_name_map)
              if sku_data:
                  skus_list.append(sku_data)
                  
                  # 收集价格信息
                  if 'price' in sku_data and sku_data['price'] is not None:
                      try:
                          price_val = float(sku_data['price'])
                          prices.append(price_val)
                          sku_prices.append(price_val)
                      except (ValueError, TypeError):
                          pass
                  
                  if 'compare_at_price' in sku_data and sku_data['compare_at_price'] is not None:
                      try:
                          compare_prices.append(float(sku_data['compare_at_price']))
                      except (ValueError, TypeError):
                          pass
                  
                  # 收集重量信息
                  if 'weight' in sku_data and sku_data['weight'] is not None:
                      try:
                          sku_weights.append(int(float(sku_data['weight'])))
                      except (ValueError, TypeError):
                          pass
                  
                  if 'weight_unit' in sku_data and sku_data['weight_unit']:
                      sku_weight_units.append(str(sku_data['weight_unit']))
                  
                  # 收集库存信息
                  if 'stock' in sku_data and sku_data['stock'] is not None:
                      try:
                          total_inventory += int(sku_data['stock'])
                      except (ValueError, TypeError):
                          pass
                  
                  # 构建specifications(从SKU的option值和option表的name)
                  sku_id = str(sku_row['id'])
                  if pd.notna(sku_row.get('option1')) and 1 in option_name_map:
d350861f   tangwang   索引结构修改
619
620
621
                      spec = _build_specification(option_name_map[1], sku_row['option1'], sku_id)
                      if spec:
                          specifications.append(spec)
0064e946   tangwang   feat: 增量索引服务、租户配置...
622
                  if pd.notna(sku_row.get('option2')) and 2 in option_name_map:
d350861f   tangwang   索引结构修改
623
624
625
                      spec = _build_specification(option_name_map[2], sku_row['option2'], sku_id)
                      if spec:
                          specifications.append(spec)
0064e946   tangwang   feat: 增量索引服务、租户配置...
626
                  if pd.notna(sku_row.get('option3')) and 3 in option_name_map:
d350861f   tangwang   索引结构修改
627
628
629
                      spec = _build_specification(option_name_map[3], sku_row['option3'], sku_id)
                      if spec:
                          specifications.append(spec)
0064e946   tangwang   feat: 增量索引服务、租户配置...
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
  
          return skus_list, prices, compare_prices, sku_prices, sku_weights, sku_weight_units, total_inventory, specifications
  
      def _fill_option_values(self, doc: Dict[str, Any], skus: pd.DataFrame):
          """填充option值字段。"""
          option1_values = []
          option2_values = []
          option3_values = []
          
          for _, sku_row in skus.iterrows():
              if pd.notna(sku_row.get('option1')):
                  option1_values.append(str(sku_row['option1']))
              if pd.notna(sku_row.get('option2')):
                  option2_values.append(str(sku_row['option2']))
              if pd.notna(sku_row.get('option3')):
                  option3_values.append(str(sku_row['option3']))
          
          # 去重并根据配置决定是否写入索引
          if 'option1' in self.searchable_option_dimensions:
              doc['option1_values'] = list(set(option1_values)) if option1_values else []
          else:
              doc['option1_values'] = []
          
          if 'option2' in self.searchable_option_dimensions:
              doc['option2_values'] = list(set(option2_values)) if option2_values else []
          else:
              doc['option2_values'] = []
          
          if 'option3' in self.searchable_option_dimensions:
              doc['option3_values'] = list(set(option3_values)) if option3_values else []
          else:
              doc['option3_values'] = []
  
d54b0467   tangwang   feat: 为商品索引补充 qan...
663
664
      def _fill_llm_attributes(self, doc: Dict[str, Any], spu_row: pd.Series) -> None:
          """
d350861f   tangwang   索引结构修改
665
          调用 indexer.product_enrich 的高层内容理解入口,为当前 SPU 填充:
d54b0467   tangwang   feat: 为商品索引补充 qan...
666
          - qanchors.{lang}
e50924ed   tangwang   1. tags -> enrich...
667
          - enriched_tags.{lang}
d350861f   tangwang   索引结构修改
668
          - enriched_attributes[].value.{lang}
d54b0467   tangwang   feat: 为商品索引补充 qan...
669
          """
d54b0467   tangwang   feat: 为商品索引补充 qan...
670
671
672
673
674
          spu_id = str(spu_row.get("id") or "").strip()
          title = str(spu_row.get("title") or "").strip()
          if not spu_id or not title:
              return
  
501066e1   tangwang   redis 缓存 LLM结果
675
          tenant_id = doc.get("tenant_id")
d350861f   tangwang   索引结构修改
676
          try:
048631be   tangwang   1. 新增说明文档《product...
677
              # TODO: 从数据库读取该 tenant 的真实行业,并据此替换当前默认的 apparel profile。
d350861f   tangwang   索引结构修改
678
679
680
681
682
683
684
685
              results = build_index_content_fields(
                  items=[
                      {
                          "id": spu_id,
                          "title": title,
                          "brief": str(spu_row.get("brief") or "").strip(),
                          "description": str(spu_row.get("description") or "").strip(),
                          "image_url": str(spu_row.get("image_src") or "").strip(),
d350861f   tangwang   索引结构修改
686
687
688
                      }
                  ],
                  tenant_id=str(tenant_id),
048631be   tangwang   1. 新增说明文档《product...
689
                  category_taxonomy_profile="apparel",
d350861f   tangwang   索引结构修改
690
691
692
693
              )
          except Exception as e:
              logger.warning("LLM attribute fill failed for SPU %s: %s", spu_id, e)
              return
501066e1   tangwang   redis 缓存 LLM结果
694
  
d350861f   tangwang   索引结构修改
695
696
          if results:
              self._apply_content_enrichment(doc, results[0])
d54b0467   tangwang   feat: 为商品索引补充 qan...
697
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
      def _transform_sku_row(self, sku_row: pd.Series, option_name_map: Dict[int, str] = None) -> Optional[Dict[str, Any]]:
          """
          SKU行转换为SKU对象。
  
          Args:
              sku_row: SKU行数据
              option_name_map: positionoption名称的映射
  
          Returns:
              SKU字典
          """
          sku_data = {}
  
          # SKU ID
          sku_data['sku_id'] = str(sku_row['id'])
  
          # Price
          if pd.notna(sku_row.get('price')):
              try:
                  sku_data['price'] = float(sku_row['price'])
              except (ValueError, TypeError):
                  sku_data['price'] = None
          else:
              sku_data['price'] = None
  
          # Compare at price
          if pd.notna(sku_row.get('compare_at_price')):
              try:
                  sku_data['compare_at_price'] = float(sku_row['compare_at_price'])
              except (ValueError, TypeError):
                  sku_data['compare_at_price'] = None
          else:
              sku_data['compare_at_price'] = None
  
          # SKU Code
          if pd.notna(sku_row.get('sku')):
              sku_data['sku_code'] = str(sku_row['sku'])
  
          # Stock
          if pd.notna(sku_row.get('inventory_quantity')):
              try:
                  sku_data['stock'] = int(sku_row['inventory_quantity'])
              except (ValueError, TypeError):
                  sku_data['stock'] = 0
          else:
              sku_data['stock'] = 0
  
          # Weight
          if pd.notna(sku_row.get('weight')):
              try:
                  sku_data['weight'] = float(sku_row['weight'])
              except (ValueError, TypeError):
                  sku_data['weight'] = None
          else:
              sku_data['weight'] = None
  
          # Weight unit
          if pd.notna(sku_row.get('weight_unit')):
              sku_data['weight_unit'] = str(sku_row['weight_unit'])
  
          # Option values
          if pd.notna(sku_row.get('option1')):
              sku_data['option1_value'] = str(sku_row['option1'])
          if pd.notna(sku_row.get('option2')):
              sku_data['option2_value'] = str(sku_row['option2'])
          if pd.notna(sku_row.get('option3')):
              sku_data['option3_value'] = str(sku_row['option3'])
          
          # Image src
          if pd.notna(sku_row.get('image_src')):
              sku_data['image_src'] = str(sku_row['image_src'])
  
          return sku_data
453992a8   tangwang   需求:
771
772
773
774
775
      
      def _fill_title_embedding(self, doc: Dict[str, Any]) -> None:
          """
          填充标题向量化字段。
          
d7d48f52   tangwang   改动(mapping + 灌入结构)
776
          使用英文标题(title.en)生成embedding。如果title.en不存在,则使用title.zh
453992a8   tangwang   需求:
777
778
779
780
          
          Args:
              doc: ES文档字典
          """
d7d48f52   tangwang   改动(mapping + 灌入结构)
781
782
783
784
785
786
787
788
789
790
791
          # 优先使用英文标题,如果没有则使用中文标题;再没有则取任意可用语言
          title_obj = doc.get("title") or {}
          if isinstance(title_obj, dict):
              title_text = title_obj.get("en") or title_obj.get("zh")
              if not title_text:
                  for v in title_obj.values():
                      if v and str(v).strip():
                          title_text = str(v)
                          break
          else:
              title_text = None
453992a8   tangwang   需求:
792
793
794
795
796
          
          if not title_text or not title_text.strip():
              logger.debug(f"No title text available for embedding, SPU: {doc.get('spu_id')}")
              return
          
ed948666   tangwang   tidy
797
798
799
800
801
802
803
804
805
806
807
          # 使用文本向量编码器生成 embedding
          # encode方法返回numpy数组,形状为(n, d)
          embeddings = self.encoder.encode(title_text)
          if embeddings is None or len(embeddings) == 0:
              raise RuntimeError(f"Failed to generate title embedding for SPU {doc.get('spu_id')}")
  
          embedding = np.asarray(embeddings[0], dtype=np.float32)
          if embedding.ndim != 1 or embedding.size == 0 or not np.isfinite(embedding).all():
              raise RuntimeError(f"Invalid title embedding for SPU {doc.get('spu_id')}")
          doc['title_embedding'] = embedding.tolist()
          logger.debug(f"Generated title_embedding for SPU: {doc.get('spu_id')}, title: {title_text[:50]}...")