be52af70
tangwang
first commit
|
1
2
3
4
5
6
|
"""
Query parser - main module for query processing.
Handles query rewriting, translation, and embedding generation.
"""
|
00c8ddb9
tangwang
suggest rank opti...
|
7
|
from typing import Dict, List, Optional, Any, Union, Tuple
|
be52af70
tangwang
first commit
|
8
|
import numpy as np
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
9
|
import logging
|
7bc756c5
tangwang
优化 ES 查询构建
|
10
|
import re
|
1556989b
tangwang
query翻译等待超时逻辑
|
11
|
from concurrent.futures import ThreadPoolExecutor, wait
|
be52af70
tangwang
first commit
|
12
|
|
07cf5a93
tangwang
START_EMBEDDING=...
|
13
|
from embeddings.text_encoder import TextEmbeddingEncoder
|
9f96d6f3
tangwang
短query不用语义搜索
|
14
|
from config import SearchConfig
|
0fd2f875
tangwang
translate
|
15
|
from translation import create_translation_client
|
be52af70
tangwang
first commit
|
16
|
from .language_detector import LanguageDetector
|
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
|
|
00c8ddb9
tangwang
suggest rank opti...
|
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
def simple_tokenize_query(text: str) -> List[str]:
"""
Lightweight tokenizer for suggestion length / analysis (aligned with QueryParser fallback).
- Consecutive CJK characters form one token
- Latin / digit runs (with internal hyphens) form tokens
"""
if not text:
return []
pattern = re.compile(r"[\u4e00-\u9fff]+|[A-Za-z0-9_]+(?:-[A-Za-z0-9_]+)*")
return pattern.findall(text)
|
be52af70
tangwang
first commit
|
40
41
42
43
44
45
|
class ParsedQuery:
"""Container for parsed query results."""
def __init__(
self,
original_query: str,
|
3a5fda00
tangwang
1. ES字段 skus的 ima...
|
46
|
query_normalized: str,
|
be52af70
tangwang
first commit
|
47
|
rewritten_query: Optional[str] = None,
|
a5a6bab8
tangwang
多语言查询优化
|
48
|
detected_language: Optional[str] = None,
|
be52af70
tangwang
first commit
|
49
50
|
translations: Dict[str, str] = None,
query_vector: Optional[np.ndarray] = None,
|
7bc756c5
tangwang
优化 ES 查询构建
|
51
52
53
|
domain: str = "default",
keywords: str = "",
token_count: int = 0,
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
54
55
56
57
58
|
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,
|
6823fe3e
tangwang
feat(search): 混合语...
|
59
60
|
contains_chinese: bool = False,
contains_english: bool = False,
|
be52af70
tangwang
first commit
|
61
62
|
):
self.original_query = original_query
|
3a5fda00
tangwang
1. ES字段 skus的 ima...
|
63
64
|
self.query_normalized = query_normalized
self.rewritten_query = rewritten_query or query_normalized
|
be52af70
tangwang
first commit
|
65
66
67
68
|
self.detected_language = detected_language
self.translations = translations or {}
self.query_vector = query_vector
self.domain = domain
|
7bc756c5
tangwang
优化 ES 查询构建
|
69
70
71
|
# Query analysis fields
self.keywords = keywords
self.token_count = token_count
|
ea118f2b
tangwang
build_query:根据 qu...
|
72
|
self.query_tokens = query_tokens or []
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
73
74
75
76
|
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)
|
6823fe3e
tangwang
feat(search): 混合语...
|
77
78
|
self.contains_chinese = bool(contains_chinese)
self.contains_english = bool(contains_english)
|
be52af70
tangwang
first commit
|
79
80
81
82
83
|
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary representation."""
result = {
"original_query": self.original_query,
|
3a5fda00
tangwang
1. ES字段 skus的 ima...
|
84
|
"query_normalized": self.query_normalized,
|
be52af70
tangwang
first commit
|
85
86
87
|
"rewritten_query": self.rewritten_query,
"detected_language": self.detected_language,
"translations": self.translations,
|
038e4e2f
tangwang
refactor(i18n): t...
|
88
|
"domain": self.domain
|
be52af70
tangwang
first commit
|
89
|
}
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
90
91
92
93
|
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
|
6823fe3e
tangwang
feat(search): 混合语...
|
94
95
|
result["contains_chinese"] = self.contains_chinese
result["contains_english"] = self.contains_english
|
be52af70
tangwang
first commit
|
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
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不用语义搜索
|
111
|
config: SearchConfig,
|
950a640e
tangwang
embeddings
|
112
|
text_encoder: Optional[TextEmbeddingEncoder] = None,
|
42e3aea6
tangwang
tidy
|
113
|
translator: Optional[Any] = None
|
be52af70
tangwang
first commit
|
114
115
116
117
118
|
):
"""
Initialize query parser.
Args:
|
9f96d6f3
tangwang
短query不用语义搜索
|
119
|
config: SearchConfig instance
|
26b910bd
tangwang
refactor service ...
|
120
121
|
text_encoder: Text embedding encoder (initialized at startup if not provided)
translator: Translator instance (initialized at startup if not provided)
|
be52af70
tangwang
first commit
|
122
|
"""
|
9f96d6f3
tangwang
短query不用语义搜索
|
123
|
self.config = config
|
be52af70
tangwang
first commit
|
124
125
126
127
128
129
|
self._text_encoder = text_encoder
self._translator = translator
# Initialize components
self.normalizer = QueryNormalizer()
self.language_detector = LanguageDetector()
|
9f96d6f3
tangwang
短query不用语义搜索
|
130
|
self.rewriter = QueryRewriter(config.query_config.rewrite_dictionary)
|
7bc756c5
tangwang
优化 ES 查询构建
|
131
|
|
484adbfe
tangwang
adapt ubuntu; con...
|
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
|
# 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
|
148
|
|
26b910bd
tangwang
refactor service ...
|
149
150
151
152
153
154
155
|
# 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()
|
5e4dc8e4
tangwang
翻译架构按“一个翻译服务 +
|
156
157
|
logger.info(
"Initializing translator client at QueryParser construction (service_url=%s, default_model=%s)...",
|
a8261ece
tangwang
检索效果优化
|
158
159
|
cfg.get("service_url"),
cfg.get("default_model"),
|
5e4dc8e4
tangwang
翻译架构按“一个翻译服务 +
|
160
|
)
|
0fd2f875
tangwang
translate
|
161
|
self._translator = create_translation_client()
|
26b910bd
tangwang
refactor service ...
|
162
|
|
be52af70
tangwang
first commit
|
163
|
@property
|
950a640e
tangwang
embeddings
|
164
|
def text_encoder(self) -> TextEmbeddingEncoder:
|
26b910bd
tangwang
refactor service ...
|
165
|
"""Return pre-initialized text encoder."""
|
be52af70
tangwang
first commit
|
166
167
168
|
return self._text_encoder
@property
|
42e3aea6
tangwang
tidy
|
169
|
def translator(self) -> Any:
|
26b910bd
tangwang
refactor service ...
|
170
|
"""Return pre-initialized translator."""
|
be52af70
tangwang
first commit
|
171
|
return self._translator
|
484adbfe
tangwang
adapt ubuntu; con...
|
172
|
|
e56fbdc1
tangwang
query trans
|
173
|
@staticmethod
|
77bfa7e3
tangwang
query translate
|
174
175
|
def _pick_query_translation_model(source_lang: str, target_lang: str, config: SearchConfig) -> str:
"""Pick the translation capability for query-time translation (configurable)."""
|
e56fbdc1
tangwang
query trans
|
176
177
|
src = str(source_lang or "").strip().lower()
tgt = str(target_lang or "").strip().lower()
|
77bfa7e3
tangwang
query translate
|
178
179
|
# Use dedicated models for zh<->en if configured
|
e56fbdc1
tangwang
query trans
|
180
|
if src == "zh" and tgt == "en":
|
77bfa7e3
tangwang
query translate
|
181
|
return config.query_config.zh_to_en_model
|
e56fbdc1
tangwang
query trans
|
182
|
if src == "en" and tgt == "zh":
|
77bfa7e3
tangwang
query translate
|
183
184
185
186
187
|
return config.query_config.en_to_zh_model
# For any other language pairs, fall back to the configurable default model.
# By default this is `nllb-200-distilled-600m` (multi-lingual local model).
return config.query_config.default_translation_model
|
e56fbdc1
tangwang
query trans
|
188
|
|
484adbfe
tangwang
adapt ubuntu; con...
|
189
|
def _simple_tokenize(self, text: str) -> List[str]:
|
00c8ddb9
tangwang
suggest rank opti...
|
190
|
return simple_tokenize_query(text)
|
7bc756c5
tangwang
优化 ES 查询构建
|
191
192
193
|
def _extract_keywords(self, query: str) -> str:
"""Extract keywords (nouns with length > 1) from query."""
|
484adbfe
tangwang
adapt ubuntu; con...
|
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
|
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 查询构建
|
209
210
211
|
return " ".join(keywords)
def _get_token_count(self, query: str) -> int:
|
484adbfe
tangwang
adapt ubuntu; con...
|
212
213
214
215
216
|
"""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...
|
217
218
|
def _get_query_tokens(self, query: str) -> List[str]:
|
484adbfe
tangwang
adapt ubuntu; con...
|
219
220
221
222
223
|
"""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
|
224
|
|
a8261ece
tangwang
检索效果优化
|
225
226
227
228
229
230
|
@staticmethod
def _contains_cjk(text: str) -> bool:
"""Whether query contains any CJK ideograph."""
return bool(re.search(r"[\u4e00-\u9fff]", text or ""))
@staticmethod
|
6823fe3e
tangwang
feat(search): 混合语...
|
231
232
233
234
235
236
237
238
239
240
|
def _is_pure_english_word_token(token: str) -> bool:
"""
A tokenizer token counts as English iff it is letters only (optional internal hyphens)
and length >= 3.
"""
if not token or len(token) < 3:
return False
return bool(re.fullmatch(r"[A-Za-z]+(?:-[A-Za-z]+)*", token))
@staticmethod
|
a8261ece
tangwang
检索效果优化
|
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
|
def _extract_latin_tokens(text: str) -> List[str]:
"""Extract latin word tokens from query text."""
return re.findall(r"[A-Za-z]+(?:-[A-Za-z]+)*", text or "")
def _infer_supplemental_search_langs(
self,
query_text: str,
detected_lang: str,
index_langs: List[str],
) -> List[str]:
"""
Infer extra languages to search when the query mixes scripts.
Rules:
- If any Chinese characters appear, include `zh` when available.
- If the query contains meaningful latin tokens, include `en` when available.
"Meaningful" means either:
1) at least 2 latin tokens with length >= 4, or
2) at least 1 latin token with length >= 4 and latin chars occupy >= 20% of non-space chars.
"""
supplemental: List[str] = []
normalized_index_langs = {str(lang or "").strip().lower() for lang in index_langs}
normalized_detected = str(detected_lang or "").strip().lower()
query_text = str(query_text or "")
if "zh" in normalized_index_langs and self._contains_cjk(query_text) and normalized_detected != "zh":
supplemental.append("zh")
latin_tokens = self._extract_latin_tokens(query_text)
significant_latin_tokens = [tok for tok in latin_tokens if len(tok) >= 4]
latin_chars = sum(len(tok) for tok in latin_tokens)
non_space_chars = len(re.sub(r"\s+", "", query_text))
latin_ratio = (latin_chars / non_space_chars) if non_space_chars > 0 else 0.0
has_meaningful_english = (
len(significant_latin_tokens) >= 2 or
(len(significant_latin_tokens) >= 1 and latin_ratio >= 0.2)
)
if "en" in normalized_index_langs and has_meaningful_english and normalized_detected != "en":
supplemental.append("en")
return supplemental
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
284
285
286
287
288
289
290
|
def parse(
self,
query: str,
tenant_id: Optional[str] = None,
generate_vector: bool = True,
context: Optional[Any] = None
) -> ParsedQuery:
|
be52af70
tangwang
first commit
|
291
292
293
294
295
296
|
"""
Parse query through all processing stages.
Args:
query: Raw query string
generate_vector: Whether to generate query embedding
|
16c42787
tangwang
feat: implement r...
|
297
|
context: Optional request context for tracking and logging
|
be52af70
tangwang
first commit
|
298
299
300
301
|
Returns:
ParsedQuery object with all processing results
"""
|
16c42787
tangwang
feat: implement r...
|
302
|
# Initialize logger if context provided
|
950a640e
tangwang
embeddings
|
303
304
305
|
active_logger = context.logger if context else logger
if context and hasattr(context, "logger"):
context.logger.info(
|
70dab99f
tangwang
add logs
|
306
|
f"Starting query parsing | Original query: '{query}' | Generate vector: {generate_vector}",
|
16c42787
tangwang
feat: implement r...
|
307
308
309
|
extra={'reqid': context.reqid, 'uid': context.uid}
)
|
16c42787
tangwang
feat: implement r...
|
310
|
def log_info(msg):
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
311
312
|
if context and hasattr(context, 'logger'):
context.logger.info(msg, extra={'reqid': context.reqid, 'uid': context.uid})
|
16c42787
tangwang
feat: implement r...
|
313
|
else:
|
950a640e
tangwang
embeddings
|
314
|
active_logger.info(msg)
|
16c42787
tangwang
feat: implement r...
|
315
316
|
def log_debug(msg):
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
317
318
|
if context and hasattr(context, 'logger'):
context.logger.debug(msg, extra={'reqid': context.reqid, 'uid': context.uid})
|
16c42787
tangwang
feat: implement r...
|
319
|
else:
|
950a640e
tangwang
embeddings
|
320
|
active_logger.debug(msg)
|
be52af70
tangwang
first commit
|
321
322
323
|
# Stage 1: Normalize
normalized = self.normalizer.normalize(query)
|
70dab99f
tangwang
add logs
|
324
|
log_debug(f"Normalization completed | '{query}' -> '{normalized}'")
|
16c42787
tangwang
feat: implement r...
|
325
|
if context:
|
3a5fda00
tangwang
1. ES字段 skus的 ima...
|
326
|
context.store_intermediate_result('query_normalized', normalized)
|
be52af70
tangwang
first commit
|
327
328
329
|
# 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
|
330
|
log_debug(f"Domain extraction | Domain: '{domain}', Query: '{query_text}'")
|
16c42787
tangwang
feat: implement r...
|
331
332
333
|
if context:
context.store_intermediate_result('extracted_domain', domain)
context.store_intermediate_result('domain_query', query_text)
|
be52af70
tangwang
first commit
|
334
335
336
|
# Stage 2: Query rewriting
rewritten = None
|
9f96d6f3
tangwang
短query不用语义搜索
|
337
|
if self.config.query_config.rewrite_dictionary: # Enable rewrite if dictionary exists
|
be52af70
tangwang
first commit
|
338
339
|
rewritten = self.rewriter.rewrite(query_text)
if rewritten != query_text:
|
70dab99f
tangwang
add logs
|
340
|
log_info(f"Query rewritten | '{query_text}' -> '{rewritten}'")
|
be52af70
tangwang
first commit
|
341
|
query_text = rewritten
|
16c42787
tangwang
feat: implement r...
|
342
343
|
if context:
context.store_intermediate_result('rewritten_query', rewritten)
|
70dab99f
tangwang
add logs
|
344
|
context.add_warning(f"Query was rewritten: {query_text}")
|
be52af70
tangwang
first commit
|
345
346
347
|
# Stage 3: Language detection
detected_lang = self.language_detector.detect(query_text)
|
a5a6bab8
tangwang
多语言查询优化
|
348
349
350
|
# 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
|
351
|
log_info(f"Language detection | Detected language: {detected_lang}")
|
16c42787
tangwang
feat: implement r...
|
352
353
|
if context:
context.store_intermediate_result('detected_language', detected_lang)
|
be52af70
tangwang
first commit
|
354
|
|
1556989b
tangwang
query翻译等待超时逻辑
|
355
356
357
358
359
|
# Stage 4: Translation — always submit to thread pool; results are collected together with
# embedding in one wait() that uses a configurable budget (short vs long by source-in-index).
translations: Dict[str, str] = {}
translation_futures: Dict[str, Any] = {}
translation_executor: Optional[ThreadPoolExecutor] = None
|
86d8358b
tangwang
config optimize
|
360
|
index_langs: List[str] = []
|
1556989b
tangwang
query翻译等待超时逻辑
|
361
362
|
detected_norm = str(detected_lang or "").strip().lower()
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
363
|
try:
|
038e4e2f
tangwang
refactor(i18n): t...
|
364
|
# 根据租户配置的 index_languages 决定翻译目标语言
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
365
366
367
|
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")
|
86d8358b
tangwang
config optimize
|
368
|
raw_index_langs = tenant_cfg.get("index_languages") or []
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
369
370
371
372
373
374
375
376
|
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...
|
377
|
|
1556989b
tangwang
query翻译等待超时逻辑
|
378
|
target_langs_for_translation = [lang for lang in index_langs if lang != detected_norm]
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
379
|
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
380
|
if target_langs_for_translation:
|
1556989b
tangwang
query翻译等待超时逻辑
|
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
|
translation_executor = ThreadPoolExecutor(
max_workers=max(1, min(len(target_langs_for_translation), 4)),
thread_name_prefix="query-translation",
)
for lang in target_langs_for_translation:
model_name = self._pick_query_translation_model(detected_lang, lang, self.config)
log_debug(
f"Submitting query translation | source={detected_lang} target={lang} model={model_name}"
)
translation_futures[lang] = translation_executor.submit(
self.translator.translate,
query_text,
lang,
detected_lang,
"ecommerce_search_query",
model_name,
)
|
d4cadc13
tangwang
翻译重构
|
398
|
|
1556989b
tangwang
query翻译等待超时逻辑
|
399
400
401
402
403
|
if context:
context.store_intermediate_result('translations', translations)
for lang, translation in translations.items():
if translation:
context.store_intermediate_result(f'translation_{lang}', translation)
|
16c42787
tangwang
feat: implement r...
|
404
|
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
405
|
except Exception as e:
|
70dab99f
tangwang
add logs
|
406
|
error_msg = f"Translation failed | Error: {str(e)}"
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
407
408
409
|
log_info(error_msg)
if context:
context.add_warning(error_msg)
|
be52af70
tangwang
first commit
|
410
|
|
ea118f2b
tangwang
build_query:根据 qu...
|
411
|
# Stage 5: Query analysis (keywords, token count, query_tokens)
|
7bc756c5
tangwang
优化 ES 查询构建
|
412
|
keywords = self._extract_keywords(query_text)
|
ea118f2b
tangwang
build_query:根据 qu...
|
413
414
|
query_tokens = self._get_query_tokens(query_text)
token_count = len(query_tokens)
|
6823fe3e
tangwang
feat(search): 混合语...
|
415
416
|
contains_chinese = self._contains_cjk(query_text)
contains_english = any(self._is_pure_english_word_token(t) for t in query_tokens)
|
7bc756c5
tangwang
优化 ES 查询构建
|
417
|
|
70dab99f
tangwang
add logs
|
418
|
log_debug(f"Query analysis | Keywords: {keywords} | Token count: {token_count} | "
|
6823fe3e
tangwang
feat(search): 混合语...
|
419
420
|
f"Query tokens: {query_tokens} | contains_chinese={contains_chinese} | "
f"contains_english={contains_english}")
|
7bc756c5
tangwang
优化 ES 查询构建
|
421
422
423
|
if context:
context.store_intermediate_result('keywords', keywords)
context.store_intermediate_result('token_count', token_count)
|
ea118f2b
tangwang
build_query:根据 qu...
|
424
|
context.store_intermediate_result('query_tokens', query_tokens)
|
6823fe3e
tangwang
feat(search): 混合语...
|
425
426
|
context.store_intermediate_result('contains_chinese', contains_chinese)
context.store_intermediate_result('contains_english', contains_english)
|
7bc756c5
tangwang
优化 ES 查询构建
|
427
|
|
3ec5bfe6
tangwang
1. get_translatio...
|
428
|
# Stage 6: Text embedding (only for non-short queries) - async execution
|
be52af70
tangwang
first commit
|
429
|
query_vector = None
|
3ec5bfe6
tangwang
1. get_translatio...
|
430
|
embedding_future = None
|
7bc756c5
tangwang
优化 ES 查询构建
|
431
432
|
should_generate_embedding = (
generate_vector and
|
9f96d6f3
tangwang
短query不用语义搜索
|
433
|
self.config.query_config.enable_text_embedding and
|
d90e7428
tangwang
补充重排
|
434
|
domain == "default"
|
7bc756c5
tangwang
优化 ES 查询构建
|
435
436
|
)
|
3ec5bfe6
tangwang
1. get_translatio...
|
437
|
encoding_executor = None
|
7bc756c5
tangwang
优化 ES 查询构建
|
438
439
|
if should_generate_embedding:
try:
|
26b910bd
tangwang
refactor service ...
|
440
441
|
if self.text_encoder is None:
raise RuntimeError("Text embedding is enabled but text encoder is not initialized")
|
70dab99f
tangwang
add logs
|
442
|
log_debug("Starting query vector generation (async)")
|
3ec5bfe6
tangwang
1. get_translatio...
|
443
444
|
# Submit encoding task to thread pool for async execution
encoding_executor = ThreadPoolExecutor(max_workers=1)
|
b2e50710
tangwang
BgeEncoder.encode...
|
445
|
def _encode_query_vector() -> Optional[np.ndarray]:
|
b754fd41
tangwang
图片向量化支持优先级参数
|
446
|
arr = self.text_encoder.encode([query_text], priority=1)
|
b2e50710
tangwang
BgeEncoder.encode...
|
447
448
449
450
|
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...
|
451
|
embedding_future = encoding_executor.submit(
|
b2e50710
tangwang
BgeEncoder.encode...
|
452
|
_encode_query_vector
|
3ec5bfe6
tangwang
1. get_translatio...
|
453
|
)
|
7bc756c5
tangwang
优化 ES 查询构建
|
454
|
except Exception as e:
|
70dab99f
tangwang
add logs
|
455
|
error_msg = f"Query vector generation task submission failed | Error: {str(e)}"
|
7bc756c5
tangwang
优化 ES 查询构建
|
456
457
458
|
log_info(error_msg)
if context:
context.add_warning(error_msg)
|
3ec5bfe6
tangwang
1. get_translatio...
|
459
460
461
|
encoding_executor = None
embedding_future = None
|
1556989b
tangwang
query翻译等待超时逻辑
|
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
|
# Wait for translation + embedding concurrently; shared budget (ms) depends on whether
# the detected language is in tenant index_languages.
qc = self.config.query_config
source_in_index_for_budget = detected_norm in index_langs
budget_ms = (
qc.translation_embedding_wait_budget_ms_source_in_index
if source_in_index_for_budget
else qc.translation_embedding_wait_budget_ms_source_not_in_index
)
budget_sec = max(0.0, float(budget_ms) / 1000.0)
if translation_futures:
log_info(
f"Translation+embedding shared wait budget | budget_ms={budget_ms} | "
f"source_in_index_languages={source_in_index_for_budget} | "
f"translation_targets={list(translation_futures.keys())}"
)
|
3ec5bfe6
tangwang
1. get_translatio...
|
480
|
if translation_futures or embedding_future:
|
1556989b
tangwang
query翻译等待超时逻辑
|
481
482
483
484
485
486
487
|
log_debug(
f"Waiting for async tasks (translation+embedding) | budget_ms={budget_ms} | "
f"source_in_index_languages={source_in_index_for_budget}"
)
all_futures: List[Any] = []
future_to_lang: Dict[Any, tuple] = {}
|
3ec5bfe6
tangwang
1. get_translatio...
|
488
489
|
for lang, future in translation_futures.items():
all_futures.append(future)
|
1556989b
tangwang
query翻译等待超时逻辑
|
490
491
|
future_to_lang[future] = ("translation", lang)
|
3ec5bfe6
tangwang
1. get_translatio...
|
492
493
|
if embedding_future:
all_futures.append(embedding_future)
|
1556989b
tangwang
query翻译等待超时逻辑
|
494
495
496
|
future_to_lang[embedding_future] = ("embedding", None)
done, not_done = wait(all_futures, timeout=budget_sec)
|
d4cadc13
tangwang
翻译重构
|
497
|
for future in done:
|
3ec5bfe6
tangwang
1. get_translatio...
|
498
499
500
|
task_type, lang = future_to_lang[future]
try:
result = future.result()
|
1556989b
tangwang
query翻译等待超时逻辑
|
501
|
if task_type == "translation":
|
3ec5bfe6
tangwang
1. get_translatio...
|
502
503
|
if result:
translations[lang] = result
|
d4cadc13
tangwang
翻译重构
|
504
|
log_info(
|
1556989b
tangwang
query翻译等待超时逻辑
|
505
506
|
f"Translation completed | Query text: '{query_text}' | "
f"Target language: {lang} | Translation result: '{result}'"
|
d4cadc13
tangwang
翻译重构
|
507
|
)
|
3ec5bfe6
tangwang
1. get_translatio...
|
508
|
if context:
|
1556989b
tangwang
query翻译等待超时逻辑
|
509
510
|
context.store_intermediate_result(f"translation_{lang}", result)
elif task_type == "embedding":
|
3ec5bfe6
tangwang
1. get_translatio...
|
511
|
query_vector = result
|
b2e50710
tangwang
BgeEncoder.encode...
|
512
|
if query_vector is not None:
|
70dab99f
tangwang
add logs
|
513
|
log_debug(f"Query vector generation completed | Shape: {query_vector.shape}")
|
b2e50710
tangwang
BgeEncoder.encode...
|
514
|
if context:
|
1556989b
tangwang
query翻译等待超时逻辑
|
515
|
context.store_intermediate_result("query_vector_shape", query_vector.shape)
|
b2e50710
tangwang
BgeEncoder.encode...
|
516
|
else:
|
1556989b
tangwang
query翻译等待超时逻辑
|
517
518
519
|
log_info(
"Query vector generation completed but result is None, will process without vector"
)
|
3ec5bfe6
tangwang
1. get_translatio...
|
520
|
except Exception as e:
|
1556989b
tangwang
query翻译等待超时逻辑
|
521
|
if task_type == "translation":
|
70dab99f
tangwang
add logs
|
522
|
error_msg = f"Translation failed | Language: {lang} | Error: {str(e)}"
|
3ec5bfe6
tangwang
1. get_translatio...
|
523
|
else:
|
70dab99f
tangwang
add logs
|
524
|
error_msg = f"Query vector generation failed | Error: {str(e)}"
|
3ec5bfe6
tangwang
1. get_translatio...
|
525
526
527
|
log_info(error_msg)
if context:
context.add_warning(error_msg)
|
d4cadc13
tangwang
翻译重构
|
528
|
|
d4cadc13
tangwang
翻译重构
|
529
530
531
|
if not_done:
for future in not_done:
task_type, lang = future_to_lang[future]
|
1556989b
tangwang
query翻译等待超时逻辑
|
532
|
if task_type == "translation":
|
d4cadc13
tangwang
翻译重构
|
533
|
timeout_msg = (
|
1556989b
tangwang
query翻译等待超时逻辑
|
534
|
f"Translation timeout (>{budget_ms}ms) | Language: {lang} | "
|
d4cadc13
tangwang
翻译重构
|
535
536
537
|
f"Query text: '{query_text}'"
)
else:
|
1556989b
tangwang
query翻译等待超时逻辑
|
538
539
540
|
timeout_msg = (
f"Query vector generation timeout (>{budget_ms}ms), proceeding without embedding result"
)
|
d4cadc13
tangwang
翻译重构
|
541
542
543
544
|
log_info(timeout_msg)
if context:
context.add_warning(timeout_msg)
|
3ec5bfe6
tangwang
1. get_translatio...
|
545
546
|
if encoding_executor:
encoding_executor.shutdown(wait=False)
|
d4cadc13
tangwang
翻译重构
|
547
548
|
if translation_executor:
translation_executor.shutdown(wait=False)
|
1556989b
tangwang
query翻译等待超时逻辑
|
549
|
|
3ec5bfe6
tangwang
1. get_translatio...
|
550
|
if translations and context:
|
1556989b
tangwang
query翻译等待超时逻辑
|
551
|
context.store_intermediate_result("translations", translations)
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
552
553
554
555
556
557
558
559
|
# 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)
|
a8261ece
tangwang
检索效果优化
|
560
561
562
563
564
565
566
567
568
569
570
|
supplemental_search_langs = self._infer_supplemental_search_langs(
query_text=query_text,
detected_lang=detected_lang,
index_langs=index_langs,
)
for lang in supplemental_search_langs:
if lang not in query_text_by_lang and query_text:
# Use the original mixed-script query as a robust fallback probe for that language field set.
query_text_by_lang[lang] = query_text
|
1556989b
tangwang
query翻译等待超时逻辑
|
571
|
source_in_index_languages = detected_norm in index_langs
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
|
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)
|
a8261ece
tangwang
检索效果优化
|
589
|
context.store_intermediate_result("supplemental_search_langs", supplemental_search_langs)
|
be52af70
tangwang
first commit
|
590
591
592
593
|
# Build result
result = ParsedQuery(
original_query=query,
|
3a5fda00
tangwang
1. ES字段 skus的 ima...
|
594
|
query_normalized=normalized,
|
be52af70
tangwang
first commit
|
595
596
597
598
|
rewritten_query=rewritten,
detected_language=detected_lang,
translations=translations,
query_vector=query_vector,
|
7bc756c5
tangwang
优化 ES 查询构建
|
599
600
601
|
domain=domain,
keywords=keywords,
token_count=token_count,
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
602
603
604
605
606
|
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,
|
6823fe3e
tangwang
feat(search): 混合语...
|
607
608
|
contains_chinese=contains_chinese,
contains_english=contains_english,
|
be52af70
tangwang
first commit
|
609
610
|
)
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
611
612
|
if context and hasattr(context, 'logger'):
context.logger.info(
|
70dab99f
tangwang
add logs
|
613
614
615
|
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...
|
616
617
618
|
extra={'reqid': context.reqid, 'uid': context.uid}
)
else:
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
619
|
logger.info(
|
70dab99f
tangwang
add logs
|
620
621
|
f"Query parsing completed | Original query: '{query}' | Final query: '{rewritten or query_text}' | "
f"Language: {detected_lang} | Domain: {domain}"
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
622
|
)
|
16c42787
tangwang
feat: implement r...
|
623
|
|
be52af70
tangwang
first commit
|
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
|
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
|
00c8ddb9
tangwang
suggest rank opti...
|
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
|
def detect_text_language_for_suggestions(
text: str,
*,
index_languages: Optional[List[str]] = None,
primary_language: str = "en",
) -> Tuple[str, float, str]:
"""
Language detection for short strings (mixed-language tags, query-log fallback).
Uses the same ``LanguageDetector`` as :class:`QueryParser`. Returns a language
code present in ``index_languages`` when possible, otherwise the tenant primary.
Returns:
(lang, confidence, source) where source is ``detector``, ``fallback``, or ``default``.
"""
langs_list = [x for x in (index_languages or []) if x]
langs_set = set(langs_list)
def _norm_lang(raw: Optional[str]) -> Optional[str]:
if not raw:
return None
token = str(raw).strip().lower().replace("-", "_")
if not token:
return None
if token in {"zh_tw", "pt_br"}:
return token
return token.split("_")[0]
primary = _norm_lang(primary_language) or "en"
if primary not in langs_set and langs_list:
primary = _norm_lang(langs_list[0]) or langs_list[0]
if not text or not str(text).strip():
return primary, 0.0, "default"
raw_code = LanguageDetector().detect(str(text).strip())
if not raw_code or raw_code == "unknown":
return primary, 0.35, "default"
def _index_lang_base(cand: str) -> str:
t = str(cand).strip().lower().replace("-", "_")
return t.split("_")[0] if t else ""
def _resolve_index_lang(code: str) -> Optional[str]:
if code in langs_set:
return code
for cand in langs_list:
if _index_lang_base(cand) == code:
return cand
return None
if langs_list:
resolved = _resolve_index_lang(raw_code)
if resolved is None:
return primary, 0.5, "fallback"
return resolved, 0.92, "detector"
return raw_code, 0.92, "detector"
|