Blame view

query/query_parser.py 23.2 KB
be52af70   tangwang   first commit
1
2
3
4
5
6
  """
  Query parser - main module for query processing.
  
  Handles query rewriting, translation, and embedding generation.
  """
  
3ec5bfe6   tangwang   1. get_translatio...
7
  from typing import Dict, List, Optional, Any, Union
be52af70   tangwang   first commit
8
  import numpy as np
325eec03   tangwang   1. 日志、配置基础设施,使用优化
9
  import logging
7bc756c5   tangwang   优化 ES 查询构建
10
  import re
3ec5bfe6   tangwang   1. get_translatio...
11
  from concurrent.futures import Future, ThreadPoolExecutor, as_completed
be52af70   tangwang   first commit
12
  
07cf5a93   tangwang   START_EMBEDDING=...
13
  from embeddings.text_encoder import TextEmbeddingEncoder
9f96d6f3   tangwang   短query不用语义搜索
14
  from config import SearchConfig
be52af70   tangwang   first commit
15
  from .language_detector import LanguageDetector
42e3aea6   tangwang   tidy
16
  from providers import create_translation_provider
be52af70   tangwang   first commit
17
18
  from .query_rewriter import QueryRewriter, QueryNormalizer
  
325eec03   tangwang   1. 日志、配置基础设施,使用优化
19
20
  logger = logging.getLogger(__name__)
  
484adbfe   tangwang   adapt ubuntu; con...
21
22
23
24
  try:
      import hanlp  # type: ignore
  except Exception:  # pragma: no cover
      hanlp = None
be52af70   tangwang   first commit
25
26
27
28
29
30
31
  
  class ParsedQuery:
      """Container for parsed query results."""
  
      def __init__(
          self,
          original_query: str,
3a5fda00   tangwang   1. ES字段 skus的 ima...
32
          query_normalized: str,
be52af70   tangwang   first commit
33
          rewritten_query: Optional[str] = None,
a5a6bab8   tangwang   多语言查询优化
34
          detected_language: Optional[str] = None,
be52af70   tangwang   first commit
35
36
          translations: Dict[str, str] = None,
          query_vector: Optional[np.ndarray] = None,
7bc756c5   tangwang   优化 ES 查询构建
37
38
39
          domain: str = "default",
          keywords: str = "",
          token_count: int = 0,
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
40
41
42
43
44
          query_tokens: Optional[List[str]] = None,
          query_text_by_lang: Optional[Dict[str, str]] = None,
          search_langs: Optional[List[str]] = None,
          index_languages: Optional[List[str]] = None,
          source_in_index_languages: bool = True,
be52af70   tangwang   first commit
45
46
      ):
          self.original_query = original_query
3a5fda00   tangwang   1. ES字段 skus的 ima...
47
48
          self.query_normalized = query_normalized
          self.rewritten_query = rewritten_query or query_normalized
be52af70   tangwang   first commit
49
50
51
52
          self.detected_language = detected_language
          self.translations = translations or {}
          self.query_vector = query_vector
          self.domain = domain
7bc756c5   tangwang   优化 ES 查询构建
53
54
55
          # Query analysis fields
          self.keywords = keywords
          self.token_count = token_count
ea118f2b   tangwang   build_query:根据 qu...
56
          self.query_tokens = query_tokens or []
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
57
58
59
60
          self.query_text_by_lang = query_text_by_lang or {}
          self.search_langs = search_langs or []
          self.index_languages = index_languages or []
          self.source_in_index_languages = bool(source_in_index_languages)
be52af70   tangwang   first commit
61
62
63
64
65
  
      def to_dict(self) -> Dict[str, Any]:
          """Convert to dictionary representation."""
          result = {
              "original_query": self.original_query,
3a5fda00   tangwang   1. ES字段 skus的 ima...
66
              "query_normalized": self.query_normalized,
be52af70   tangwang   first commit
67
68
69
              "rewritten_query": self.rewritten_query,
              "detected_language": self.detected_language,
              "translations": self.translations,
038e4e2f   tangwang   refactor(i18n): t...
70
              "domain": self.domain
be52af70   tangwang   first commit
71
          }
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
72
73
74
75
          result["query_text_by_lang"] = self.query_text_by_lang
          result["search_langs"] = self.search_langs
          result["index_languages"] = self.index_languages
          result["source_in_index_languages"] = self.source_in_index_languages
be52af70   tangwang   first commit
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
          return result
  
  
  class QueryParser:
      """
      Main query parser that processes queries through multiple stages:
      1. Normalization
      2. Query rewriting (brand/category mappings, synonyms)
      3. Language detection
      4. Translation to target languages
      5. Text embedding generation (for semantic search)
      """
  
      def __init__(
          self,
9f96d6f3   tangwang   短query不用语义搜索
91
          config: SearchConfig,
950a640e   tangwang   embeddings
92
          text_encoder: Optional[TextEmbeddingEncoder] = None,
42e3aea6   tangwang   tidy
93
          translator: Optional[Any] = None
be52af70   tangwang   first commit
94
95
96
97
98
      ):
          """
          Initialize query parser.
  
          Args:
9f96d6f3   tangwang   短query不用语义搜索
99
              config: SearchConfig instance
26b910bd   tangwang   refactor service ...
100
101
              text_encoder: Text embedding encoder (initialized at startup if not provided)
              translator: Translator instance (initialized at startup if not provided)
be52af70   tangwang   first commit
102
          """
9f96d6f3   tangwang   短query不用语义搜索
103
          self.config = config
be52af70   tangwang   first commit
104
105
106
107
108
109
          self._text_encoder = text_encoder
          self._translator = translator
  
          # Initialize components
          self.normalizer = QueryNormalizer()
          self.language_detector = LanguageDetector()
9f96d6f3   tangwang   短query不用语义搜索
110
          self.rewriter = QueryRewriter(config.query_config.rewrite_dictionary)
7bc756c5   tangwang   优化 ES 查询构建
111
          
484adbfe   tangwang   adapt ubuntu; con...
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
          # Optional HanLP components (heavy). If unavailable, fall back to a lightweight tokenizer.
          self._tok = None
          self._pos_tag = None
          if hanlp is not None:
              try:
                  logger.info("Initializing HanLP components...")
                  self._tok = hanlp.load(hanlp.pretrained.tok.CTB9_TOK_ELECTRA_BASE_CRF)
                  self._tok.config.output_spans = True
                  self._pos_tag = hanlp.load(hanlp.pretrained.pos.CTB9_POS_ELECTRA_SMALL)
                  logger.info("HanLP components initialized")
              except Exception as e:
                  logger.warning(f"HanLP init failed, falling back to simple tokenizer: {e}")
                  self._tok = None
                  self._pos_tag = None
          else:
              logger.info("HanLP not installed; using simple tokenizer")
be52af70   tangwang   first commit
128
  
26b910bd   tangwang   refactor service ...
129
130
131
132
133
134
135
136
137
138
          # Eager initialization (startup-time failure visibility, no lazy init in request path)
          if self.config.query_config.enable_text_embedding and self._text_encoder is None:
              logger.info("Initializing text encoder at QueryParser construction...")
              self._text_encoder = TextEmbeddingEncoder()
          if self._translator is None:
              from config.services_config import get_translation_config
              cfg = get_translation_config()
              logger.info("Initializing translator at QueryParser construction (provider=%s)...", cfg.provider)
              self._translator = create_translation_provider(self.config.query_config)
  
be52af70   tangwang   first commit
139
      @property
950a640e   tangwang   embeddings
140
      def text_encoder(self) -> TextEmbeddingEncoder:
26b910bd   tangwang   refactor service ...
141
          """Return pre-initialized text encoder."""
be52af70   tangwang   first commit
142
143
144
          return self._text_encoder
  
      @property
42e3aea6   tangwang   tidy
145
      def translator(self) -> Any:
26b910bd   tangwang   refactor service ...
146
          """Return pre-initialized translator."""
be52af70   tangwang   first commit
147
          return self._translator
484adbfe   tangwang   adapt ubuntu; con...
148
149
150
151
152
153
154
155
156
157
158
159
  
      def _simple_tokenize(self, text: str) -> List[str]:
          """
          Lightweight tokenizer fallback.
  
          - Groups consecutive CJK chars as a token
          - Groups consecutive latin/digits/underscore/dash as a token
          """
          if not text:
              return []
          pattern = re.compile(r"[\u4e00-\u9fff]+|[A-Za-z0-9_]+(?:-[A-Za-z0-9_]+)*")
          return pattern.findall(text)
7bc756c5   tangwang   优化 ES 查询构建
160
161
162
      
      def _extract_keywords(self, query: str) -> str:
          """Extract keywords (nouns with length > 1) from query."""
484adbfe   tangwang   adapt ubuntu; con...
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
          if self._tok is not None and self._pos_tag is not None:
              tok_result = self._tok(query)
              if not tok_result:
                  return ""
              words = [x[0] for x in tok_result]
              pos_tags = self._pos_tag(words)
              keywords = []
              for word, pos in zip(words, pos_tags):
                  if len(word) > 1 and isinstance(pos, str) and pos.startswith("N"):
                      keywords.append(word)
              return " ".join(keywords)
  
          # Fallback: treat tokens with length > 1 as "keywords"
          tokens = self._simple_tokenize(query)
          keywords = [t for t in tokens if len(t) > 1]
7bc756c5   tangwang   优化 ES 查询构建
178
179
180
          return " ".join(keywords)
      
      def _get_token_count(self, query: str) -> int:
484adbfe   tangwang   adapt ubuntu; con...
181
182
183
184
185
          """Get token count (HanLP if available, otherwise simple)."""
          if self._tok is not None:
              tok_result = self._tok(query)
              return len(tok_result) if tok_result else 0
          return len(self._simple_tokenize(query))
ea118f2b   tangwang   build_query:根据 qu...
186
187
  
      def _get_query_tokens(self, query: str) -> List[str]:
484adbfe   tangwang   adapt ubuntu; con...
188
189
190
191
192
          """Get token list (HanLP if available, otherwise simple)."""
          if self._tok is not None:
              tok_result = self._tok(query)
              return [x[0] for x in tok_result] if tok_result else []
          return self._simple_tokenize(query)
be52af70   tangwang   first commit
193
  
345d960b   tangwang   1. 删除全局 enable_tr...
194
195
196
197
198
199
200
      def parse(
          self,
          query: str,
          tenant_id: Optional[str] = None,
          generate_vector: bool = True,
          context: Optional[Any] = None
      ) -> ParsedQuery:
be52af70   tangwang   first commit
201
202
203
204
205
206
          """
          Parse query through all processing stages.
  
          Args:
              query: Raw query string
              generate_vector: Whether to generate query embedding
16c42787   tangwang   feat: implement r...
207
              context: Optional request context for tracking and logging
be52af70   tangwang   first commit
208
209
210
211
  
          Returns:
              ParsedQuery object with all processing results
          """
16c42787   tangwang   feat: implement r...
212
          # Initialize logger if context provided
950a640e   tangwang   embeddings
213
214
215
          active_logger = context.logger if context else logger
          if context and hasattr(context, "logger"):
              context.logger.info(
70dab99f   tangwang   add logs
216
                  f"Starting query parsing | Original query: '{query}' | Generate vector: {generate_vector}",
16c42787   tangwang   feat: implement r...
217
218
219
                  extra={'reqid': context.reqid, 'uid': context.uid}
              )
  
16c42787   tangwang   feat: implement r...
220
          def log_info(msg):
325eec03   tangwang   1. 日志、配置基础设施,使用优化
221
222
              if context and hasattr(context, 'logger'):
                  context.logger.info(msg, extra={'reqid': context.reqid, 'uid': context.uid})
16c42787   tangwang   feat: implement r...
223
              else:
950a640e   tangwang   embeddings
224
                  active_logger.info(msg)
16c42787   tangwang   feat: implement r...
225
226
  
          def log_debug(msg):
325eec03   tangwang   1. 日志、配置基础设施,使用优化
227
228
              if context and hasattr(context, 'logger'):
                  context.logger.debug(msg, extra={'reqid': context.reqid, 'uid': context.uid})
16c42787   tangwang   feat: implement r...
229
              else:
950a640e   tangwang   embeddings
230
                  active_logger.debug(msg)
be52af70   tangwang   first commit
231
232
233
  
          # Stage 1: Normalize
          normalized = self.normalizer.normalize(query)
70dab99f   tangwang   add logs
234
          log_debug(f"Normalization completed | '{query}' -> '{normalized}'")
16c42787   tangwang   feat: implement r...
235
          if context:
3a5fda00   tangwang   1. ES字段 skus的 ima...
236
              context.store_intermediate_result('query_normalized', normalized)
be52af70   tangwang   first commit
237
238
239
  
          # Extract domain if present (e.g., "brand:Nike" -> domain="brand", query="Nike")
          domain, query_text = self.normalizer.extract_domain_query(normalized)
70dab99f   tangwang   add logs
240
          log_debug(f"Domain extraction | Domain: '{domain}', Query: '{query_text}'")
16c42787   tangwang   feat: implement r...
241
242
243
          if context:
              context.store_intermediate_result('extracted_domain', domain)
              context.store_intermediate_result('domain_query', query_text)
be52af70   tangwang   first commit
244
245
246
  
          # Stage 2: Query rewriting
          rewritten = None
9f96d6f3   tangwang   短query不用语义搜索
247
          if self.config.query_config.rewrite_dictionary:  # Enable rewrite if dictionary exists
be52af70   tangwang   first commit
248
249
              rewritten = self.rewriter.rewrite(query_text)
              if rewritten != query_text:
70dab99f   tangwang   add logs
250
                  log_info(f"Query rewritten | '{query_text}' -> '{rewritten}'")
be52af70   tangwang   first commit
251
                  query_text = rewritten
16c42787   tangwang   feat: implement r...
252
253
                  if context:
                      context.store_intermediate_result('rewritten_query', rewritten)
70dab99f   tangwang   add logs
254
                      context.add_warning(f"Query was rewritten: {query_text}")
be52af70   tangwang   first commit
255
256
257
  
          # Stage 3: Language detection
          detected_lang = self.language_detector.detect(query_text)
a5a6bab8   tangwang   多语言查询优化
258
259
260
          # Use default language if detection failed (None or "unknown")
          if not detected_lang or detected_lang == "unknown":
              detected_lang = self.config.query_config.default_language
70dab99f   tangwang   add logs
261
          log_info(f"Language detection | Detected language: {detected_lang}")
16c42787   tangwang   feat: implement r...
262
263
          if context:
              context.store_intermediate_result('detected_language', detected_lang)
be52af70   tangwang   first commit
264
  
3ec5bfe6   tangwang   1. get_translatio...
265
          # Stage 4: Translation (with async support and conditional waiting)
be52af70   tangwang   first commit
266
          translations = {}
3ec5bfe6   tangwang   1. get_translatio...
267
          translation_futures = {}
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
268
          index_langs = ["en", "zh"]
345d960b   tangwang   1. 删除全局 enable_tr...
269
          try:
038e4e2f   tangwang   refactor(i18n): t...
270
              # 根据租户配置的 index_languages 决定翻译目标语言
345d960b   tangwang   1. 删除全局 enable_tr...
271
272
273
              from config.tenant_config_loader import get_tenant_config_loader
              tenant_loader = get_tenant_config_loader()
              tenant_cfg = tenant_loader.get_tenant_config(tenant_id or "default")
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
274
275
276
277
278
279
280
281
282
              raw_index_langs = tenant_cfg.get("index_languages") or ["en", "zh"]
              index_langs = []
              seen_langs = set()
              for lang in raw_index_langs:
                  norm_lang = str(lang or "").strip().lower()
                  if not norm_lang or norm_lang in seen_langs:
                      continue
                  seen_langs.add(norm_lang)
                  index_langs.append(norm_lang)
345d960b   tangwang   1. 删除全局 enable_tr...
283
  
038e4e2f   tangwang   refactor(i18n): t...
284
              target_langs_for_translation = [lang for lang in index_langs if lang != detected_lang]
345d960b   tangwang   1. 删除全局 enable_tr...
285
  
345d960b   tangwang   1. 删除全局 enable_tr...
286
              if target_langs_for_translation:
038e4e2f   tangwang   refactor(i18n): t...
287
                  target_langs = target_langs_for_translation
16c42787   tangwang   feat: implement r...
288
289
  
                  if target_langs:
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
290
                      # Use e-commerce context for better disambiguation
0064e946   tangwang   feat: 增量索引服务、租户配置...
291
292
                      translation_context = self.config.query_config.translation_context
                      # For query translation, we use a general prompt (not language-specific)
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
293
294
295
296
297
298
                      query_prompt = (
                          self.config.query_config.translation_prompts.get(f"query_{detected_lang}")
                          or self.config.query_config.translation_prompts.get("query_en")
                          or self.config.query_config.translation_prompts.get("default_en")
                          or self.config.query_config.translation_prompts.get("default_zh")
                      )
3ec5bfe6   tangwang   1. get_translatio...
299
300
                      
                      # Determine if we need to wait for translation results
038e4e2f   tangwang   refactor(i18n): t...
301
302
                      # If detected_lang is not in index_languages, we must wait for translation
                      need_wait_translation = detected_lang not in index_langs
3ec5bfe6   tangwang   1. get_translatio...
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
                      
                      if need_wait_translation:
                          # Use async method that returns Futures, so we can wait for results
                          translation_results = self.translator.translate_multi_async(
                              query_text,
                              target_langs,
                              source_lang=detected_lang,
                              context=translation_context,
                              prompt=query_prompt
                          )
                          # Separate cached results and futures
                          for lang, result in translation_results.items():
                              if isinstance(result, Future):
                                  translation_futures[lang] = result
                              else:
                                  translations[lang] = result
                      else:
                          # Use async mode: returns cached translations immediately, missing ones translated in background
                          translations = self.translator.translate_multi(
                              query_text,
                              target_langs,
                              source_lang=detected_lang,
                              context=translation_context,
                              async_mode=True,
                              prompt=query_prompt
                          )
                          # Filter out None values (missing translations that are being processed async)
                          translations = {k: v for k, v in translations.items() if v is not None}
6e0e310c   tangwang   1. Translator 类增强
331
332
                      
                      if translations:
70dab99f   tangwang   add logs
333
                          log_info(f"Translation completed (cache hit) | Query text: '{query_text}' | Results: {translations}")
3ec5bfe6   tangwang   1. get_translatio...
334
                      if translation_futures:
70dab99f   tangwang   add logs
335
                          log_debug(f"Translation in progress, waiting for results... | Query text: '{query_text}' | Languages: {list(translation_futures.keys())}")
6e0e310c   tangwang   1. Translator 类增强
336
                      
16c42787   tangwang   feat: implement r...
337
338
339
340
341
342
                      if context:
                          context.store_intermediate_result('translations', translations)
                          for lang, translation in translations.items():
                              if translation:
                                  context.store_intermediate_result(f'translation_{lang}', translation)
  
345d960b   tangwang   1. 删除全局 enable_tr...
343
          except Exception as e:
70dab99f   tangwang   add logs
344
              error_msg = f"Translation failed | Error: {str(e)}"
345d960b   tangwang   1. 删除全局 enable_tr...
345
346
347
              log_info(error_msg)
              if context:
                  context.add_warning(error_msg)
be52af70   tangwang   first commit
348
  
ea118f2b   tangwang   build_query:根据 qu...
349
          # Stage 5: Query analysis (keywords, token count, query_tokens)
7bc756c5   tangwang   优化 ES 查询构建
350
          keywords = self._extract_keywords(query_text)
ea118f2b   tangwang   build_query:根据 qu...
351
352
          query_tokens = self._get_query_tokens(query_text)
          token_count = len(query_tokens)
7bc756c5   tangwang   优化 ES 查询构建
353
          
70dab99f   tangwang   add logs
354
          log_debug(f"Query analysis | Keywords: {keywords} | Token count: {token_count} | "
ea118f2b   tangwang   build_query:根据 qu...
355
                   f"Query tokens: {query_tokens}")
7bc756c5   tangwang   优化 ES 查询构建
356
357
358
          if context:
              context.store_intermediate_result('keywords', keywords)
              context.store_intermediate_result('token_count', token_count)
ea118f2b   tangwang   build_query:根据 qu...
359
              context.store_intermediate_result('query_tokens', query_tokens)
7bc756c5   tangwang   优化 ES 查询构建
360
          
3ec5bfe6   tangwang   1. get_translatio...
361
          # Stage 6: Text embedding (only for non-short queries) - async execution
be52af70   tangwang   first commit
362
          query_vector = None
3ec5bfe6   tangwang   1. get_translatio...
363
          embedding_future = None
7bc756c5   tangwang   优化 ES 查询构建
364
365
          should_generate_embedding = (
              generate_vector and
9f96d6f3   tangwang   短query不用语义搜索
366
              self.config.query_config.enable_text_embedding and
d90e7428   tangwang   补充重排
367
              domain == "default"
7bc756c5   tangwang   优化 ES 查询构建
368
369
          )
          
3ec5bfe6   tangwang   1. get_translatio...
370
          encoding_executor = None
7bc756c5   tangwang   优化 ES 查询构建
371
372
          if should_generate_embedding:
              try:
26b910bd   tangwang   refactor service ...
373
374
                  if self.text_encoder is None:
                      raise RuntimeError("Text embedding is enabled but text encoder is not initialized")
70dab99f   tangwang   add logs
375
                  log_debug("Starting query vector generation (async)")
3ec5bfe6   tangwang   1. get_translatio...
376
377
                  # Submit encoding task to thread pool for async execution
                  encoding_executor = ThreadPoolExecutor(max_workers=1)
b2e50710   tangwang   BgeEncoder.encode...
378
379
380
381
382
383
                  def _encode_query_vector() -> Optional[np.ndarray]:
                      arr = self.text_encoder.encode([query_text])
                      if arr is None or len(arr) == 0:
                          return None
                      vec = arr[0]
                      return vec if isinstance(vec, np.ndarray) else None
3ec5bfe6   tangwang   1. get_translatio...
384
                  embedding_future = encoding_executor.submit(
b2e50710   tangwang   BgeEncoder.encode...
385
                      _encode_query_vector
3ec5bfe6   tangwang   1. get_translatio...
386
                  )
7bc756c5   tangwang   优化 ES 查询构建
387
              except Exception as e:
70dab99f   tangwang   add logs
388
                  error_msg = f"Query vector generation task submission failed | Error: {str(e)}"
7bc756c5   tangwang   优化 ES 查询构建
389
390
391
                  log_info(error_msg)
                  if context:
                      context.add_warning(error_msg)
3ec5bfe6   tangwang   1. get_translatio...
392
393
394
395
396
                  encoding_executor = None
                  embedding_future = None
          
          # Wait for all async tasks to complete (translation and embedding)
          if translation_futures or embedding_future:
70dab99f   tangwang   add logs
397
              log_debug("Waiting for async tasks to complete...")
3ec5bfe6   tangwang   1. get_translatio...
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
              
              # Collect all futures with their identifiers
              all_futures = []
              future_to_lang = {}
              for lang, future in translation_futures.items():
                  all_futures.append(future)
                  future_to_lang[future] = ('translation', lang)
              
              if embedding_future:
                  all_futures.append(embedding_future)
                  future_to_lang[embedding_future] = ('embedding', None)
              
              # Wait for all futures to complete
              for future in as_completed(all_futures):
                  task_type, lang = future_to_lang[future]
                  try:
                      result = future.result()
                      if task_type == 'translation':
                          if result:
                              translations[lang] = result
70dab99f   tangwang   add logs
418
                              log_info(f"Translation completed | Query text: '{query_text}' | Target language: {lang} | Translation result: '{result}'")
3ec5bfe6   tangwang   1. get_translatio...
419
420
421
422
                              if context:
                                  context.store_intermediate_result(f'translation_{lang}', result)
                      elif task_type == 'embedding':
                          query_vector = result
b2e50710   tangwang   BgeEncoder.encode...
423
                          if query_vector is not None:
70dab99f   tangwang   add logs
424
                              log_debug(f"Query vector generation completed | Shape: {query_vector.shape}")
b2e50710   tangwang   BgeEncoder.encode...
425
426
427
                              if context:
                                  context.store_intermediate_result('query_vector_shape', query_vector.shape)
                          else:
70dab99f   tangwang   add logs
428
                              log_info("Query vector generation completed but result is None, will process without vector")
3ec5bfe6   tangwang   1. get_translatio...
429
430
                  except Exception as e:
                      if task_type == 'translation':
70dab99f   tangwang   add logs
431
                          error_msg = f"Translation failed | Language: {lang} | Error: {str(e)}"
3ec5bfe6   tangwang   1. get_translatio...
432
                      else:
70dab99f   tangwang   add logs
433
                          error_msg = f"Query vector generation failed | Error: {str(e)}"
3ec5bfe6   tangwang   1. get_translatio...
434
435
436
437
438
439
440
441
442
443
444
                      log_info(error_msg)
                      if context:
                          context.add_warning(error_msg)
              
              # Clean up encoding executor
              if encoding_executor:
                  encoding_executor.shutdown(wait=False)
              
              # Update translations in context after all are complete
              if translations and context:
                  context.store_intermediate_result('translations', translations)
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
          
          # Build language-scoped query plan: source language + available translations
          query_text_by_lang: Dict[str, str] = {}
          if query_text:
              query_text_by_lang[detected_lang] = query_text
          for lang, translated_text in (translations or {}).items():
              if translated_text and str(translated_text).strip():
                  query_text_by_lang[str(lang).strip().lower()] = str(translated_text)
          
          source_in_index_languages = detected_lang in index_langs
          ordered_search_langs: List[str] = []
          seen_order = set()
          if detected_lang in query_text_by_lang:
              ordered_search_langs.append(detected_lang)
              seen_order.add(detected_lang)
          for lang in index_langs:
              if lang in query_text_by_lang and lang not in seen_order:
                  ordered_search_langs.append(lang)
                  seen_order.add(lang)
          for lang in query_text_by_lang.keys():
              if lang not in seen_order:
                  ordered_search_langs.append(lang)
                  seen_order.add(lang)
          
          if context:
              context.store_intermediate_result("search_langs", ordered_search_langs)
              context.store_intermediate_result("query_text_by_lang", query_text_by_lang)
be52af70   tangwang   first commit
472
473
474
475
  
          # Build result
          result = ParsedQuery(
              original_query=query,
3a5fda00   tangwang   1. ES字段 skus的 ima...
476
              query_normalized=normalized,
be52af70   tangwang   first commit
477
478
479
480
              rewritten_query=rewritten,
              detected_language=detected_lang,
              translations=translations,
              query_vector=query_vector,
7bc756c5   tangwang   优化 ES 查询构建
481
482
483
              domain=domain,
              keywords=keywords,
              token_count=token_count,
bd96cead   tangwang   1. 动态多语言字段与统一策略配置
484
485
486
487
488
              query_tokens=query_tokens,
              query_text_by_lang=query_text_by_lang,
              search_langs=ordered_search_langs,
              index_languages=index_langs,
              source_in_index_languages=source_in_index_languages,
be52af70   tangwang   first commit
489
490
          )
  
325eec03   tangwang   1. 日志、配置基础设施,使用优化
491
492
          if context and hasattr(context, 'logger'):
              context.logger.info(
70dab99f   tangwang   add logs
493
494
495
                  f"Query parsing completed | Original query: '{query}' | Final query: '{rewritten or query_text}' | "
                  f"Language: {detected_lang} | Domain: {domain} | "
                  f"Translation count: {len(translations)} | Vector: {'yes' if query_vector is not None else 'no'}",
16c42787   tangwang   feat: implement r...
496
497
498
                  extra={'reqid': context.reqid, 'uid': context.uid}
              )
          else:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
499
              logger.info(
70dab99f   tangwang   add logs
500
501
                  f"Query parsing completed | Original query: '{query}' | Final query: '{rewritten or query_text}' | "
                  f"Language: {detected_lang} | Domain: {domain}"
325eec03   tangwang   1. 日志、配置基础设施,使用优化
502
              )
16c42787   tangwang   feat: implement r...
503
  
be52af70   tangwang   first commit
504
505
506
507
508
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
          return result
  
      def get_search_queries(self, parsed_query: ParsedQuery) -> List[str]:
          """
          Get list of queries to search (original + translations).
  
          Args:
              parsed_query: Parsed query object
  
          Returns:
              List of query strings to search
          """
          queries = [parsed_query.rewritten_query]
  
          # Add translations
          for lang, translation in parsed_query.translations.items():
              if translation and translation != parsed_query.rewritten_query:
                  queries.append(translation)
  
          return queries
  
      def update_rewrite_rules(self, rules: Dict[str, str]) -> None:
          """
          Update query rewrite rules.
  
          Args:
              rules: Dictionary of pattern -> replacement mappings
          """
          for pattern, replacement in rules.items():
              self.rewriter.add_rule(pattern, replacement)
  
      def get_rewrite_rules(self) -> Dict[str, str]:
          """Get current rewrite rules."""
          return self.rewriter.get_rules()