Blame view

suggestion/builder.py 32.1 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
ded6f29e   tangwang   补充suggestion模块
23
  from suggestion.mapping import build_suggestion_mapping
ff9efda0   tangwang   suggest
24
  from utils.es_client import ESClient
ded6f29e   tangwang   补充suggestion模块
25
26
27
28
  
  logger = logging.getLogger(__name__)
  
  
ff9efda0   tangwang   suggest
29
  def _index_prefix() -> str:
86d8358b   tangwang   config optimize
30
      return get_app_config().runtime.index_namespace or ""
ff9efda0   tangwang   suggest
31
32
  
  
ff9efda0   tangwang   suggest
33
  def get_suggestion_alias_name(tenant_id: str) -> str:
5b8f58c0   tangwang   sugg
34
      """Read alias for suggestion index (single source of truth)."""
ff9efda0   tangwang   suggest
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
      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模块
52
53
54
55
56
57
58
59
60
61
62
63
64
  @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)
      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模块
65
  
ff9efda0   tangwang   suggest
66
      def add_product(self, source: str, spu_id: str) -> None:
ded6f29e   tangwang   补充suggestion模块
67
68
69
70
71
          self.sources.add(source)
          if source == "title":
              self.title_spu_ids.add(spu_id)
          elif source == "qanchor":
              self.qanchor_spu_ids.add(spu_id)
ded6f29e   tangwang   补充suggestion模块
72
73
74
75
76
77
78
79
  
      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
80
81
82
83
84
85
86
87
88
89
90
91
92
  @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模块
93
  class SuggestionIndexBuilder:
ff9efda0   tangwang   suggest
94
      """Build and update suggestion index."""
ded6f29e   tangwang   补充suggestion模块
95
96
97
98
99
100
  
      def __init__(self, es_client: ESClient, db_engine: Any):
          self.es_client = es_client
          self.db_engine = db_engine
  
      @staticmethod
ff9efda0   tangwang   suggest
101
102
103
104
105
106
107
108
109
110
      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模块
111
      def _normalize_text(value: str) -> str:
ff9efda0   tangwang   suggest
112
          text_value = unicodedata.normalize("NFKC", (value or "")).strip().lower()
ded6f29e   tangwang   补充suggestion模块
113
114
115
116
          text_value = re.sub(r"\s+", " ", text_value)
          return text_value
  
      @staticmethod
daf66a51   tangwang   已完成接口级压测脚本,覆盖搜索、s...
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
      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模块
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
      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 []
          parts = re.split(r"[,;|/\n\t]+", raw)
          out = [p.strip() for p in parts if p and p.strip()]
          if not out:
              return [raw]
          return out
  
      @staticmethod
      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模块
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
          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
  
      @staticmethod
      def _detect_script_language(query: str) -> Tuple[Optional[str], float, str]:
ded6f29e   tangwang   补充suggestion模块
192
193
          if re.search(r"[\u4e00-\u9fff]", query):
              return "zh", 0.98, "script"
ded6f29e   tangwang   补充suggestion模块
194
195
          if re.search(r"[\u0600-\u06FF]", query):
              return "ar", 0.98, "script"
ded6f29e   tangwang   补充suggestion模块
196
197
          if re.search(r"[\u0400-\u04FF]", query):
              return "ru", 0.95, "script"
ded6f29e   tangwang   补充suggestion模块
198
199
          if re.search(r"[\u0370-\u03FF]", query):
              return "el", 0.95, "script"
ded6f29e   tangwang   补充suggestion模块
200
201
202
203
204
205
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
231
232
233
234
          if re.search(r"[a-zA-Z]", query):
              return "en", 0.55, "model"
          return None, 0.0, "default"
  
      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
  
          detected_lang, conf, source = self._detect_script_language(query)
          if detected_lang and (not langs_set or detected_lang in langs_set):
              return detected_lang, conf, source, conflict
  
          return primary, 0.3, "default", conflict
  
      @staticmethod
ff9efda0   tangwang   suggest
235
      def _compute_rank_score(query_count_30d: int, query_count_7d: int, qanchor_doc_count: int, title_doc_count: int) -> float:
ded6f29e   tangwang   补充suggestion模块
236
          return (
ff9efda0   tangwang   suggest
237
238
239
240
              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))
              + 0.6 * math.log1p(max(title_doc_count, 0))
ded6f29e   tangwang   补充suggestion模块
241
242
          )
  
ff9efda0   tangwang   suggest
243
244
245
246
247
248
249
250
251
252
253
      @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),
          )
  
      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模块
254
255
256
          from indexer.mapping_generator import get_tenant_index_name
  
          index_name = get_tenant_index_name(tenant_id)
ded6f29e   tangwang   补充suggestion模块
257
258
259
260
261
          search_after: Optional[List[Any]] = None
  
          while True:
              body: Dict[str, Any] = {
                  "size": batch_size,
daf66a51   tangwang   已完成接口级压测脚本,覆盖搜索、s...
262
                  "_source": ["id", "spu_id", "title", "qanchors"],
daf66a51   tangwang   已完成接口级压测脚本,覆盖搜索、s...
263
264
                  "sort": [
                      {"spu_id": {"order": "asc", "missing": "_last"}},
daf66a51   tangwang   已完成接口级压测脚本,覆盖搜索、s...
265
                  ],
ded6f29e   tangwang   补充suggestion模块
266
267
268
269
270
271
272
273
274
                  "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
275
276
              for hit in hits:
                  yield hit
ded6f29e   tangwang   补充suggestion模块
277
278
279
              search_after = hits[-1].get("sort")
              if len(hits) < batch_size:
                  break
ded6f29e   tangwang   补充suggestion模块
280
  
ff9efda0   tangwang   suggest
281
      def _iter_query_log_rows(
ded6f29e   tangwang   补充suggestion模块
282
283
          self,
          tenant_id: str,
ff9efda0   tangwang   suggest
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
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
          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模块
401
  
ff9efda0   tangwang   suggest
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
          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
418
          """Resolve active suggestion index for incremental updates (alias only)."""
ff9efda0   tangwang   suggest
419
420
421
422
423
          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
424
425
426
427
428
429
430
431
432
433
434
          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模块
435
436
437
          key_to_candidate: Dict[Tuple[str, str], SuggestionCandidate] = {}
  
          # Step 1: product title/qanchors
ff9efda0   tangwang   suggest
438
          for hit in self._iter_products(tenant_id, batch_size=batch_size):
ded6f29e   tangwang   补充suggestion模块
439
              src = hit.get("_source", {}) or {}
daf66a51   tangwang   已完成接口级压测脚本,覆盖搜索、s...
440
441
              product_id = str(src.get("spu_id") or src.get("id") or hit.get("_id") or "")
              if not product_id:
ded6f29e   tangwang   补充suggestion模块
442
443
444
                  continue
              title_obj = src.get("title") or {}
              qanchor_obj = src.get("qanchors") or {}
ded6f29e   tangwang   补充suggestion模块
445
446
447
448
  
              for lang in index_languages:
                  title = ""
                  if isinstance(title_obj, dict):
daf66a51   tangwang   已完成接口级压测脚本,覆盖搜索、s...
449
                      title = self._prepare_title_for_suggest(title_obj.get(lang) or "")
ded6f29e   tangwang   补充suggestion模块
450
451
452
453
454
455
456
457
                  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...
458
                          c.add_product("title", spu_id=product_id)
ded6f29e   tangwang   补充suggestion模块
459
460
461
462
463
464
465
466
467
468
469
470
471
  
                  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...
472
                      c.add_product("qanchor", spu_id=product_id)
ded6f29e   tangwang   补充suggestion模块
473
474
475
  
          # Step 2: query logs
          now = datetime.now(timezone.utc)
ff9efda0   tangwang   suggest
476
          since = now - timedelta(days=days)
ded6f29e   tangwang   补充suggestion模块
477
          since_7d = now - timedelta(days=7)
ded6f29e   tangwang   补充suggestion模块
478
  
ff9efda0   tangwang   suggest
479
          for row in self._iter_query_log_rows(tenant_id=tenant_id, since=since, until=now):
ded6f29e   tangwang   补充suggestion模块
480
481
482
              q = str(row.query or "").strip()
              if len(q) < min_query_len:
                  continue
ff9efda0   tangwang   suggest
483
  
ded6f29e   tangwang   补充suggestion模块
484
485
486
487
488
489
490
491
492
493
              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
494
  
ded6f29e   tangwang   补充suggestion模块
495
496
497
498
499
              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
500
  
ded6f29e   tangwang   补充suggestion模块
501
502
503
504
              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
505
506
              created_at = self._to_utc(getattr(row, "create_time", None))
              is_7d = bool(created_at and created_at >= since_7d)
ded6f29e   tangwang   补充suggestion模块
507
508
              c.add_query_log(is_7d=is_7d)
  
ff9efda0   tangwang   suggest
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
          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),
              "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
540
541
542
543
          batch_size: int = 500,
          min_query_len: int = 1,
          publish_alias: bool = True,
          keep_versions: int = 2,
ff9efda0   tangwang   suggest
544
545
546
547
548
549
550
551
552
553
554
555
556
      ) -> 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
557
558
          # 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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
  
          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模块
576
          now_iso = datetime.now(timezone.utc).isoformat()
ff9efda0   tangwang   suggest
577
          docs = [self._candidate_to_doc(tenant_id, c, now_iso) for c in key_to_candidate.values()]
ded6f29e   tangwang   补充suggestion模块
578
579
  
          if docs:
ff9efda0   tangwang   suggest
580
              bulk_result = self.es_client.bulk_index(index_name=index_name, docs=docs)
ded6f29e   tangwang   补充suggestion模块
581
582
              self.es_client.refresh(index_name)
          else:
ff9efda0   tangwang   suggest
583
584
585
              bulk_result = {"success": 0, "failed": 0, "errors": []}
  
          alias_publish: Optional[Dict[str, Any]] = None
5b8f58c0   tangwang   sugg
586
          if publish_alias:
ff9efda0   tangwang   suggest
587
588
589
590
591
592
593
594
595
596
597
              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
598
          if publish_alias:
ff9efda0   tangwang   suggest
599
600
601
              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模块
602
603
  
          return {
ff9efda0   tangwang   suggest
604
              "mode": "full",
ded6f29e   tangwang   补充suggestion模块
605
606
              "tenant_id": str(tenant_id),
              "index_name": index_name,
ff9efda0   tangwang   suggest
607
608
              "alias_published": bool(alias_publish),
              "alias_publish": alias_publish,
ded6f29e   tangwang   补充suggestion模块
609
610
              "total_candidates": len(key_to_candidate),
              "indexed_docs": len(docs),
ff9efda0   tangwang   suggest
611
              "bulk_result": bulk_result,
ded6f29e   tangwang   补充suggestion模块
612
613
          }
  
ff9efda0   tangwang   suggest
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
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
663
664
665
666
667
668
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
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
      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,
          )
          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,
              "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; }
  
              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;
  
              double score = 1.8 * Math.log(1 + q30)
                           + 1.2 * Math.log(1 + q7)
                           + 1.0 * Math.log(1 + qa)
                           + 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 索引文档
818
                  publish_alias=True
ff9efda0   tangwang   suggest
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
878
              )
              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,
          }