Blame view

suggestion/builder.py 34.2 KB
ded6f29e   tangwang   补充suggestion模块
1
  """
ff9efda0   tangwang   suggest
2
  Suggestion index builder (Phase 2).
ded6f29e   tangwang   补充suggestion模块
3
  
ff9efda0   tangwang   suggest
4
5
6
7
  Capabilities:
  - Full rebuild to versioned index
  - Atomic alias publish
  - Incremental update from query logs with watermark
ded6f29e   tangwang   补充suggestion模块
8
9
10
11
12
13
  """
  
  import json
  import logging
  import math
  import re
ff9efda0   tangwang   suggest
14
  import unicodedata
ded6f29e   tangwang   补充suggestion模块
15
16
  from dataclasses import dataclass, field
  from datetime import datetime, timedelta, timezone
ff9efda0   tangwang   suggest
17
  from typing import Any, Dict, Iterator, List, Optional, Tuple
ded6f29e   tangwang   补充suggestion模块
18
19
20
  
  from sqlalchemy import text
  
86d8358b   tangwang   config optimize
21
  from config.loader import get_app_config
ded6f29e   tangwang   补充suggestion模块
22
  from config.tenant_config_loader import get_tenant_config_loader
00c8ddb9   tangwang   suggest rank opti...
23
  from query.query_parser import detect_text_language_for_suggestions
ded6f29e   tangwang   补充suggestion模块
24
  from suggestion.mapping import build_suggestion_mapping
ff9efda0   tangwang   suggest
25
  from utils.es_client import ESClient
ded6f29e   tangwang   补充suggestion模块
26
27
28
29
  
  logger = logging.getLogger(__name__)
  
  
ff9efda0   tangwang   suggest
30
  def _index_prefix() -> str:
86d8358b   tangwang   config optimize
31
      return get_app_config().runtime.index_namespace or ""
ff9efda0   tangwang   suggest
32
33
  
  
ff9efda0   tangwang   suggest
34
  def get_suggestion_alias_name(tenant_id: str) -> str:
5b8f58c0   tangwang   sugg
35
      """Read alias for suggestion index (single source of truth)."""
ff9efda0   tangwang   suggest
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
      return f"{_index_prefix()}search_suggestions_tenant_{tenant_id}_current"
  
  
  def get_suggestion_versioned_index_name(tenant_id: str, build_at: Optional[datetime] = None) -> str:
      """Versioned suggestion index name."""
      ts = (build_at or datetime.now(timezone.utc)).strftime("%Y%m%d%H%M%S")
      return f"{_index_prefix()}search_suggestions_tenant_{tenant_id}_v{ts}"
  
  
  def get_suggestion_versioned_index_pattern(tenant_id: str) -> str:
      return f"{_index_prefix()}search_suggestions_tenant_{tenant_id}_v*"
  
  
  def get_suggestion_meta_index_name() -> str:
      return f"{_index_prefix()}search_suggestions_meta"
  
  
ded6f29e   tangwang   补充suggestion模块
53
54
55
56
57
58
59
60
  @dataclass
  class SuggestionCandidate:
      text: str
      text_norm: str
      lang: str
      sources: set = field(default_factory=set)
      title_spu_ids: set = field(default_factory=set)
      qanchor_spu_ids: set = field(default_factory=set)
00c8ddb9   tangwang   suggest rank opti...
61
      tag_spu_ids: set = field(default_factory=set)
ded6f29e   tangwang   补充suggestion模块
62
63
64
65
66
      query_count_7d: int = 0
      query_count_30d: int = 0
      lang_confidence: float = 1.0
      lang_source: str = "default"
      lang_conflict: bool = False
ded6f29e   tangwang   补充suggestion模块
67
  
ff9efda0   tangwang   suggest
68
      def add_product(self, source: str, spu_id: str) -> None:
ded6f29e   tangwang   补充suggestion模块
69
70
71
72
73
          self.sources.add(source)
          if source == "title":
              self.title_spu_ids.add(spu_id)
          elif source == "qanchor":
              self.qanchor_spu_ids.add(spu_id)
00c8ddb9   tangwang   suggest rank opti...
74
75
          elif source == "tag":
              self.tag_spu_ids.add(spu_id)
ded6f29e   tangwang   补充suggestion模块
76
77
78
79
80
81
82
83
  
      def add_query_log(self, is_7d: bool) -> None:
          self.sources.add("query_log")
          self.query_count_30d += 1
          if is_7d:
              self.query_count_7d += 1
  
  
ff9efda0   tangwang   suggest
84
85
86
87
88
89
90
91
92
93
94
95
96
  @dataclass
  class QueryDelta:
      tenant_id: str
      lang: str
      text: str
      text_norm: str
      delta_7d: int = 0
      delta_30d: int = 0
      lang_confidence: float = 1.0
      lang_source: str = "default"
      lang_conflict: bool = False
  
  
ded6f29e   tangwang   补充suggestion模块
97
  class SuggestionIndexBuilder:
ff9efda0   tangwang   suggest
98
      """Build and update suggestion index."""
ded6f29e   tangwang   补充suggestion模块
99
100
101
102
103
104
  
      def __init__(self, es_client: ESClient, db_engine: Any):
          self.es_client = es_client
          self.db_engine = db_engine
  
      @staticmethod
ff9efda0   tangwang   suggest
105
106
107
108
109
110
111
112
113
114
      def _to_utc(dt: Any) -> Optional[datetime]:
          if dt is None:
              return None
          if isinstance(dt, datetime):
              if dt.tzinfo is None:
                  return dt.replace(tzinfo=timezone.utc)
              return dt.astimezone(timezone.utc)
          return None
  
      @staticmethod
ded6f29e   tangwang   补充suggestion模块
115
      def _normalize_text(value: str) -> str:
ff9efda0   tangwang   suggest
116
          text_value = unicodedata.normalize("NFKC", (value or "")).strip().lower()
ded6f29e   tangwang   补充suggestion模块
117
118
119
120
          text_value = re.sub(r"\s+", " ", text_value)
          return text_value
  
      @staticmethod
daf66a51   tangwang   已完成接口级压测脚本,覆盖搜索、s...
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
      def _prepare_title_for_suggest(title: str, max_len: int = 120) -> str:
          """
          Keep title-derived suggestions concise:
          - keep raw title when short enough
          - for long titles, keep the leading phrase before common separators
          - fallback to hard truncate
          """
          raw = str(title or "").strip()
          if not raw:
              return ""
          if len(raw) <= max_len:
              return raw
  
          head = re.split(r"[,,;;|/\\\\((\\[【]", raw, maxsplit=1)[0].strip()
          if 1 < len(head) <= max_len:
              return head
  
          truncated = raw[:max_len].rstrip(" ,,;;|/\\\\-—–()()[]【】")
          return truncated or raw[:max_len]
  
      @staticmethod
ded6f29e   tangwang   补充suggestion模块
142
143
144
145
146
147
148
149
      def _split_qanchors(value: Any) -> List[str]:
          if value is None:
              return []
          if isinstance(value, list):
              return [str(x).strip() for x in value if str(x).strip()]
          raw = str(value).strip()
          if not raw:
              return []
69881ecb   tangwang   相关性调参、enrich内容解析优化
150
          parts = re.split(r"[,、,;|/\n\t]+", raw)
ded6f29e   tangwang   补充suggestion模块
151
152
153
154
155
156
          out = [p.strip() for p in parts if p and p.strip()]
          if not out:
              return [raw]
          return out
  
      @staticmethod
00c8ddb9   tangwang   suggest rank opti...
157
158
159
160
161
162
163
164
      def _iter_product_tags(raw: Any) -> List[str]:
          if raw is None:
              return []
          if isinstance(raw, list):
              return [str(x).strip() for x in raw if str(x).strip()]
          s = str(raw).strip()
          if not s:
              return []
69881ecb   tangwang   相关性调参、enrich内容解析优化
165
          parts = re.split(r"[,、,;|/\n\t]+", s)
00c8ddb9   tangwang   suggest rank opti...
166
167
168
          out = [p.strip() for p in parts if p and p.strip()]
          return out if out else [s]
  
d350861f   tangwang   索引结构修改
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
      def _iter_multilang_product_tags(
          self,
          raw: Any,
          index_languages: List[str],
          primary_language: str,
      ) -> List[Tuple[str, str]]:
          if isinstance(raw, dict):
              pairs: List[Tuple[str, str]] = []
              for lang in index_languages:
                  for tag in self._iter_product_tags(raw.get(lang)):
                      pairs.append((lang, tag))
              return pairs
  
          pairs = []
          for tag in self._iter_product_tags(raw):
              tag_lang, _, _ = detect_text_language_for_suggestions(
                  tag,
                  index_languages=index_languages,
                  primary_language=primary_language,
              )
              pairs.append((tag_lang, tag))
          return pairs
  
00c8ddb9   tangwang   suggest rank opti...
192
      @staticmethod
ded6f29e   tangwang   补充suggestion模块
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
      def _looks_noise(text_value: str) -> bool:
          if not text_value:
              return True
          if len(text_value) > 120:
              return True
          if re.fullmatch(r"[\W_]+", text_value):
              return True
          return False
  
      @staticmethod
      def _normalize_lang(lang: Optional[str]) -> Optional[str]:
          if not lang:
              return None
          token = str(lang).strip().lower().replace("-", "_")
          if not token:
              return None
ded6f29e   tangwang   补充suggestion模块
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
          if token in {"zh_tw", "pt_br"}:
              return token
          return token.split("_")[0]
  
      @staticmethod
      def _parse_request_params_language(raw: Any) -> Optional[str]:
          if raw is None:
              return None
          if isinstance(raw, dict):
              return raw.get("language")
          text_raw = str(raw).strip()
          if not text_raw:
              return None
          try:
              obj = json.loads(text_raw)
              if isinstance(obj, dict):
                  return obj.get("language")
          except Exception:
              return None
          return None
  
ded6f29e   tangwang   补充suggestion模块
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
      def _resolve_query_language(
          self,
          query: str,
          log_language: Optional[str],
          request_params: Any,
          index_languages: List[str],
          primary_language: str,
      ) -> Tuple[str, float, str, bool]:
          """Resolve lang with priority: log field > request_params > script/model."""
          langs_set = set(index_languages or [])
          primary = self._normalize_lang(primary_language) or "en"
          if primary not in langs_set and langs_set:
              primary = index_languages[0]
  
          log_lang = self._normalize_lang(log_language)
          req_lang = self._normalize_lang(self._parse_request_params_language(request_params))
          conflict = bool(log_lang and req_lang and log_lang != req_lang)
  
          if log_lang and (not langs_set or log_lang in langs_set):
              return log_lang, 1.0, "log_field", conflict
  
          if req_lang and (not langs_set or req_lang in langs_set):
              return req_lang, 1.0, "request_params", conflict
  
00c8ddb9   tangwang   suggest rank opti...
254
255
256
257
258
259
260
          det_lang, conf, det_source = detect_text_language_for_suggestions(
              query,
              index_languages=index_languages,
              primary_language=primary,
          )
          if det_lang and (not langs_set or det_lang in langs_set):
              return det_lang, conf, det_source, conflict
ded6f29e   tangwang   补充suggestion模块
261
262
263
264
  
          return primary, 0.3, "default", conflict
  
      @staticmethod
00c8ddb9   tangwang   suggest rank opti...
265
266
267
268
269
270
271
      def _compute_rank_score(
          query_count_30d: int,
          query_count_7d: int,
          qanchor_doc_count: int,
          title_doc_count: int,
          tag_doc_count: int = 0,
      ) -> float:
ded6f29e   tangwang   补充suggestion模块
272
          return (
ff9efda0   tangwang   suggest
273
274
275
              1.8 * math.log1p(max(query_count_30d, 0))
              + 1.2 * math.log1p(max(query_count_7d, 0))
              + 1.0 * math.log1p(max(qanchor_doc_count, 0))
00c8ddb9   tangwang   suggest rank opti...
276
              + 0.85 * math.log1p(max(tag_doc_count, 0))
ff9efda0   tangwang   suggest
277
              + 0.6 * math.log1p(max(title_doc_count, 0))
ded6f29e   tangwang   补充suggestion模块
278
279
          )
  
ff9efda0   tangwang   suggest
280
281
282
283
284
285
286
      @classmethod
      def _compute_rank_score_from_candidate(cls, c: SuggestionCandidate) -> float:
          return cls._compute_rank_score(
              query_count_30d=c.query_count_30d,
              query_count_7d=c.query_count_7d,
              qanchor_doc_count=len(c.qanchor_spu_ids),
              title_doc_count=len(c.title_spu_ids),
00c8ddb9   tangwang   suggest rank opti...
287
              tag_doc_count=len(c.tag_spu_ids),
ff9efda0   tangwang   suggest
288
289
290
291
          )
  
      def _iter_products(self, tenant_id: str, batch_size: int = 500) -> Iterator[Dict[str, Any]]:
          """Stream product docs from tenant index using search_after."""
ded6f29e   tangwang   补充suggestion模块
292
293
294
          from indexer.mapping_generator import get_tenant_index_name
  
          index_name = get_tenant_index_name(tenant_id)
ded6f29e   tangwang   补充suggestion模块
295
296
297
298
299
          search_after: Optional[List[Any]] = None
  
          while True:
              body: Dict[str, Any] = {
                  "size": batch_size,
e50924ed   tangwang   1. tags -> enrich...
300
                  "_source": ["id", "spu_id", "title", "qanchors", "enriched_tags"],
daf66a51   tangwang   已完成接口级压测脚本,覆盖搜索、s...
301
302
                  "sort": [
                      {"spu_id": {"order": "asc", "missing": "_last"}},
00c8ddb9   tangwang   suggest rank opti...
303
                      {"id.keyword": {"order": "asc", "missing": "_last"}},
daf66a51   tangwang   已完成接口级压测脚本,覆盖搜索、s...
304
                  ],
ded6f29e   tangwang   补充suggestion模块
305
306
307
308
309
310
311
312
313
                  "query": {"match_all": {}},
              }
              if search_after is not None:
                  body["search_after"] = search_after
  
              resp = self.es_client.client.search(index=index_name, body=body)
              hits = resp.get("hits", {}).get("hits", []) or []
              if not hits:
                  break
ff9efda0   tangwang   suggest
314
315
              for hit in hits:
                  yield hit
ded6f29e   tangwang   补充suggestion模块
316
317
318
              search_after = hits[-1].get("sort")
              if len(hits) < batch_size:
                  break
ded6f29e   tangwang   补充suggestion模块
319
  
ff9efda0   tangwang   suggest
320
      def _iter_query_log_rows(
ded6f29e   tangwang   补充suggestion模块
321
322
          self,
          tenant_id: str,
ff9efda0   tangwang   suggest
323
324
325
326
327
328
329
330
331
332
333
334
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
          since: datetime,
          until: datetime,
          fetch_size: int = 2000,
      ) -> Iterator[Any]:
          """Stream search logs from MySQL with bounded time range."""
          query_sql = text(
              """
              SELECT query, language, request_params, create_time
              FROM shoplazza_search_log
              WHERE tenant_id = :tenant_id
                AND deleted = 0
                AND query IS NOT NULL
                AND query <> ''
                AND create_time >= :since_time
                AND create_time < :until_time
              ORDER BY create_time ASC
              """
          )
  
          with self.db_engine.connect().execution_options(stream_results=True) as conn:
              result = conn.execute(
                  query_sql,
                  {
                      "tenant_id": int(tenant_id),
                      "since_time": since,
                      "until_time": until,
                  },
              )
              while True:
                  rows = result.fetchmany(fetch_size)
                  if not rows:
                      break
                  for row in rows:
                      yield row
  
      def _ensure_meta_index(self) -> str:
          meta_index = get_suggestion_meta_index_name()
          if self.es_client.index_exists(meta_index):
              return meta_index
          body = {
              "settings": {
                  "number_of_shards": 1,
                  "number_of_replicas": 0,
                  "refresh_interval": "1s",
              },
              "mappings": {
                  "properties": {
                      "tenant_id": {"type": "keyword"},
                      "active_alias": {"type": "keyword"},
                      "active_index": {"type": "keyword"},
                      "last_full_build_at": {"type": "date"},
                      "last_incremental_build_at": {"type": "date"},
                      "last_incremental_watermark": {"type": "date"},
                      "updated_at": {"type": "date"},
                  }
              },
          }
          if not self.es_client.create_index(meta_index, body):
              raise RuntimeError(f"Failed to create suggestion meta index: {meta_index}")
          return meta_index
  
      def _get_meta(self, tenant_id: str) -> Dict[str, Any]:
          meta_index = self._ensure_meta_index()
          try:
              resp = self.es_client.client.get(index=meta_index, id=str(tenant_id))
              return resp.get("_source", {}) or {}
          except Exception:
              return {}
  
      def _upsert_meta(self, tenant_id: str, patch: Dict[str, Any]) -> None:
          meta_index = self._ensure_meta_index()
          current = self._get_meta(tenant_id)
          now_iso = datetime.now(timezone.utc).isoformat()
          merged = {
              "tenant_id": str(tenant_id),
              **current,
              **patch,
              "updated_at": now_iso,
          }
          self.es_client.client.index(index=meta_index, id=str(tenant_id), document=merged, refresh="wait_for")
  
      def _cleanup_old_versions(self, tenant_id: str, keep_versions: int, protected_indices: Optional[List[str]] = None) -> List[str]:
          if keep_versions < 1:
              keep_versions = 1
          protected = set(protected_indices or [])
          pattern = get_suggestion_versioned_index_pattern(tenant_id)
          all_indices = self.es_client.list_indices(pattern)
          if len(all_indices) <= keep_versions:
              return []
  
          # Names are timestamp-ordered by suffix; keep newest N.
          kept = set(sorted(all_indices)[-keep_versions:])
          dropped: List[str] = []
          for idx in sorted(all_indices):
              if idx in kept or idx in protected:
                  continue
              if self.es_client.delete_index(idx):
                  dropped.append(idx)
          return dropped
  
      def _publish_alias(self, tenant_id: str, index_name: str, keep_versions: int = 2) -> Dict[str, Any]:
          alias_name = get_suggestion_alias_name(tenant_id)
          current_indices = self.es_client.get_alias_indices(alias_name)
  
          actions: List[Dict[str, Any]] = []
          for idx in current_indices:
              actions.append({"remove": {"index": idx, "alias": alias_name}})
          actions.append({"add": {"index": index_name, "alias": alias_name}})
  
          if not self.es_client.update_aliases(actions):
              raise RuntimeError(f"Failed to publish alias {alias_name} -> {index_name}")
  
          dropped = self._cleanup_old_versions(
              tenant_id=tenant_id,
              keep_versions=keep_versions,
              protected_indices=[index_name],
          )
ded6f29e   tangwang   补充suggestion模块
440
  
ff9efda0   tangwang   suggest
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
          self._upsert_meta(
              tenant_id,
              {
                  "active_alias": alias_name,
                  "active_index": index_name,
              },
          )
  
          return {
              "alias": alias_name,
              "previous_indices": current_indices,
              "current_index": index_name,
              "dropped_old_indices": dropped,
          }
  
      def _resolve_incremental_target_index(self, tenant_id: str) -> Optional[str]:
5b8f58c0   tangwang   sugg
457
          """Resolve active suggestion index for incremental updates (alias only)."""
ff9efda0   tangwang   suggest
458
459
460
461
462
          alias_name = get_suggestion_alias_name(tenant_id)
          aliased = self.es_client.get_alias_indices(alias_name)
          if aliased:
              # alias should map to one index in this design
              return sorted(aliased)[-1]
ff9efda0   tangwang   suggest
463
464
465
466
467
468
469
470
471
472
473
          return None
  
      def _build_full_candidates(
          self,
          tenant_id: str,
          index_languages: List[str],
          primary_language: str,
          days: int,
          batch_size: int,
          min_query_len: int,
      ) -> Dict[Tuple[str, str], SuggestionCandidate]:
ded6f29e   tangwang   补充suggestion模块
474
475
476
          key_to_candidate: Dict[Tuple[str, str], SuggestionCandidate] = {}
  
          # Step 1: product title/qanchors
ff9efda0   tangwang   suggest
477
          for hit in self._iter_products(tenant_id, batch_size=batch_size):
ded6f29e   tangwang   补充suggestion模块
478
              src = hit.get("_source", {}) or {}
daf66a51   tangwang   已完成接口级压测脚本,覆盖搜索、s...
479
480
              product_id = str(src.get("spu_id") or src.get("id") or hit.get("_id") or "")
              if not product_id:
ded6f29e   tangwang   补充suggestion模块
481
482
483
                  continue
              title_obj = src.get("title") or {}
              qanchor_obj = src.get("qanchors") or {}
ded6f29e   tangwang   补充suggestion模块
484
485
486
487
  
              for lang in index_languages:
                  title = ""
                  if isinstance(title_obj, dict):
daf66a51   tangwang   已完成接口级压测脚本,覆盖搜索、s...
488
                      title = self._prepare_title_for_suggest(title_obj.get(lang) or "")
ded6f29e   tangwang   补充suggestion模块
489
490
491
492
493
494
495
496
                  if title:
                      text_norm = self._normalize_text(title)
                      if not self._looks_noise(text_norm):
                          key = (lang, text_norm)
                          c = key_to_candidate.get(key)
                          if c is None:
                              c = SuggestionCandidate(text=title, text_norm=text_norm, lang=lang)
                              key_to_candidate[key] = c
daf66a51   tangwang   已完成接口级压测脚本,覆盖搜索、s...
497
                          c.add_product("title", spu_id=product_id)
ded6f29e   tangwang   补充suggestion模块
498
499
500
501
502
503
504
505
506
507
508
509
510
  
                  q_raw = None
                  if isinstance(qanchor_obj, dict):
                      q_raw = qanchor_obj.get(lang)
                  for q_text in self._split_qanchors(q_raw):
                      text_norm = self._normalize_text(q_text)
                      if self._looks_noise(text_norm):
                          continue
                      key = (lang, text_norm)
                      c = key_to_candidate.get(key)
                      if c is None:
                          c = SuggestionCandidate(text=q_text, text_norm=text_norm, lang=lang)
                          key_to_candidate[key] = c
daf66a51   tangwang   已完成接口级压测脚本,覆盖搜索、s...
511
                      c.add_product("qanchor", spu_id=product_id)
ded6f29e   tangwang   补充suggestion模块
512
  
d350861f   tangwang   索引结构修改
513
              for tag_lang, tag in self._iter_multilang_product_tags(
e50924ed   tangwang   1. tags -> enrich...
514
                  src.get("enriched_tags"),
d350861f   tangwang   索引结构修改
515
516
517
                  index_languages=index_languages,
                  primary_language=primary_language,
              ):
00c8ddb9   tangwang   suggest rank opti...
518
519
520
521
522
523
524
525
526
527
                  text_norm = self._normalize_text(tag)
                  if self._looks_noise(text_norm):
                      continue
                  key = (tag_lang, text_norm)
                  c = key_to_candidate.get(key)
                  if c is None:
                      c = SuggestionCandidate(text=tag, text_norm=text_norm, lang=tag_lang)
                      key_to_candidate[key] = c
                  c.add_product("tag", spu_id=product_id)
  
ded6f29e   tangwang   补充suggestion模块
528
529
          # Step 2: query logs
          now = datetime.now(timezone.utc)
ff9efda0   tangwang   suggest
530
          since = now - timedelta(days=days)
ded6f29e   tangwang   补充suggestion模块
531
          since_7d = now - timedelta(days=7)
ded6f29e   tangwang   补充suggestion模块
532
  
ff9efda0   tangwang   suggest
533
          for row in self._iter_query_log_rows(tenant_id=tenant_id, since=since, until=now):
ded6f29e   tangwang   补充suggestion模块
534
535
536
              q = str(row.query or "").strip()
              if len(q) < min_query_len:
                  continue
ff9efda0   tangwang   suggest
537
  
ded6f29e   tangwang   补充suggestion模块
538
539
540
541
542
543
544
545
546
547
              lang, conf, source, conflict = self._resolve_query_language(
                  query=q,
                  log_language=getattr(row, "language", None),
                  request_params=getattr(row, "request_params", None),
                  index_languages=index_languages,
                  primary_language=primary_language,
              )
              text_norm = self._normalize_text(q)
              if self._looks_noise(text_norm):
                  continue
ff9efda0   tangwang   suggest
548
  
ded6f29e   tangwang   补充suggestion模块
549
550
551
552
553
              key = (lang, text_norm)
              c = key_to_candidate.get(key)
              if c is None:
                  c = SuggestionCandidate(text=q, text_norm=text_norm, lang=lang)
                  key_to_candidate[key] = c
ff9efda0   tangwang   suggest
554
  
ded6f29e   tangwang   补充suggestion模块
555
556
557
558
              c.lang_confidence = max(c.lang_confidence, conf)
              c.lang_source = source if c.lang_source == "default" else c.lang_source
              c.lang_conflict = c.lang_conflict or conflict
  
ff9efda0   tangwang   suggest
559
560
              created_at = self._to_utc(getattr(row, "create_time", None))
              is_7d = bool(created_at and created_at >= since_7d)
ded6f29e   tangwang   补充suggestion模块
561
562
              c.add_query_log(is_7d=is_7d)
  
ff9efda0   tangwang   suggest
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
          return key_to_candidate
  
      def _candidate_to_doc(self, tenant_id: str, c: SuggestionCandidate, now_iso: str) -> Dict[str, Any]:
          rank_score = self._compute_rank_score_from_candidate(c)
          completion_obj = {c.lang: {"input": [c.text], "weight": int(max(rank_score, 1.0) * 100)}}
          sat_obj = {c.lang: c.text}
          return {
              "_id": f"{tenant_id}|{c.lang}|{c.text_norm}",
              "tenant_id": str(tenant_id),
              "lang": c.lang,
              "text": c.text,
              "text_norm": c.text_norm,
              "sources": sorted(c.sources),
              "title_doc_count": len(c.title_spu_ids),
              "qanchor_doc_count": len(c.qanchor_spu_ids),
00c8ddb9   tangwang   suggest rank opti...
578
              "tag_doc_count": len(c.tag_spu_ids),
ff9efda0   tangwang   suggest
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
              "query_count_7d": c.query_count_7d,
              "query_count_30d": c.query_count_30d,
              "rank_score": float(rank_score),
              "lang_confidence": float(c.lang_confidence),
              "lang_source": c.lang_source,
              "lang_conflict": bool(c.lang_conflict),
              "status": 1,
              "updated_at": now_iso,
              "completion": completion_obj,
              "sat": sat_obj,
          }
  
      def rebuild_tenant_index(
          self,
          tenant_id: str,
          days: int = 365,
ff9efda0   tangwang   suggest
595
596
597
598
          batch_size: int = 500,
          min_query_len: int = 1,
          publish_alias: bool = True,
          keep_versions: int = 2,
ff9efda0   tangwang   suggest
599
600
601
602
603
604
605
606
607
608
609
610
611
      ) -> Dict[str, Any]:
          """
          Full rebuild.
  
          Phase2 default behavior:
          - write to versioned index
          - atomically publish alias
          """
          tenant_loader = get_tenant_config_loader()
          tenant_cfg = tenant_loader.get_tenant_config(tenant_id)
          index_languages: List[str] = tenant_cfg.get("index_languages") or ["en", "zh"]
          primary_language: str = tenant_cfg.get("primary_language") or "en"
  
5b8f58c0   tangwang   sugg
612
613
          # Always write to a fresh versioned index; legacy concrete index is no longer supported.
          index_name = get_suggestion_versioned_index_name(tenant_id)
ff9efda0   tangwang   suggest
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
  
          if self.es_client.index_exists(index_name):
              raise RuntimeError(f"Target suggestion index already exists: {index_name}")
  
          mapping = build_suggestion_mapping(index_languages=index_languages)
          if not self.es_client.create_index(index_name, mapping):
              raise RuntimeError(f"Failed to create suggestion index: {index_name}")
  
          key_to_candidate = self._build_full_candidates(
              tenant_id=tenant_id,
              index_languages=index_languages,
              primary_language=primary_language,
              days=days,
              batch_size=batch_size,
              min_query_len=min_query_len,
          )
  
ded6f29e   tangwang   补充suggestion模块
631
          now_iso = datetime.now(timezone.utc).isoformat()
ff9efda0   tangwang   suggest
632
          docs = [self._candidate_to_doc(tenant_id, c, now_iso) for c in key_to_candidate.values()]
ded6f29e   tangwang   补充suggestion模块
633
634
  
          if docs:
ff9efda0   tangwang   suggest
635
              bulk_result = self.es_client.bulk_index(index_name=index_name, docs=docs)
ded6f29e   tangwang   补充suggestion模块
636
637
              self.es_client.refresh(index_name)
          else:
ff9efda0   tangwang   suggest
638
639
640
              bulk_result = {"success": 0, "failed": 0, "errors": []}
  
          alias_publish: Optional[Dict[str, Any]] = None
5b8f58c0   tangwang   sugg
641
          if publish_alias:
ff9efda0   tangwang   suggest
642
643
644
645
646
647
648
649
650
651
652
              alias_publish = self._publish_alias(
                  tenant_id=tenant_id,
                  index_name=index_name,
                  keep_versions=keep_versions,
              )
  
          now_utc = datetime.now(timezone.utc).isoformat()
          meta_patch: Dict[str, Any] = {
              "last_full_build_at": now_utc,
              "last_incremental_watermark": now_utc,
          }
5b8f58c0   tangwang   sugg
653
          if publish_alias:
ff9efda0   tangwang   suggest
654
655
656
              meta_patch["active_index"] = index_name
              meta_patch["active_alias"] = get_suggestion_alias_name(tenant_id)
          self._upsert_meta(tenant_id, meta_patch)
ded6f29e   tangwang   补充suggestion模块
657
658
  
          return {
ff9efda0   tangwang   suggest
659
              "mode": "full",
ded6f29e   tangwang   补充suggestion模块
660
661
              "tenant_id": str(tenant_id),
              "index_name": index_name,
ff9efda0   tangwang   suggest
662
663
              "alias_published": bool(alias_publish),
              "alias_publish": alias_publish,
ded6f29e   tangwang   补充suggestion模块
664
665
              "total_candidates": len(key_to_candidate),
              "indexed_docs": len(docs),
ff9efda0   tangwang   suggest
666
              "bulk_result": bulk_result,
ded6f29e   tangwang   补充suggestion模块
667
668
          }
  
ff9efda0   tangwang   suggest
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
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
      def _build_incremental_deltas(
          self,
          tenant_id: str,
          index_languages: List[str],
          primary_language: str,
          since: datetime,
          until: datetime,
          min_query_len: int,
      ) -> Dict[Tuple[str, str], QueryDelta]:
          now = datetime.now(timezone.utc)
          since_7d = now - timedelta(days=7)
          deltas: Dict[Tuple[str, str], QueryDelta] = {}
  
          for row in self._iter_query_log_rows(tenant_id=tenant_id, since=since, until=until):
              q = str(row.query or "").strip()
              if len(q) < min_query_len:
                  continue
  
              lang, conf, source, conflict = self._resolve_query_language(
                  query=q,
                  log_language=getattr(row, "language", None),
                  request_params=getattr(row, "request_params", None),
                  index_languages=index_languages,
                  primary_language=primary_language,
              )
              text_norm = self._normalize_text(q)
              if self._looks_noise(text_norm):
                  continue
  
              key = (lang, text_norm)
              item = deltas.get(key)
              if item is None:
                  item = QueryDelta(
                      tenant_id=str(tenant_id),
                      lang=lang,
                      text=q,
                      text_norm=text_norm,
                      lang_confidence=conf,
                      lang_source=source,
                      lang_conflict=conflict,
                  )
                  deltas[key] = item
  
              created_at = self._to_utc(getattr(row, "create_time", None))
              item.delta_30d += 1
              if created_at and created_at >= since_7d:
                  item.delta_7d += 1
  
              if conf > item.lang_confidence:
                  item.lang_confidence = conf
                  item.lang_source = source
              item.lang_conflict = item.lang_conflict or conflict
  
          return deltas
  
      def _delta_to_upsert_doc(self, delta: QueryDelta, now_iso: str) -> Dict[str, Any]:
          rank_score = self._compute_rank_score(
              query_count_30d=delta.delta_30d,
              query_count_7d=delta.delta_7d,
              qanchor_doc_count=0,
              title_doc_count=0,
00c8ddb9   tangwang   suggest rank opti...
730
              tag_doc_count=0,
ff9efda0   tangwang   suggest
731
732
733
734
735
736
737
738
739
          )
          return {
              "tenant_id": delta.tenant_id,
              "lang": delta.lang,
              "text": delta.text,
              "text_norm": delta.text_norm,
              "sources": ["query_log"],
              "title_doc_count": 0,
              "qanchor_doc_count": 0,
00c8ddb9   tangwang   suggest rank opti...
740
              "tag_doc_count": 0,
ff9efda0   tangwang   suggest
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
              "query_count_7d": delta.delta_7d,
              "query_count_30d": delta.delta_30d,
              "rank_score": float(rank_score),
              "lang_confidence": float(delta.lang_confidence),
              "lang_source": delta.lang_source,
              "lang_conflict": bool(delta.lang_conflict),
              "status": 1,
              "updated_at": now_iso,
              "completion": {
                  delta.lang: {
                      "input": [delta.text],
                      "weight": int(max(rank_score, 1.0) * 100),
                  }
              },
              "sat": {delta.lang: delta.text},
          }
  
      @staticmethod
      def _build_incremental_update_script() -> str:
          return """
              if (ctx._source == null || ctx._source.isEmpty()) {
                  ctx._source = params.upsert;
                  return;
              }
  
              if (ctx._source.query_count_30d == null) { ctx._source.query_count_30d = 0; }
              if (ctx._source.query_count_7d == null) { ctx._source.query_count_7d = 0; }
              if (ctx._source.qanchor_doc_count == null) { ctx._source.qanchor_doc_count = 0; }
              if (ctx._source.title_doc_count == null) { ctx._source.title_doc_count = 0; }
00c8ddb9   tangwang   suggest rank opti...
770
              if (ctx._source.tag_doc_count == null) { ctx._source.tag_doc_count = 0; }
ff9efda0   tangwang   suggest
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
  
              ctx._source.query_count_30d += params.delta_30d;
              ctx._source.query_count_7d += params.delta_7d;
  
              if (ctx._source.sources == null) { ctx._source.sources = new ArrayList(); }
              if (!ctx._source.sources.contains('query_log')) { ctx._source.sources.add('query_log'); }
  
              if (ctx._source.lang_conflict == null) { ctx._source.lang_conflict = false; }
              ctx._source.lang_conflict = ctx._source.lang_conflict || params.lang_conflict;
  
              if (ctx._source.lang_confidence == null || params.lang_confidence > ctx._source.lang_confidence) {
                  ctx._source.lang_confidence = params.lang_confidence;
                  ctx._source.lang_source = params.lang_source;
              }
  
              int q30 = ctx._source.query_count_30d;
              int q7 = ctx._source.query_count_7d;
              int qa = ctx._source.qanchor_doc_count;
              int td = ctx._source.title_doc_count;
00c8ddb9   tangwang   suggest rank opti...
790
              int tg = ctx._source.tag_doc_count;
ff9efda0   tangwang   suggest
791
792
793
794
  
              double score = 1.8 * Math.log(1 + q30)
                           + 1.2 * Math.log(1 + q7)
                           + 1.0 * Math.log(1 + qa)
00c8ddb9   tangwang   suggest rank opti...
795
                           + 0.85 * Math.log(1 + tg)
ff9efda0   tangwang   suggest
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
                           + 0.6 * Math.log(1 + td);
              ctx._source.rank_score = score;
              ctx._source.status = 1;
              ctx._source.updated_at = params.now_iso;
              ctx._source.text = params.text;
              ctx._source.lang = params.lang;
              ctx._source.text_norm = params.text_norm;
  
              if (ctx._source.completion == null) { ctx._source.completion = new HashMap(); }
              Map c = new HashMap();
              c.put('input', params.completion_input);
              c.put('weight', params.completion_weight);
              ctx._source.completion.put(params.lang, c);
  
              if (ctx._source.sat == null) { ctx._source.sat = new HashMap(); }
              ctx._source.sat.put(params.lang, params.text);
          """
  
      def _build_incremental_actions(self, target_index: str, deltas: Dict[Tuple[str, str], QueryDelta]) -> List[Dict[str, Any]]:
          now_iso = datetime.now(timezone.utc).isoformat()
          script_source = self._build_incremental_update_script()
          actions: List[Dict[str, Any]] = []
  
          for delta in deltas.values():
              upsert_doc = self._delta_to_upsert_doc(delta=delta, now_iso=now_iso)
              upsert_rank = float(upsert_doc.get("rank_score") or 0.0)
              action = {
                  "_op_type": "update",
                  "_index": target_index,
                  "_id": f"{delta.tenant_id}|{delta.lang}|{delta.text_norm}",
                  "scripted_upsert": True,
                  "script": {
                      "lang": "painless",
                      "source": script_source,
                      "params": {
                          "delta_30d": int(delta.delta_30d),
                          "delta_7d": int(delta.delta_7d),
                          "lang_confidence": float(delta.lang_confidence),
                          "lang_source": delta.lang_source,
                          "lang_conflict": bool(delta.lang_conflict),
                          "now_iso": now_iso,
                          "lang": delta.lang,
                          "text": delta.text,
                          "text_norm": delta.text_norm,
                          "completion_input": [delta.text],
                          "completion_weight": int(max(upsert_rank, 1.0) * 100),
                          "upsert": upsert_doc,
                      },
                  },
                  "upsert": upsert_doc,
              }
              actions.append(action)
  
          return actions
  
      def incremental_update_tenant_index(
          self,
          tenant_id: str,
          min_query_len: int = 1,
          fallback_days: int = 7,
          overlap_minutes: int = 30,
          bootstrap_if_missing: bool = True,
          bootstrap_days: int = 30,
          batch_size: int = 500,
      ) -> Dict[str, Any]:
          tenant_loader = get_tenant_config_loader()
          tenant_cfg = tenant_loader.get_tenant_config(tenant_id)
          index_languages: List[str] = tenant_cfg.get("index_languages") or ["en", "zh"]
          primary_language: str = tenant_cfg.get("primary_language") or "en"
  
          target_index = self._resolve_incremental_target_index(tenant_id)
          if not target_index:
              if not bootstrap_if_missing:
                  raise RuntimeError(
                      f"No active suggestion index for tenant={tenant_id}. "
                      "Run full rebuild first or enable bootstrap_if_missing."
                  )
              full_result = self.rebuild_tenant_index(
                  tenant_id=tenant_id,
                  days=bootstrap_days,
                  batch_size=batch_size,
                  min_query_len=min_query_len,
1cca75c8   tangwang   sugg 索引文档
878
                  publish_alias=True
ff9efda0   tangwang   suggest
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
              )
              return {
                  "mode": "incremental",
                  "tenant_id": str(tenant_id),
                  "bootstrapped": True,
                  "bootstrap_result": full_result,
              }
  
          meta = self._get_meta(tenant_id)
          watermark_raw = meta.get("last_incremental_watermark") or meta.get("last_full_build_at")
          now = datetime.now(timezone.utc)
          default_since = now - timedelta(days=fallback_days)
          since = None
          if isinstance(watermark_raw, str) and watermark_raw.strip():
              try:
                  since = self._to_utc(datetime.fromisoformat(watermark_raw.replace("Z", "+00:00")))
              except Exception:
                  since = None
          if since is None:
              since = default_since
          since = since - timedelta(minutes=max(overlap_minutes, 0))
          if since < default_since:
              since = default_since
  
          deltas = self._build_incremental_deltas(
              tenant_id=tenant_id,
              index_languages=index_languages,
              primary_language=primary_language,
              since=since,
              until=now,
              min_query_len=min_query_len,
          )
  
          actions = self._build_incremental_actions(target_index=target_index, deltas=deltas)
          bulk_result = self.es_client.bulk_actions(actions)
          self.es_client.refresh(target_index)
  
          now_iso = now.isoformat()
          self._upsert_meta(
              tenant_id,
              {
                  "last_incremental_build_at": now_iso,
                  "last_incremental_watermark": now_iso,
                  "active_index": target_index,
                  "active_alias": get_suggestion_alias_name(tenant_id),
              },
          )
  
          return {
              "mode": "incremental",
              "tenant_id": str(tenant_id),
              "target_index": target_index,
              "query_window": {
                  "since": since.isoformat(),
                  "until": now_iso,
                  "overlap_minutes": int(overlap_minutes),
              },
              "updated_terms": len(deltas),
              "bulk_result": bulk_result,
          }