Blame view

suggestion/service.py 8.29 KB
ded6f29e   tangwang   补充suggestion模块
1
2
3
4
5
6
7
8
9
  """
  Online suggestion query service.
  """
  
  import logging
  import time
  from typing import Any, Dict, List, Optional
  
  from config.tenant_config_loader import get_tenant_config_loader
ff9efda0   tangwang   suggest
10
11
12
13
14
  from suggestion.builder import (
      get_suggestion_alias_name,
      get_suggestion_index_name,
      get_suggestion_legacy_index_name,
  )
ded6f29e   tangwang   补充suggestion模块
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  from utils.es_client import ESClient
  
  logger = logging.getLogger(__name__)
  
  
  class SuggestionService:
      def __init__(self, es_client: ESClient):
          self.es_client = es_client
  
      def _resolve_language(self, tenant_id: str, language: str) -> str:
          cfg = get_tenant_config_loader().get_tenant_config(tenant_id)
          index_languages = cfg.get("index_languages") or ["en", "zh"]
          primary = cfg.get("primary_language") or "en"
          lang = (language or "").strip().lower().replace("-", "_")
          if lang in {"zh_tw", "pt_br"}:
              normalized = lang
          else:
              normalized = lang.split("_")[0] if lang else ""
          if normalized in index_languages:
              return normalized
          if primary in index_languages:
              return primary
          return index_languages[0]
  
ff9efda0   tangwang   suggest
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
      def _resolve_search_target(self, tenant_id: str) -> Optional[str]:
          alias_name = get_suggestion_alias_name(tenant_id)
          if self.es_client.alias_exists(alias_name):
              return alias_name
  
          # Fallback for pre-Phase2 deployments
          legacy = get_suggestion_legacy_index_name(tenant_id)
          if self.es_client.index_exists(legacy):
              return legacy
  
          # Last fallback: current naming helper
          candidate = get_suggestion_index_name(tenant_id)
          if self.es_client.index_exists(candidate):
              return candidate
          return None
  
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
55
56
57
58
59
60
      def _completion_suggest(
          self,
          index_name: str,
          query: str,
          lang: str,
          size: int,
ff9efda0   tangwang   suggest
61
          tenant_id: str,
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
      ) -> List[Dict[str, Any]]:
          """
          Query ES completion suggester from `completion.<lang>`.
  
          Returns items in the same shape as search hits -> dicts with "text"/"lang"/"score"/"rank_score"/"sources".
          """
          field_name = f"completion.{lang}"
          body = {
              "suggest": {
                  "s": {
                      "prefix": query,
                      "completion": {
                          "field": field_name,
                          "size": size,
                          "skip_duplicates": True,
                      },
                  }
              },
              "_source": [
                  "text",
                  "lang",
                  "rank_score",
                  "sources",
                  "lang_source",
                  "lang_confidence",
                  "lang_conflict",
              ],
          }
          try:
ff9efda0   tangwang   suggest
91
              resp = self.es_client.client.search(index=index_name, body=body, routing=str(tenant_id))
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
          except Exception as e:
              # completion is an optimization path; never hard-fail the whole endpoint
              logger.warning("Completion suggest failed for index=%s field=%s: %s", index_name, field_name, e)
              return []
  
          entries = (resp.get("suggest", {}) or {}).get("s", []) or []
          if not entries:
              return []
          options = entries[0].get("options", []) or []
          out: List[Dict[str, Any]] = []
          for opt in options:
              src = opt.get("_source", {}) or {}
              out.append(
                  {
                      "text": src.get("text") or opt.get("text"),
                      "lang": src.get("lang") or lang,
                      "score": opt.get("_score", 0.0),
                      "rank_score": src.get("rank_score"),
                      "sources": src.get("sources", []),
                      "lang_source": src.get("lang_source"),
                      "lang_confidence": src.get("lang_confidence"),
                      "lang_conflict": src.get("lang_conflict", False),
                  }
              )
          return out
  
ded6f29e   tangwang   补充suggestion模块
118
119
120
121
122
123
      def search(
          self,
          tenant_id: str,
          query: str,
          language: str,
          size: int = 10,
ded6f29e   tangwang   补充suggestion模块
124
125
126
      ) -> Dict[str, Any]:
          start = time.time()
          resolved_lang = self._resolve_language(tenant_id, language)
ff9efda0   tangwang   suggest
127
128
          index_name = self._resolve_search_target(tenant_id)
          if not index_name:
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
129
130
131
132
133
134
135
136
137
138
              # On a fresh ES cluster the suggestion index might not be built yet.
              # Keep endpoint stable for frontend autocomplete: return empty list instead of 500.
              took_ms = int((time.time() - start) * 1000)
              return {
                  "query": query,
                  "language": language,
                  "resolved_language": resolved_lang,
                  "suggestions": [],
                  "took_ms": took_ms,
              }
ded6f29e   tangwang   补充suggestion模块
139
140
141
  
          sat_field = f"sat.{resolved_lang}"
          dsl = {
ff9efda0   tangwang   suggest
142
              "track_total_hits": False,
ded6f29e   tangwang   补充suggestion模块
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
169
170
171
172
173
174
175
176
177
              "query": {
                  "function_score": {
                      "query": {
                          "bool": {
                              "filter": [
                                  {"term": {"lang": resolved_lang}},
                                  {"term": {"status": 1}},
                              ],
                              "should": [
                                  {
                                      "multi_match": {
                                          "query": query,
                                          "type": "bool_prefix",
                                          "fields": [sat_field, f"{sat_field}._2gram", f"{sat_field}._3gram"],
                                      }
                                  }
                              ],
                              "minimum_should_match": 1,
                          }
                      },
                      "field_value_factor": {
                          "field": "rank_score",
                          "factor": 1.0,
                          "modifier": "log1p",
                          "missing": 0.0,
                      },
                      "boost_mode": "sum",
                      "score_mode": "sum",
                  }
              },
              "_source": [
                  "text",
                  "lang",
                  "rank_score",
                  "sources",
ded6f29e   tangwang   补充suggestion模块
178
179
180
181
182
                  "lang_source",
                  "lang_confidence",
                  "lang_conflict",
              ],
          }
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
183
          # Recall path A: bool_prefix on search_as_you_type
ff9efda0   tangwang   suggest
184
185
186
187
188
189
190
          es_resp = self.es_client.search(
              index_name=index_name,
              body=dsl,
              size=size,
              from_=0,
              routing=str(tenant_id),
          )
ded6f29e   tangwang   补充suggestion模块
191
192
          hits = es_resp.get("hits", {}).get("hits", []) or []
  
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
193
194
195
196
197
198
          # Recall path B: completion suggester (optional optimization)
          completion_items = self._completion_suggest(
              index_name=index_name,
              query=query,
              lang=resolved_lang,
              size=size,
ff9efda0   tangwang   suggest
199
              tenant_id=tenant_id,
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
200
201
          )
  
ded6f29e   tangwang   补充suggestion模块
202
          suggestions: List[Dict[str, Any]] = []
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
203
204
205
206
207
208
209
210
211
212
213
214
215
216
          seen_text_norm: set = set()
  
          def _norm_text(v: Any) -> str:
              return str(v or "").strip().lower()
  
          # Put completion results first (usually better prefix UX), then fill with sat results.
          for item in completion_items:
              text_val = item.get("text")
              norm = _norm_text(text_val)
              if not norm or norm in seen_text_norm:
                  continue
              seen_text_norm.add(norm)
              suggestions.append(dict(item))
  
ded6f29e   tangwang   补充suggestion模块
217
218
          for hit in hits:
              src = hit.get("_source", {}) or {}
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
219
220
221
222
223
              text_val = src.get("text")
              norm = _norm_text(text_val)
              if not norm or norm in seen_text_norm:
                  continue
              seen_text_norm.add(norm)
ded6f29e   tangwang   补充suggestion模块
224
              item = {
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
225
                  "text": text_val,
ded6f29e   tangwang   补充suggestion模块
226
227
228
229
230
231
232
233
                  "lang": src.get("lang"),
                  "score": hit.get("_score", 0.0),
                  "rank_score": src.get("rank_score"),
                  "sources": src.get("sources", []),
                  "lang_source": src.get("lang_source"),
                  "lang_confidence": src.get("lang_confidence"),
                  "lang_conflict": src.get("lang_conflict", False),
              }
ded6f29e   tangwang   补充suggestion模块
234
235
236
237
238
239
240
              suggestions.append(item)
  
          took_ms = int((time.time() - start) * 1000)
          return {
              "query": query,
              "language": language,
              "resolved_language": resolved_lang,
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
241
              "suggestions": suggestions[:size],
ded6f29e   tangwang   补充suggestion模块
242
243
              "took_ms": took_ms,
          }