Blame view

api/routes/indexer.py 26.1 KB
0064e946   tangwang   feat: 增量索引服务、租户配置...
1
  """
3c1f8031   tangwang   api/routes/indexe...
2
  索引API路由。
0064e946   tangwang   feat: 增量索引服务、租户配置...
3
  
3c1f8031   tangwang   api/routes/indexe...
4
  提供全量和增量索引接口,供外部Java程序调用。
0064e946   tangwang   feat: 增量索引服务、租户配置...
5
6
  """
  
791a7909   tangwang   支持并发的增量和全量请求:
7
  import asyncio
9f5994b4   tangwang   reranker
8
  import re
3c1f8031   tangwang   api/routes/indexe...
9
  from fastapi import APIRouter, HTTPException
5aaf0c7d   tangwang   feat(indexer): 完善...
10
  from typing import Any, Dict, List, Literal, Optional
89638140   tangwang   重构 indexer 文档构建接口...
11
  from pydantic import BaseModel, Field
0064e946   tangwang   feat: 增量索引服务、租户配置...
12
  import logging
bb9c626c   tangwang   搜索服务(6002)不再初始化/挂...
13
14
15
16
  from sqlalchemy import text
  
  # Indexer routes depend on services provided by api/indexer_app.py via this registry.
  from ..service_registry import get_incremental_service, get_bulk_indexing_service, get_es_client
0064e946   tangwang   feat: 增量索引服务、租户配置...
17
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
18
19
20
21
  logger = logging.getLogger(__name__)
  
  router = APIRouter(prefix="/indexer", tags=["indexer"])
  
dabd52a5   tangwang   feat(indexer): 支持...
22
23
24
25
26
  SUPPORTED_CATEGORY_TAXONOMY_PROFILES = (
      "apparel, 3c, bags, pet_supplies, electronics, outdoor, "
      "home_appliances, home_living, wigs, beauty, accessories, toys, shoes, sports, others"
  )
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
27
  
c55c5e47   tangwang   feat: 新增增量索引接口并重构...
28
29
  class ReindexRequest(BaseModel):
      """全量重建索引请求"""
3c1f8031   tangwang   api/routes/indexe...
30
      tenant_id: str
3c1f8031   tangwang   api/routes/indexe...
31
32
      batch_size: int = 500
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
33
  
c55c5e47   tangwang   feat: 新增增量索引接口并重构...
34
35
  class IndexSpusRequest(BaseModel):
      """增量索引请求(按SPU列表索引)"""
3c1f8031   tangwang   api/routes/indexe...
36
37
      tenant_id: str
      spu_ids: List[str]
be3f0d46   tangwang   /indexer/enrich-c...
38
      delete_spu_ids: List[str] = Field(default_factory=list)  # 显式指定要删除的SPU ID列表(可选)
0064e946   tangwang   feat: 增量索引服务、租户配置...
39
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
40
  
c55c5e47   tangwang   feat: 新增增量索引接口并重构...
41
42
43
44
45
46
  class GetDocumentsRequest(BaseModel):
      """查询文档请求(不写入ES)"""
      tenant_id: str
      spu_ids: List[str]
  
  
89638140   tangwang   重构 indexer 文档构建接口...
47
48
49
50
51
52
53
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
  class BuildDocItem(BaseModel):
      """
      单个 SPU 的原始数据包(由上游从 MySQL 查询得到)。
  
      - spu: 一行 SPU 记录,对应 shoplazza_product_spu 
      - skus:  SPU 下的所有 SKU 记录,对应 shoplazza_product_sku 
      - options:  SPU 的所有 Option 记录,对应 shoplazza_product_option 
      """
      spu: Dict[str, Any] = Field(..., description="单个 SPU 的原始字段(MySQL 行数据)")
      skus: List[Dict[str, Any]] = Field(default_factory=list, description="该 SPU 关联的 SKU 列表")
      options: List[Dict[str, Any]] = Field(default_factory=list, description="该 SPU 关联的 Option 列表")
  
  
  class BuildDocsRequest(BaseModel):
      """
      基于上游已查询出的 MySQL 原始数据,构建 ES 索引文档(不访问数据库、不写入 ES)。
  
      该接口是 Java 等外部索引程序正式使用的“doc 生成接口”:
      - 上游负责:全量 / 增量调度 +  MySQL 查询出各表数据
      - 本模块负责:根据配置和算法,将原始行数据转换为与 mappings/search_products.json 一致的 ES 文档
      """
      tenant_id: str = Field(..., description="租户 ID,用于加载租户配置、语言策略等")
      items: List[BuildDocItem] = Field(..., description="需要构建 doc 的 SPU 列表(含其 SKUs 和 Options)")
  
  
  class BuildDocsFromDbRequest(BaseModel):
      """
      便捷测试请求:只提供 tenant_id  spu_ids,由本服务从 MySQL 查询原始数据,
      然后内部调用 /indexer/build-docs 的同一套逻辑构建 ES doc
  
      用途:
      - 本地/联调时快速验证 doc 结构,无需手工构造庞大的 BuildDocsRequest JSON
      - 生产正式使用建议直接走 BuildDocsRequest,由外层(Java)控制 MySQL 查询
      """
      tenant_id: str = Field(..., description="租户 ID")
      spu_ids: List[str] = Field(..., description="需要构建 doc 的 SPU ID 列表")
  
  
9f5994b4   tangwang   reranker
85
  class EnrichContentItem(BaseModel):
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
86
      """单条待生成内容理解字段的商品。"""
9f5994b4   tangwang   reranker
87
      spu_id: str = Field(..., description="SPU ID")
d350861f   tangwang   索引结构修改
88
      title: str = Field(..., description="商品标题,用于 LLM 分析生成 qanchors / enriched_tags 等")
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
89
90
91
      image_url: Optional[str] = Field(None, description="商品主图 URL(预留给多模态/内容理解扩展)")
      brief: Optional[str] = Field(None, description="商品简介/短描述")
      description: Optional[str] = Field(None, description="商品详情/长描述")
9f5994b4   tangwang   reranker
92
93
94
95
  
  
  class EnrichContentRequest(BaseModel):
      """
2703b6ea   tangwang   refactor(indexer)...
96
      内容理解字段生成请求:根据商品标题批量生成通用增强字段与品类 taxonomy 字段。
9f5994b4   tangwang   reranker
97
98
      供外部 indexer 在自行组织 doc 时调用,与翻译、向量化等微服务并列。
      """
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
99
100
      tenant_id: str = Field(..., description="租户 ID,用于请求路由与结果归属,不参与缓存键")
      items: List[EnrichContentItem] = Field(..., description="待分析的 SPU 列表(spu_id + title,可附带 brief/description/image_url)")
2703b6ea   tangwang   refactor(indexer)...
101
102
      enrichment_scopes: Optional[List[Literal["generic", "category_taxonomy"]]] = Field(
          default=None,
5aaf0c7d   tangwang   feat(indexer): 完善...
103
          description=(
2703b6ea   tangwang   refactor(indexer)...
104
105
106
              "要执行的增强范围。"
              "`generic` 返回 qanchors/enriched_tags/enriched_attributes;"
              "`category_taxonomy` 返回 enriched_taxonomy_attributes。"
5aaf0c7d   tangwang   feat(indexer): 完善...
107
108
109
              "默认两者都执行。"
          ),
      )
2703b6ea   tangwang   refactor(indexer)...
110
111
112
      category_taxonomy_profile: str = Field(
          "apparel",
          description=(
dabd52a5   tangwang   feat(indexer): 支持...
113
114
115
              "品类 taxonomy profile。默认 `apparel`。"
              f"当前支持:{SUPPORTED_CATEGORY_TAXONOMY_PROFILES}。"
              "其中除 `apparel` 外,其余 profile 的 taxonomy 输出仅返回 `en`。"
2703b6ea   tangwang   refactor(indexer)...
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
          ),
      )
      analysis_kinds: Optional[List[Literal["content", "taxonomy"]]] = Field(
          default=None,
          description="Deprecated alias of enrichment_scopes. `content` -> `generic`, `taxonomy` -> `category_taxonomy`.",
      )
  
      def resolved_enrichment_scopes(self) -> List[str]:
          if self.enrichment_scopes:
              return list(self.enrichment_scopes)
          if self.analysis_kinds:
              mapped = []
              for item in self.analysis_kinds:
                  mapped.append("generic" if item == "content" else "category_taxonomy")
              return mapped
          return ["generic", "category_taxonomy"]
9f5994b4   tangwang   reranker
132
133
  
  
c55c5e47   tangwang   feat: 新增增量索引接口并重构...
134
135
136
137
138
  @router.post("/reindex")
  async def reindex_all(request: ReindexRequest):
      """
      全量重建索引接口
      
351a7eb5   tangwang   1. 新的重建索引脚本
139
      将指定租户的所有SPU数据重新索引到ES
80f87e57   tangwang   多语言索引修改 对应的 索引创建、...
140
      注意:此接口不会删除旧索引,只会更新或创建索引。如需重建索引结构(删除后重建),请使用 `scripts/create_tenant_index.sh` 脚本。
791a7909   tangwang   支持并发的增量和全量请求:
141
142
143
      
      注意:全量索引是长时间运行的操作,会在线程池中执行,不会阻塞其他请求。
      全量索引和增量索引可以并行执行。
c55c5e47   tangwang   feat: 新增增量索引接口并重构...
144
      """
3c1f8031   tangwang   api/routes/indexe...
145
      try:
3c1f8031   tangwang   api/routes/indexe...
146
147
148
          service = get_bulk_indexing_service()
          if service is None:
              raise HTTPException(status_code=503, detail="Bulk indexing service is not initialized")
791a7909   tangwang   支持并发的增量和全量请求:
149
150
151
152
153
154
155
156
157
158
159
          
          # 显式将同步阻塞操作放到线程池执行,确保不阻塞事件循环
          # 这样全量索引和增量索引可以并行执行
          loop = asyncio.get_event_loop()
          result = await loop.run_in_executor(
              None,  # 使用默认线程池
              lambda: service.bulk_index(
                  tenant_id=request.tenant_id,
                  recreate_index=False,
                  batch_size=request.batch_size
              )
3c1f8031   tangwang   api/routes/indexe...
160
          )
791a7909   tangwang   支持并发的增量和全量请求:
161
162
          
          return result
3c1f8031   tangwang   api/routes/indexe...
163
164
165
      except HTTPException:
          raise
      except Exception as e:
c55c5e47   tangwang   feat: 新增增量索引接口并重构...
166
167
168
169
170
171
172
173
174
175
          logger.error(f"Error in reindex for tenant_id={request.tenant_id}: {e}", exc_info=True)
          raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
  
  
  @router.post("/index")
  async def index_spus(request: IndexSpusRequest):
      """
      增量索引接口
      
      根据指定的SPU ID列表,将数据索引到ES。用于增量更新指定商品。
f54b3854   tangwang   pu_ids参数。目前总共3个参数:
176
177
178
179
180
181
182
183
184
      
      支持两种删除方式:
      1. **自动检测删除**:如果SPU在数据库中被标记为deleted=1,自动从ES中删除对应文档
      2. **显式删除**:通过delete_spu_ids参数显式指定要删除的SPU(无论数据库状态如何)
      
      删除策略说明:
      - 数据库是唯一真实来源(Single Source of Truth
      - 自动检测:查询数据库时发现deleted=1,自动从ES删除
      - 显式删除:调用方明确知道哪些SPU要删除,直接删除(适用于批量删除场景)
c797ba2b   tangwang   1. 增量索引接口,增加删除操作后...
185
186
187
188
189
190
      
      响应格式:
      - spu_ids: spu_ids对应的响应列表,每个元素包含spu_idstatusindexed/deleted/failed
      - delete_spu_ids: delete_spu_ids对应的响应列表,每个元素包含spu_idstatusdeleted/not_found/failed
      - failed状态的元素会包含msg字段说明失败原因
      - 最后给出总体统计:total, success_count, failed_count
791a7909   tangwang   支持并发的增量和全量请求:
191
192
      
      注意:增量索引在线程池中执行,可以与全量索引并行执行。
c55c5e47   tangwang   feat: 新增增量索引接口并重构...
193
194
      """
      try:
f54b3854   tangwang   pu_ids参数。目前总共3个参数:
195
196
197
198
199
200
201
202
203
          # 验证请求参数
          if not request.spu_ids and not request.delete_spu_ids:
              raise HTTPException(status_code=400, detail="spu_ids and delete_spu_ids cannot both be empty")
          
          if request.spu_ids and len(request.spu_ids) > 100:
              raise HTTPException(status_code=400, detail="Maximum 100 SPU IDs allowed per request for indexing")
          
          if request.delete_spu_ids and len(request.delete_spu_ids) > 100:
              raise HTTPException(status_code=400, detail="Maximum 100 SPU IDs allowed per request for deletion")
c55c5e47   tangwang   feat: 新增增量索引接口并重构...
204
205
206
207
208
209
210
211
212
          
          service = get_incremental_service()
          if service is None:
              raise HTTPException(status_code=503, detail="Incremental indexer service is not initialized")
          
          es_client = get_es_client()
          if es_client is None:
              raise HTTPException(status_code=503, detail="Elasticsearch client is not initialized")
          
791a7909   tangwang   支持并发的增量和全量请求:
213
214
215
216
217
218
219
220
221
222
223
          # 显式将同步阻塞操作放到线程池执行,确保不阻塞事件循环
          # 这样全量索引和增量索引可以并行执行
          loop = asyncio.get_event_loop()
          result = await loop.run_in_executor(
              None,  # 使用默认线程池
              lambda: service.index_spus_to_es(
                  es_client=es_client,
                  tenant_id=request.tenant_id,
                  spu_ids=request.spu_ids if request.spu_ids else [],
                  delete_spu_ids=request.delete_spu_ids if request.delete_spu_ids else None
              )
c55c5e47   tangwang   feat: 新增增量索引接口并重构...
224
225
226
227
228
229
230
231
          )
          
          return result
          
      except HTTPException:
          raise
      except Exception as e:
          logger.error(f"Error indexing SPUs for tenant_id={request.tenant_id}: {e}", exc_info=True)
3c1f8031   tangwang   api/routes/indexe...
232
          raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
0064e946   tangwang   feat: 增量索引服务、租户配置...
233
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
234
  
89638140   tangwang   重构 indexer 文档构建接口...
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
  @router.post("/build-docs")
  async def build_docs(request: BuildDocsRequest):
      """
      构建 ES 文档(不访问数据库、不写入 ES)。
  
      使用场景:
      - 上游(例如 Java 索引程序)已经从 MySQL 查询出了 SPU / SKU / Option 等原始行数据
      - 希望复用本项目的全部“索引富化”能力(多语言、翻译、向量、规格聚合等)
      - 只需要拿到与 `mappings/search_products.json` 一致的 doc 列表,由上游自行写入 ES
      """
      try:
          if not request.items:
              raise HTTPException(status_code=400, detail="items cannot be empty")
          if len(request.items) > 200:
              raise HTTPException(status_code=400, detail="Maximum 200 items allowed per request")
  
          incremental_service = get_incremental_service()
          if incremental_service is None:
              raise HTTPException(status_code=503, detail="Incremental indexer service is not initialized")
  
          # 复用增量索引服务中的 transformer 缓存与配置 / 语言 / embedding 初始化逻辑
          transformer, encoder, enable_embedding = incremental_service._get_transformer_bundle(
              tenant_id=request.tenant_id
          )
  
          import pandas as pd
  
          docs: List[Dict[str, Any]] = []
be3f0d46   tangwang   /indexer/enrich-c...
263
          doc_spu_rows: List[pd.Series] = []
89638140   tangwang   重构 indexer 文档构建接口...
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
          failed: List[Dict[str, Any]] = []
  
          for item in request.items:
              try:
                  # 将上游传入的 MySQL 行数据转换为 Pandas 结构,复用 SPUDocumentTransformer
                  spu_df = pd.DataFrame([item.spu])
                  spu_row = spu_df.iloc[0]
                  skus_df = pd.DataFrame(item.skus) if item.skus else pd.DataFrame()
                  options_df = pd.DataFrame(item.options) if item.options else pd.DataFrame()
  
                  doc = transformer.transform_spu_to_doc(
                      tenant_id=request.tenant_id,
                      spu_row=spu_row,
                      skus=skus_df,
                      options=options_df,
be3f0d46   tangwang   /indexer/enrich-c...
279
                      fill_llm_attributes=False,
89638140   tangwang   重构 indexer 文档构建接口...
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
                  )
  
                  if doc is None:
                      failed.append(
                          {
                              "spu_id": str(item.spu.get("id")),
                              "error": "transform_spu_to_doc returned None",
                          }
                      )
                      continue
  
                  # 在“构建 doc”接口中,是否补齐 embedding 由内部配置决定(与增量索引一致)
                  # 此处不强制生成 / 不强制关闭,只复用 transformer_bundle 的 encoder / enable_embedding 设置。
                  if enable_embedding and encoder:
                      title_obj = doc.get("title") or {}
                      title_text = None
                      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
                      if title_text and str(title_text).strip():
ed948666   tangwang   tidy
304
305
306
307
308
309
310
311
312
313
314
                          import numpy as np
  
                          embeddings = encoder.encode(title_text)
                          if embeddings is None or len(embeddings) == 0:
                              raise RuntimeError(
                                  f"title_embedding empty for spu_id={doc.get('spu_id')}"
                              )
                          emb0 = np.asarray(embeddings[0], dtype=np.float32)
                          if emb0.ndim != 1 or emb0.size == 0 or not np.isfinite(emb0).all():
                              raise RuntimeError(
                                  f"title_embedding invalid for spu_id={doc.get('spu_id')}"
cc11ae04   tangwang   cnclip
315
                              )
ed948666   tangwang   tidy
316
                          doc["title_embedding"] = emb0.tolist()
89638140   tangwang   重构 indexer 文档构建接口...
317
318
  
                  docs.append(doc)
be3f0d46   tangwang   /indexer/enrich-c...
319
                  doc_spu_rows.append(spu_row)
89638140   tangwang   重构 indexer 文档构建接口...
320
321
322
323
324
325
326
327
              except Exception as e:
                  failed.append(
                      {
                          "spu_id": str(item.spu.get("id")),
                          "error": str(e),
                      }
                  )
  
be3f0d46   tangwang   /indexer/enrich-c...
328
329
330
331
332
333
334
          # 批量填充 LLM 字段(尽量攒批,每次最多 20 条;失败仅 warning,不影响 build-docs 主功能)
          try:
              if docs and doc_spu_rows:
                  transformer.fill_llm_attributes_batch(docs, doc_spu_rows)
          except Exception as e:
              logger.warning("Batch LLM fill failed in build-docs (tenant_id=%s): %s", request.tenant_id, e)
  
89638140   tangwang   重构 indexer 文档构建接口...
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
          return {
              "tenant_id": request.tenant_id,
              "docs": docs,
              "total": len(request.items),
              "success_count": len(docs),
              "failed_count": len(failed),
              "failed": failed,
          }
  
      except HTTPException:
          raise
      except Exception as e:
          logger.error(f"Error building docs for tenant_id={request.tenant_id}: {e}", exc_info=True)
          raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
  
  
  @router.post("/build-docs-from-db")
  async def build_docs_from_db(request: BuildDocsFromDbRequest):
      """
      基于数据库数据构建 ES 文档(测试 / 调试用)。
  
      - 入参:tenant_id + spu_ids
      - 步骤:
        1. 使用增量索引服务的查询能力,从 MySQL 批量加载 SPU / SKU / Option
        2. 组装为 BuildDocsRequest  items
        3. 内部调用与 /indexer/build-docs 相同的构建逻辑,返回 ES-ready docs
  
      注意:
      - 该接口主要用于本项目自测和调试;正式生产建议由上游(Java)自行查库后调用 /indexer/build-docs
      """
      try:
          if not request.spu_ids:
              raise HTTPException(status_code=400, detail="spu_ids cannot be empty")
          if len(request.spu_ids) > 200:
              raise HTTPException(status_code=400, detail="Maximum 200 SPU IDs allowed per request")
  
          incremental_service = get_incremental_service()
          if incremental_service is None:
              raise HTTPException(status_code=503, detail="Incremental indexer service is not initialized")
  
          # 直接复用增量服务里的批量查询方法,从 MySQL 拉取原始行数据
          # 只加载未删除的记录(include_deleted=False)
          spu_df = incremental_service._load_spus_for_spu_ids(
              tenant_id=request.tenant_id,
              spu_ids=request.spu_ids,
              include_deleted=False
          )
          if spu_df.empty:
              return {
                  "tenant_id": request.tenant_id,
                  "docs": [],
                  "total": 0,
                  "success_count": 0,
                  "failed_count": len(request.spu_ids),
                  "failed": [
                      {"spu_id": spu_id, "error": "SPU not found or deleted"}
                      for spu_id in request.spu_ids
                  ],
              }
  
          # 仅对存在的 spu_id 构建 item,避免无效 ID
          # _load_skus_for_spu_ids / _load_options_for_spu_ids 会自动过滤不存在的 spu_id
          existing_ids = [str(int(i)) for i in spu_df["id"].tolist()]
          skus_df = incremental_service._load_skus_for_spu_ids(
              tenant_id=request.tenant_id, spu_ids=existing_ids
          )
          options_df = incremental_service._load_options_for_spu_ids(
              tenant_id=request.tenant_id, spu_ids=existing_ids
          )
  
          import pandas as pd
  
          # group by spu_id 方便取子集
          sku_groups = skus_df.groupby("spu_id") if not skus_df.empty else None
          option_groups = options_df.groupby("spu_id") if not options_df.empty else None
  
          items: List[BuildDocItem] = []
          failed: List[Dict[str, Any]] = []
  
          for _, spu_row in spu_df.iterrows():
              spu_id = int(spu_row["id"])
              try:
                  spu_dict = spu_row.to_dict()
                  skus = (
                      sku_groups.get_group(spu_id).to_dict("records")
                      if sku_groups is not None and spu_id in sku_groups.groups
                      else []
                  )
                  options = (
                      option_groups.get_group(spu_id).to_dict("records")
                      if option_groups is not None and spu_id in option_groups.groups
                      else []
                  )
                  items.append(
                      BuildDocItem(
                          spu=spu_dict,
                          skus=skus,
                          options=options,
                      )
                  )
              except Exception as e:
                  failed.append(
                      {
                          "spu_id": str(spu_id),
                          "error": str(e),
                      }
                  )
  
          if not items:
              return {
                  "tenant_id": request.tenant_id,
                  "docs": [],
                  "total": 0,
                  "success_count": 0,
                  "failed_count": len(request.spu_ids),
                  "failed": failed
                  or [
                      {"spu_id": spu_id, "error": "SPU not found or data load failed"}
                      for spu_id in request.spu_ids
                  ],
              }
  
          # 调用与 /indexer/build-docs 相同的构建逻辑
          build_request = BuildDocsRequest(tenant_id=request.tenant_id, items=items)
          result = await build_docs(build_request)
  
          # 合并两层 failed 信息
          merged_failed = list(result.get("failed", [])) if isinstance(result, dict) else []
          merged_failed.extend(failed)
  
          if isinstance(result, dict):
              result["failed"] = merged_failed
              # 更新 failed_count
              result["failed_count"] = len(merged_failed)
              return result
          return result
  
      except HTTPException:
          raise
      except Exception as e:
          logger.error(f"Error building docs from DB for tenant_id={request.tenant_id}: {e}", exc_info=True)
          raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
  
  
5aaf0c7d   tangwang   feat(indexer): 完善...
479
480
481
  def _run_enrich_content(
      tenant_id: str,
      items: List[Dict[str, str]],
2703b6ea   tangwang   refactor(indexer)...
482
483
      enrichment_scopes: Optional[List[str]] = None,
      category_taxonomy_profile: str = "apparel",
5aaf0c7d   tangwang   feat(indexer): 完善...
484
  ) -> List[Dict[str, Any]]:
9f5994b4   tangwang   reranker
485
      """
d350861f   tangwang   索引结构修改
486
487
      同步执行内容理解,返回与 ES mapping 对齐的字段结构。
      语言策略由 product_enrich 内部统一决定,路由层不参与。
9f5994b4   tangwang   reranker
488
      """
d350861f   tangwang   索引结构修改
489
      from indexer.product_enrich import build_index_content_fields
6f7840cf   tangwang   refactor: rename ...
490
  
5aaf0c7d   tangwang   feat(indexer): 完善...
491
492
493
      results = build_index_content_fields(
          items=items,
          tenant_id=tenant_id,
2703b6ea   tangwang   refactor(indexer)...
494
495
          enrichment_scopes=enrichment_scopes,
          category_taxonomy_profile=category_taxonomy_profile,
5aaf0c7d   tangwang   feat(indexer): 完善...
496
      )
d350861f   tangwang   索引结构修改
497
      return [
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
498
          {
d350861f   tangwang   索引结构修改
499
500
501
502
              "spu_id": item["id"],
              "qanchors": item["qanchors"],
              "enriched_attributes": item["enriched_attributes"],
              "enriched_tags": item["enriched_tags"],
5aaf0c7d   tangwang   feat(indexer): 完善...
503
              "enriched_taxonomy_attributes": item["enriched_taxonomy_attributes"],
d350861f   tangwang   索引结构修改
504
              **({"error": item["error"]} if item.get("error") else {}),
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
505
          }
d350861f   tangwang   索引结构修改
506
          for item in results
9f5994b4   tangwang   reranker
507
508
      ]
  
9f5994b4   tangwang   reranker
509
510
511
512
  
  @router.post("/enrich-content")
  async def enrich_content(request: EnrichContentRequest):
      """
2703b6ea   tangwang   refactor(indexer)...
513
      内容理解字段生成接口:根据商品标题批量生成通用增强字段与品类 taxonomy 字段。
9f5994b4   tangwang   reranker
514
515
516
517
518
  
      使用场景:
      - 外部 indexer 采用「微服务组合」方式自己组织 doc 时,可调用本接口获取 LLM 生成的
        锚文本与语义属性,再与翻译、向量化结果合并写入 ES
      -  /indexer/build-docs 解耦,避免 build-docs  LLM 耗时过长而阻塞;调用方可
5aaf0c7d   tangwang   feat(indexer): 完善...
519
        先拿不含 qanchors/enriched_tags/taxonomy attributes  doc,再异步或离线补齐本接口结果后更新 ES
9f5994b4   tangwang   reranker
520
  
5aaf0c7d   tangwang   feat(indexer): 完善...
521
      实现逻辑与 indexer.product_enrich.build_index_content_fields 一致,支持多语言与 Redis 缓存。
9f5994b4   tangwang   reranker
522
523
524
525
526
527
528
529
530
531
532
      """
      try:
          if not request.items:
              raise HTTPException(status_code=400, detail="items cannot be empty")
          if len(request.items) > 50:
              raise HTTPException(
                  status_code=400,
                  detail="Maximum 50 items per request for enrich-content (LLM batch limit)",
              )
  
          items_payload = [
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
533
534
535
536
537
538
539
              {
                  "spu_id": it.spu_id,
                  "title": it.title or "",
                  "brief": it.brief or "",
                  "description": it.description or "",
                  "image_url": it.image_url or "",
              }
9f5994b4   tangwang   reranker
540
541
542
              for it in request.items
          ]
          loop = asyncio.get_event_loop()
2703b6ea   tangwang   refactor(indexer)...
543
          enrichment_scopes = request.resolved_enrichment_scopes()
9f5994b4   tangwang   reranker
544
545
546
547
          result = await loop.run_in_executor(
              None,
              lambda: _run_enrich_content(
                  tenant_id=request.tenant_id,
5aaf0c7d   tangwang   feat(indexer): 完善...
548
                  items=items_payload,
2703b6ea   tangwang   refactor(indexer)...
549
550
                  enrichment_scopes=enrichment_scopes,
                  category_taxonomy_profile=request.category_taxonomy_profile,
9f5994b4   tangwang   reranker
551
552
553
554
              ),
          )
          return {
              "tenant_id": request.tenant_id,
2703b6ea   tangwang   refactor(indexer)...
555
556
              "enrichment_scopes": enrichment_scopes,
              "category_taxonomy_profile": request.category_taxonomy_profile,
9f5994b4   tangwang   reranker
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
              "results": result,
              "total": len(result),
          }
      except HTTPException:
          raise
      except RuntimeError as e:
          if "DASHSCOPE_API_KEY" in str(e) or "cannot call LLM" in str(e).lower():
              raise HTTPException(
                  status_code=503,
                  detail="Content understanding service unavailable: DASHSCOPE_API_KEY not set",
              )
          raise HTTPException(status_code=500, detail=str(e))
      except Exception as e:
          logger.error(f"Error in enrich-content for tenant_id={request.tenant_id}: {e}", exc_info=True)
          raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
  
  
c55c5e47   tangwang   feat: 新增增量索引接口并重构...
574
575
576
577
578
579
580
  @router.post("/documents")
  async def get_documents(request: GetDocumentsRequest):
      """
      查询文档接口
      
      根据SPU ID列表获取ES文档数据(不写入ES)。用于查看、调试或验证SPU数据。
      """
0064e946   tangwang   feat: 增量索引服务、租户配置...
581
      try:
3c1f8031   tangwang   api/routes/indexe...
582
583
584
585
          if not request.spu_ids:
              raise HTTPException(status_code=400, detail="spu_ids cannot be empty")
          if len(request.spu_ids) > 100:
              raise HTTPException(status_code=400, detail="Maximum 100 SPU IDs allowed per request")
0064e946   tangwang   feat: 增量索引服务、租户配置...
586
587
          service = get_incremental_service()
          if service is None:
3c1f8031   tangwang   api/routes/indexe...
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
              raise HTTPException(status_code=503, detail="Incremental indexer service is not initialized")
          success_list, failed_list = [], []
          for spu_id in request.spu_ids:
              try:
                  doc = service.get_spu_document(tenant_id=request.tenant_id, spu_id=spu_id)
                  (success_list if doc else failed_list).append({
                      "spu_id": spu_id,
                      "document": doc
                  } if doc else {
                      "spu_id": spu_id,
                      "error": "SPU not found or deleted"
                  })
              except Exception as e:
                  failed_list.append({"spu_id": spu_id, "error": str(e)})
          return {
              "success": success_list,
              "failed": failed_list,
              "total": len(request.spu_ids),
              "success_count": len(success_list),
              "failed_count": len(failed_list)
          }
0064e946   tangwang   feat: 增量索引服务、租户配置...
609
610
611
      except HTTPException:
          raise
      except Exception as e:
c55c5e47   tangwang   feat: 新增增量索引接口并重构...
612
          logger.error(f"Error getting documents for tenant_id={request.tenant_id}: {e}", exc_info=True)
0064e946   tangwang   feat: 增量索引服务、租户配置...
613
614
615
616
617
          raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
  
  
  @router.get("/health")
  async def indexer_health_check():
3c1f8031   tangwang   api/routes/indexe...
618
      """检查索引服务健康状态"""
0064e946   tangwang   feat: 增量索引服务、租户配置...
619
      try:
0064e946   tangwang   feat: 增量索引服务、租户配置...
620
621
          service = get_incremental_service()
          if service is None:
3c1f8031   tangwang   api/routes/indexe...
622
              return {"status": "unavailable", "database": "unknown", "preloaded_data": {"category_mappings": 0}}
0064e946   tangwang   feat: 增量索引服务、租户配置...
623
          try:
0064e946   tangwang   feat: 增量索引服务、租户配置...
624
625
626
627
628
              with service.db_engine.connect() as conn:
                  conn.execute(text("SELECT 1"))
              db_status = "connected"
          except Exception as e:
              db_status = f"disconnected: {str(e)}"
0064e946   tangwang   feat: 增量索引服务、租户配置...
629
630
631
          return {
              "status": "available",
              "database": db_status,
3c1f8031   tangwang   api/routes/indexe...
632
              "preloaded_data": {"category_mappings": len(service.category_id_to_name)}
0064e946   tangwang   feat: 增量索引服务、租户配置...
633
          }
0064e946   tangwang   feat: 增量索引服务、租户配置...
634
635
      except Exception as e:
          logger.error(f"Error checking indexer health: {e}", exc_info=True)
3c1f8031   tangwang   api/routes/indexe...
636
          return {"status": "error", "message": str(e)}