b926f678
tangwang
多语言查询
|
1
2
3
4
5
6
7
8
9
10
|
"""
Multi-language query builder for handling domain-specific searches.
This module extends the ESQueryBuilder to support multi-language field mappings,
allowing queries to be routed to appropriate language-specific fields while
maintaining a unified external interface.
"""
from typing import Dict, Any, List, Optional
import numpy as np
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
11
12
|
import logging
import re
|
b926f678
tangwang
多语言查询
|
13
|
|
9cb7528e
tangwang
店匠体系数据的搜索:mock da...
|
14
|
from config import SearchConfig, IndexConfig
|
b926f678
tangwang
多语言查询
|
15
16
17
|
from query import ParsedQuery
from .es_query_builder import ESQueryBuilder
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
18
19
|
logger = logging.getLogger(__name__)
|
b926f678
tangwang
多语言查询
|
20
21
22
23
24
25
26
27
28
29
30
31
32
|
class MultiLanguageQueryBuilder(ESQueryBuilder):
"""
Enhanced query builder with multi-language support.
Handles routing queries to appropriate language-specific fields based on:
1. Detected query language
2. Available translations
3. Domain configuration (language_field_mapping)
"""
def __init__(
self,
|
9cb7528e
tangwang
店匠体系数据的搜索:mock da...
|
33
|
config: SearchConfig,
|
b926f678
tangwang
多语言查询
|
34
35
|
index_name: str,
text_embedding_field: Optional[str] = None,
|
13377199
tangwang
接口优化
|
36
37
|
image_embedding_field: Optional[str] = None,
source_fields: Optional[List[str]] = None
|
b926f678
tangwang
多语言查询
|
38
39
40
41
42
|
):
"""
Initialize multi-language query builder.
Args:
|
37e994bb
tangwang
命名修改、代码清理
|
43
|
config: Search configuration
|
b926f678
tangwang
多语言查询
|
44
45
46
|
index_name: ES index name
text_embedding_field: Field name for text embeddings
image_embedding_field: Field name for image embeddings
|
13377199
tangwang
接口优化
|
47
|
source_fields: Fields to return in search results (_source includes)
|
b926f678
tangwang
多语言查询
|
48
49
|
"""
self.config = config
|
a00c3672
tangwang
feat: Function Sc...
|
50
|
self.function_score_config = config.function_score
|
b926f678
tangwang
多语言查询
|
51
52
53
54
55
56
57
58
|
# For default domain, use all fields as fallback
default_fields = self._get_domain_fields("default")
super().__init__(
index_name=index_name,
match_fields=default_fields,
text_embedding_field=text_embedding_field,
|
13377199
tangwang
接口优化
|
59
60
|
image_embedding_field=image_embedding_field,
source_fields=source_fields
|
b926f678
tangwang
多语言查询
|
61
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
91
92
93
94
|
)
# Build domain configurations
self.domain_configs = self._build_domain_configs()
def _build_domain_configs(self) -> Dict[str, IndexConfig]:
"""Build mapping of domain name to IndexConfig."""
return {index.name: index for index in self.config.indexes}
def _get_domain_fields(self, domain_name: str) -> List[str]:
"""Get fields for a specific domain with boost notation."""
for index in self.config.indexes:
if index.name == domain_name:
result = []
for field_name in index.fields:
field = self._get_field_by_name(field_name)
if field and field.boost != 1.0:
result.append(f"{field_name}^{field.boost}")
else:
result.append(field_name)
return result
return []
def _get_field_by_name(self, field_name: str):
"""Get field configuration by name."""
for field in self.config.fields:
if field.name == field_name:
return field
return None
def build_multilang_query(
self,
parsed_query: ParsedQuery,
query_vector: Optional[np.ndarray] = None,
|
f739c5e3
tangwang
fix sch
|
95
|
query_node: Optional[Any] = None,
|
b926f678
tangwang
多语言查询
|
96
|
filters: Optional[Dict[str, Any]] = None,
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
97
|
range_filters: Optional[Dict[str, Any]] = None,
|
b926f678
tangwang
多语言查询
|
98
99
100
101
102
103
104
105
|
size: int = 10,
from_: int = 0,
enable_knn: bool = True,
knn_k: int = 50,
knn_num_candidates: int = 200,
min_score: Optional[float] = None
) -> Dict[str, Any]:
"""
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
106
|
Build ES query with multi-language support (重构版).
|
b926f678
tangwang
多语言查询
|
107
108
109
110
|
Args:
parsed_query: Parsed query with language info and translations
query_vector: Query embedding for KNN search
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
111
112
|
filters: Exact match filters
range_filters: Range filters for numeric fields
|
b926f678
tangwang
多语言查询
|
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
|
size: Number of results
from_: Offset for pagination
enable_knn: Whether to use KNN search
knn_k: K value for KNN
knn_num_candidates: Number of candidates for KNN
min_score: Minimum score threshold
Returns:
ES query DSL dictionary
"""
domain = parsed_query.domain
domain_config = self.domain_configs.get(domain)
if not domain_config:
# Fallback to default domain
domain = "default"
domain_config = self.domain_configs.get("default")
if not domain_config:
# Use original behavior
return super().build_query(
query_text=parsed_query.rewritten_query,
query_vector=query_vector,
filters=filters,
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
137
|
range_filters=range_filters,
|
b926f678
tangwang
多语言查询
|
138
139
140
141
142
143
144
145
|
size=size,
from_=from_,
enable_knn=enable_knn,
knn_k=knn_k,
knn_num_candidates=knn_num_candidates,
min_score=min_score
)
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
146
|
logger.debug(f"Building query for domain: {domain}, language: {parsed_query.detected_language}")
|
b926f678
tangwang
多语言查询
|
147
148
|
# Build query clause with multi-language support
|
f739c5e3
tangwang
fix sch
|
149
150
151
152
|
if query_node and isinstance(query_node, tuple) and len(query_node) > 0:
# Handle boolean query from tuple (AST, score)
ast_node = query_node[0]
query_clause = self._build_boolean_query_from_tuple(ast_node)
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
153
|
logger.debug(f"Using boolean query")
|
f739c5e3
tangwang
fix sch
|
154
155
156
|
elif query_node and hasattr(query_node, 'operator') and query_node.operator != 'TERM':
# Handle boolean query using base class method
query_clause = self._build_boolean_query(query_node)
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
157
|
logger.debug(f"Using boolean query")
|
f739c5e3
tangwang
fix sch
|
158
159
160
|
else:
# Handle text query with multi-language support
query_clause = self._build_multilang_text_query(parsed_query, domain_config)
|
b926f678
tangwang
多语言查询
|
161
|
|
43f1139f
tangwang
refactor: ES查询结构重...
|
162
163
|
# 构建内层bool: 文本和KNN二选一
inner_bool_should = [query_clause]
|
b926f678
tangwang
多语言查询
|
164
|
|
43f1139f
tangwang
refactor: ES查询结构重...
|
165
166
167
168
169
170
171
172
|
# 如果启用KNN,添加到should
if enable_knn and query_vector is not None and self.text_embedding_field:
knn_query = {
"knn": {
"field": self.text_embedding_field,
"query_vector": query_vector.tolist(),
"k": knn_k,
"num_candidates": knn_num_candidates
|
b926f678
tangwang
多语言查询
|
173
|
}
|
43f1139f
tangwang
refactor: ES查询结构重...
|
174
175
|
}
inner_bool_should.append(knn_query)
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
176
|
logger.info(f"KNN query added: field={self.text_embedding_field}, k={knn_k}")
|
3bb1af6b
tangwang
tenant1和tenant2 m...
|
177
178
179
180
181
182
183
184
185
|
else:
# Debug why KNN is not added
reasons = []
if not enable_knn:
reasons.append("enable_knn=False")
if query_vector is None:
reasons.append("query_vector is None")
if not self.text_embedding_field:
reasons.append(f"text_embedding_field is not set (current: {self.text_embedding_field})")
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
186
|
logger.debug(f"KNN query NOT added. Reasons: {', '.join(reasons) if reasons else 'unknown'}")
|
b926f678
tangwang
多语言查询
|
187
|
|
43f1139f
tangwang
refactor: ES查询结构重...
|
188
189
190
191
192
|
# 构建内层bool结构
inner_bool = {
"bool": {
"should": inner_bool_should,
"minimum_should_match": 1
|
b926f678
tangwang
多语言查询
|
193
|
}
|
43f1139f
tangwang
refactor: ES查询结构重...
|
194
195
196
197
198
199
200
201
202
203
204
205
206
207
|
}
# 构建外层bool: 包含filter
filter_clauses = self._build_filters(filters, range_filters) if (filters or range_filters) else []
outer_bool = {
"bool": {
"must": [inner_bool]
}
}
if filter_clauses:
outer_bool["bool"]["filter"] = filter_clauses
|
a00c3672
tangwang
feat: Function Sc...
|
208
|
# 包裹function_score(从配置读取score_mode和boost_mode)
|
43f1139f
tangwang
refactor: ES查询结构重...
|
209
210
211
212
|
function_score_query = {
"function_score": {
"query": outer_bool,
"functions": self._build_score_functions(),
|
a00c3672
tangwang
feat: Function Sc...
|
213
214
|
"score_mode": self.function_score_config.score_mode if self.function_score_config else "sum",
"boost_mode": self.function_score_config.boost_mode if self.function_score_config else "multiply"
|
43f1139f
tangwang
refactor: ES查询结构重...
|
215
216
217
218
219
220
221
222
|
}
}
es_query = {
"size": size,
"from": from_,
"query": function_score_query
}
|
b926f678
tangwang
多语言查询
|
223
|
|
13377199
tangwang
接口优化
|
224
225
226
227
228
229
|
# Add _source filtering if source_fields are configured
if self.source_fields:
es_query["_source"] = {
"includes": self.source_fields
}
|
b926f678
tangwang
多语言查询
|
230
231
232
233
234
|
if min_score is not None:
es_query["min_score"] = min_score
return es_query
|
43f1139f
tangwang
refactor: ES查询结构重...
|
235
236
|
def _build_score_functions(self) -> List[Dict[str, Any]]:
"""
|
a00c3672
tangwang
feat: Function Sc...
|
237
|
从配置构建 function_score 的打分函数列表
|
43f1139f
tangwang
refactor: ES查询结构重...
|
238
239
|
Returns:
|
a00c3672
tangwang
feat: Function Sc...
|
240
|
打分函数列表(ES原生格式)
|
43f1139f
tangwang
refactor: ES查询结构重...
|
241
|
"""
|
a00c3672
tangwang
feat: Function Sc...
|
242
243
244
|
if not self.function_score_config or not self.function_score_config.functions:
return []
|
43f1139f
tangwang
refactor: ES查询结构重...
|
245
246
|
functions = []
|
a00c3672
tangwang
feat: Function Sc...
|
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
|
for func_config in self.function_score_config.functions:
func_type = func_config.get('type')
if func_type == 'filter_weight':
# Filter + Weight
functions.append({
"filter": func_config['filter'],
"weight": func_config.get('weight', 1.0)
})
elif func_type == 'field_value_factor':
# Field Value Factor
functions.append({
"field_value_factor": {
"field": func_config['field'],
"factor": func_config.get('factor', 1.0),
"modifier": func_config.get('modifier', 'none'),
"missing": func_config.get('missing', 1.0)
}
})
elif func_type == 'decay':
# Decay Function (gauss/exp/linear)
decay_func = func_config.get('function', 'gauss')
field = func_config['field']
decay_params = {
"origin": func_config.get('origin', 'now'),
"scale": func_config['scale']
|
43f1139f
tangwang
refactor: ES查询结构重...
|
276
|
}
|
a00c3672
tangwang
feat: Function Sc...
|
277
278
279
280
281
282
283
284
285
286
287
|
if 'offset' in func_config:
decay_params['offset'] = func_config['offset']
if 'decay' in func_config:
decay_params['decay'] = func_config['decay']
functions.append({
decay_func: {
field: decay_params
}
})
|
43f1139f
tangwang
refactor: ES查询结构重...
|
288
289
290
|
return functions
|
b926f678
tangwang
多语言查询
|
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
|
def _build_multilang_text_query(
self,
parsed_query: ParsedQuery,
domain_config: IndexConfig
) -> Dict[str, Any]:
"""
Build text query with multi-language field routing.
Args:
parsed_query: Parsed query with language info
domain_config: Domain configuration
Returns:
ES query clause
"""
if not domain_config.language_field_mapping:
# No multi-language mapping, use all fields with default analyzer
fields_with_boost = []
for field_name in domain_config.fields:
field = self._get_field_by_name(field_name)
if field and field.boost != 1.0:
fields_with_boost.append(f"{field_name}^{field.boost}")
else:
fields_with_boost.append(field_name)
return {
"multi_match": {
"query": parsed_query.rewritten_query,
"fields": fields_with_boost,
"minimum_should_match": "67%",
"tie_breaker": 0.9,
"boost": domain_config.boost,
"_name": f"{domain_config.name}_query"
}
}
# Multi-language mapping exists - build targeted queries
should_clauses = []
available_languages = set(domain_config.language_field_mapping.keys())
# 1. Query in detected language (if it exists in mapping)
detected_lang = parsed_query.detected_language
if detected_lang in available_languages:
target_fields = domain_config.language_field_mapping[detected_lang]
fields_with_boost = self._apply_field_boosts(target_fields)
should_clauses.append({
"multi_match": {
"query": parsed_query.rewritten_query,
"fields": fields_with_boost,
"minimum_should_match": "67%",
"tie_breaker": 0.9,
"boost": domain_config.boost * 1.5, # Higher boost for detected language
"_name": f"{domain_config.name}_{detected_lang}_query"
}
})
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
347
|
logger.debug(f"Added query for detected language '{detected_lang}'")
|
b926f678
tangwang
多语言查询
|
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
|
# 2. Query in translated languages (only for languages in mapping)
for lang, translation in parsed_query.translations.items():
# Only use translations for languages that exist in the mapping
if lang in available_languages and translation and translation.strip():
target_fields = domain_config.language_field_mapping[lang]
fields_with_boost = self._apply_field_boosts(target_fields)
should_clauses.append({
"multi_match": {
"query": translation,
"fields": fields_with_boost,
"minimum_should_match": "67%",
"tie_breaker": 0.9,
"boost": domain_config.boost,
"_name": f"{domain_config.name}_{lang}_translated_query"
}
})
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
366
|
logger.debug(f"Added translated query for language '{lang}'")
|
b926f678
tangwang
多语言查询
|
367
368
369
|
# 3. Fallback: query all fields in mapping if no language-specific query was built
if not should_clauses:
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
370
|
logger.debug("No language mapping matched, using all fields from mapping")
|
b926f678
tangwang
多语言查询
|
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
|
# Use all fields from all languages in the mapping
all_mapped_fields = []
for lang_fields in domain_config.language_field_mapping.values():
all_mapped_fields.extend(lang_fields)
# Remove duplicates while preserving order
unique_fields = list(dict.fromkeys(all_mapped_fields))
fields_with_boost = self._apply_field_boosts(unique_fields)
should_clauses.append({
"multi_match": {
"query": parsed_query.rewritten_query,
"fields": fields_with_boost,
"minimum_should_match": "67%",
"tie_breaker": 0.9,
"boost": domain_config.boost * 0.8, # Lower boost for fallback
"_name": f"{domain_config.name}_fallback_query"
}
})
if len(should_clauses) == 1:
return should_clauses[0]
else:
return {
"bool": {
"should": should_clauses,
"minimum_should_match": 1
}
}
def _apply_field_boosts(self, field_names: List[str]) -> List[str]:
"""Apply boost values to field names."""
result = []
for field_name in field_names:
field = self._get_field_by_name(field_name)
if field and field.boost != 1.0:
result.append(f"{field_name}^{field.boost}")
else:
result.append(field_name)
return result
|
f739c5e3
tangwang
fix sch
|
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
|
def _build_boolean_query_from_tuple(self, node) -> Dict[str, Any]:
"""
Build query from boolean expression tuple.
Args:
node: Boolean expression tuple (operator, terms...)
Returns:
ES query clause
"""
if not node:
return {"match_all": {}}
# Handle different node types from boolean parser
if hasattr(node, 'operator'):
# QueryNode object
operator = node.operator
|
c86c8237
tangwang
支持聚合。过滤项补充了逻辑,但是有问题
|
428
429
430
431
432
|
terms = node.terms if hasattr(node, 'terms') else None
# For TERM nodes, check if there's a value
if operator == 'TERM' and hasattr(node, 'value') and node.value:
terms = node.value
|
f739c5e3
tangwang
fix sch
|
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
|
elif isinstance(node, tuple) and len(node) > 0:
# Tuple format from boolean parser
if hasattr(node[0], 'operator'):
# Nested tuple with QueryNode
operator = node[0].operator
terms = node[0].terms
elif isinstance(node[0], str):
# Simple tuple like ('TERM', 'field:value')
operator = node[0]
terms = node[1] if len(node) > 1 else ''
else:
# Complex tuple like (OR( TERM(...), TERM(...) ), score)
if hasattr(node[0], '__class__') and hasattr(node[0], '__name__'):
# Constructor call like OR(...)
operator = node[0].__name__
elif str(node[0]).startswith('('):
# String representation of constructor call
|
f739c5e3
tangwang
fix sch
|
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
|
match = re.match(r'(\w+)\(', str(node[0]))
if match:
operator = match.group(1)
else:
return {"match_all": {}}
else:
operator = str(node[0])
# Extract terms from nested structure
terms = []
if len(node) > 1 and isinstance(node[1], tuple):
terms = node[1]
else:
return {"match_all": {}}
|
c86c8237
tangwang
支持聚合。过滤项补充了逻辑,但是有问题
|
465
|
|
f739c5e3
tangwang
fix sch
|
466
467
468
469
470
471
472
473
474
|
if operator == 'TERM':
# Leaf node - handle field:query format
if isinstance(terms, str) and ':' in terms:
field, value = terms.split(':', 1)
return {
"term": {
field: value
}
}
|
c86c8237
tangwang
支持聚合。过滤项补充了逻辑,但是有问题
|
475
476
477
478
479
480
481
482
483
484
|
elif isinstance(terms, str):
# Simple text term - create match query
return {
"multi_match": {
"query": terms,
"fields": self.match_fields,
"type": "best_fields",
"operator": "AND"
}
}
|
f739c5e3
tangwang
fix sch
|
485
|
else:
|
c86c8237
tangwang
支持聚合。过滤项补充了逻辑,但是有问题
|
486
487
488
489
|
# Invalid TERM node - return empty match
return {
"match_none": {}
}
|
f739c5e3
tangwang
fix sch
|
490
491
492
493
|
elif operator == 'OR':
# Any term must match
should_clauses = []
|
c86c8237
tangwang
支持聚合。过滤项补充了逻辑,但是有问题
|
494
495
496
497
498
499
500
501
502
503
504
505
|
if terms:
for term in terms:
clause = self._build_boolean_query_from_tuple(term)
if clause and clause.get("match_none") is None:
should_clauses.append(clause)
if should_clauses:
return {
"bool": {
"should": should_clauses,
"minimum_should_match": 1
}
|
f739c5e3
tangwang
fix sch
|
506
|
}
|
c86c8237
tangwang
支持聚合。过滤项补充了逻辑,但是有问题
|
507
508
|
else:
return {"match_none": {}}
|
f739c5e3
tangwang
fix sch
|
509
510
511
512
|
elif operator == 'AND':
# All terms must match
must_clauses = []
|
c86c8237
tangwang
支持聚合。过滤项补充了逻辑,但是有问题
|
513
514
515
516
517
518
519
520
521
522
523
|
if terms:
for term in terms:
clause = self._build_boolean_query_from_tuple(term)
if clause and clause.get("match_none") is None:
must_clauses.append(clause)
if must_clauses:
return {
"bool": {
"must": must_clauses
}
|
f739c5e3
tangwang
fix sch
|
524
|
}
|
c86c8237
tangwang
支持聚合。过滤项补充了逻辑,但是有问题
|
525
526
|
else:
return {"match_none": {}}
|
f739c5e3
tangwang
fix sch
|
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
|
elif operator == 'ANDNOT':
# First term must match, second must not
if len(terms) >= 2:
return {
"bool": {
"must": [self._build_boolean_query_from_tuple(terms[0])],
"must_not": [self._build_boolean_query_from_tuple(terms[1])]
}
}
else:
return self._build_boolean_query_from_tuple(terms[0])
elif operator == 'RANK':
# Like OR but for ranking (all terms contribute to score)
should_clauses = []
for term in terms:
should_clauses.append(self._build_boolean_query_from_tuple(term))
return {
"bool": {
"should": should_clauses
}
}
else:
# Unknown operator
return {"match_all": {}}
|
b926f678
tangwang
多语言查询
|
555
556
557
558
559
560
561
562
563
564
565
566
567
|
def get_domain_summary(self) -> Dict[str, Any]:
"""Get summary of all configured domains."""
summary = {}
for domain_name, domain_config in self.domain_configs.items():
summary[domain_name] = {
"label": domain_config.label,
"fields": domain_config.fields,
"analyzer": domain_config.analyzer.value,
"boost": domain_config.boost,
"has_multilang_mapping": domain_config.language_field_mapping is not None,
"supported_languages": list(domain_config.language_field_mapping.keys()) if domain_config.language_field_mapping else []
}
return summary
|