be52af70
tangwang
first commit
|
1
2
3
4
|
"""
Elasticsearch query builder.
Converts parsed queries and search parameters into ES DSL queries.
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
5
6
7
8
|
Simplified architecture:
- filters and (text_recall or embedding_recall)
- function_score wrapper for boosting fields
|
be52af70
tangwang
first commit
|
9
10
|
"""
|
7bc756c5
tangwang
优化 ES 查询构建
|
11
|
from typing import Dict, Any, List, Optional, Union, Tuple
|
6823fe3e
tangwang
feat(search): 混合语...
|
12
|
|
be52af70
tangwang
first commit
|
13
|
import numpy as np
|
9f96d6f3
tangwang
短query不用语义搜索
|
14
|
from config import FunctionScoreConfig
|
be52af70
tangwang
first commit
|
15
|
|
6823fe3e
tangwang
feat(search): 混合语...
|
16
17
18
|
# (Elasticsearch field path, boost before formatting as "path^boost")
MatchFieldSpec = Tuple[str, float]
|
be52af70
tangwang
first commit
|
19
20
21
22
23
24
|
class ESQueryBuilder:
"""Builds Elasticsearch DSL queries."""
def __init__(
self,
|
be52af70
tangwang
first commit
|
25
|
match_fields: List[str],
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
26
27
28
29
|
field_boosts: Optional[Dict[str, float]] = None,
multilingual_fields: Optional[List[str]] = None,
shared_fields: Optional[List[str]] = None,
core_multilingual_fields: Optional[List[str]] = None,
|
be52af70
tangwang
first commit
|
30
|
text_embedding_field: Optional[str] = None,
|
13377199
tangwang
接口优化
|
31
|
image_embedding_field: Optional[str] = None,
|
9f96d6f3
tangwang
短query不用语义搜索
|
32
|
source_fields: Optional[List[str]] = None,
|
7bc756c5
tangwang
优化 ES 查询构建
|
33
|
function_score_config: Optional[FunctionScoreConfig] = None,
|
2739b281
tangwang
多语言索引调整
|
34
|
default_language: str = "en",
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
35
36
37
38
39
40
|
knn_boost: float = 0.25,
base_minimum_should_match: str = "75%",
translation_minimum_should_match: str = "75%",
translation_boost: float = 0.4,
translation_boost_when_source_missing: float = 1.0,
source_boost_when_missing: float = 0.6,
|
bcada818
tangwang
last
|
41
|
original_query_fallback_boost_when_translation_missing: float = 0.2,
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
42
|
tie_breaker_base_query: float = 0.9,
|
6823fe3e
tangwang
feat(search): 混合语...
|
43
|
mixed_script_merged_field_boost_scale: float = 0.6,
|
be52af70
tangwang
first commit
|
44
45
46
47
|
):
"""
Initialize query builder.
|
24e92141
tangwang
delete enable_mul...
|
48
|
Multi-language search (translation-based cross-language recall) is always enabled:
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
49
|
queries are matched against detected-language and translated target-language clauses.
|
24e92141
tangwang
delete enable_mul...
|
50
|
|
be52af70
tangwang
first commit
|
51
|
Args:
|
be52af70
tangwang
first commit
|
52
53
54
|
match_fields: Fields to search for text matching
text_embedding_field: Field name for text embeddings
image_embedding_field: Field name for image embeddings
|
13377199
tangwang
接口优化
|
55
|
source_fields: Fields to return in search results (_source includes)
|
9f96d6f3
tangwang
短query不用语义搜索
|
56
|
function_score_config: Function score configuration
|
a5a6bab8
tangwang
多语言查询优化
|
57
|
default_language: Default language to use when detection fails or returns "unknown"
|
70dab99f
tangwang
add logs
|
58
|
knn_boost: Boost value for KNN (embedding recall)
|
6823fe3e
tangwang
feat(search): 混合语...
|
59
|
mixed_script_merged_field_boost_scale: Multiply per-field ^boost for cross-script merged fields
|
be52af70
tangwang
first commit
|
60
|
"""
|
be52af70
tangwang
first commit
|
61
|
self.match_fields = match_fields
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
62
63
|
self.field_boosts = field_boosts or {}
self.multilingual_fields = multilingual_fields or [
|
a8261ece
tangwang
检索效果优化
|
64
|
"title", "brief", "description", "qanchors", "vendor", "category_path", "category_name_text"
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
65
66
67
|
]
self.shared_fields = shared_fields or ["tags", "option1_values", "option2_values", "option3_values"]
self.core_multilingual_fields = core_multilingual_fields or ["title", "brief", "vendor", "category_name_text"]
|
be52af70
tangwang
first commit
|
68
69
|
self.text_embedding_field = text_embedding_field
self.image_embedding_field = image_embedding_field
|
13377199
tangwang
接口优化
|
70
|
self.source_fields = source_fields
|
9f96d6f3
tangwang
短query不用语义搜索
|
71
|
self.function_score_config = function_score_config
|
a5a6bab8
tangwang
多语言查询优化
|
72
|
self.default_language = default_language
|
70dab99f
tangwang
add logs
|
73
|
self.knn_boost = knn_boost
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
74
75
76
77
78
|
self.base_minimum_should_match = base_minimum_should_match
self.translation_minimum_should_match = translation_minimum_should_match
self.translation_boost = float(translation_boost)
self.translation_boost_when_source_missing = float(translation_boost_when_source_missing)
self.source_boost_when_missing = float(source_boost_when_missing)
|
bcada818
tangwang
last
|
79
80
81
|
self.original_query_fallback_boost_when_translation_missing = float(
original_query_fallback_boost_when_translation_missing
)
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
82
|
self.tie_breaker_base_query = float(tie_breaker_base_query)
|
6823fe3e
tangwang
feat(search): 混合语...
|
83
|
self.mixed_script_merged_field_boost_scale = float(mixed_script_merged_field_boost_scale)
|
be52af70
tangwang
first commit
|
84
|
|
26b910bd
tangwang
refactor service ...
|
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
def _apply_source_filter(self, es_query: Dict[str, Any]) -> None:
"""
Apply tri-state _source semantics:
- None: do not set _source (return all source fields)
- []: _source=false
- [..]: _source.includes=[..]
"""
if self.source_fields is None:
return
if not isinstance(self.source_fields, list):
raise ValueError("query_config.source_fields must be null or list[str]")
if len(self.source_fields) == 0:
es_query["_source"] = False
return
es_query["_source"] = {"includes": self.source_fields}
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
|
def _split_filters_for_faceting(
self,
filters: Optional[Dict[str, Any]],
facet_configs: Optional[List[Any]]
) -> tuple:
"""
Split filters into conjunctive (query) and disjunctive (post_filter) based on facet configs.
Disjunctive filters (multi-select facets):
- Applied via post_filter (affects results but not aggregations)
- Allows showing other options in the same facet even when filtered
Conjunctive filters (standard facets):
- Applied in query.bool.filter (affects both results and aggregations)
- Standard drill-down behavior
Args:
filters: All filters from request
|
9a9b9ec5
tangwang
1. facet disjunctive
|
119
|
facet_configs: Facet configurations with disjunctive flags
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
120
121
122
123
124
125
126
127
128
129
|
Returns:
(conjunctive_filters, disjunctive_filters)
"""
if not filters or not facet_configs:
return filters or {}, {}
# Get fields that support multi-select
multi_select_fields = set()
for fc in facet_configs:
|
9a9b9ec5
tangwang
1. facet disjunctive
|
130
|
if getattr(fc, 'disjunctive', False):
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
|
# Handle specifications.xxx format
if fc.field.startswith('specifications.'):
multi_select_fields.add('specifications')
else:
multi_select_fields.add(fc.field)
# Split filters
conjunctive = {}
disjunctive = {}
for field, value in filters.items():
if field in multi_select_fields:
disjunctive[field] = value
else:
conjunctive[field] = value
return conjunctive, disjunctive
|
be52af70
tangwang
first commit
|
149
150
151
152
|
def build_query(
self,
query_text: str,
query_vector: Optional[np.ndarray] = None,
|
be52af70
tangwang
first commit
|
153
|
filters: Optional[Dict[str, Any]] = None,
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
154
|
range_filters: Optional[Dict[str, Any]] = None,
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
155
|
facet_configs: Optional[List[Any]] = None,
|
be52af70
tangwang
first commit
|
156
157
158
159
160
|
size: int = 10,
from_: int = 0,
enable_knn: bool = True,
knn_k: int = 50,
knn_num_candidates: int = 200,
|
7bc756c5
tangwang
优化 ES 查询构建
|
161
162
|
min_score: Optional[float] = None,
parsed_query: Optional[Any] = None
|
be52af70
tangwang
first commit
|
163
164
|
) -> Dict[str, Any]:
"""
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
165
|
Build complete ES query with post_filter support for multi-select faceting.
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
166
|
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
167
168
169
|
结构:filters and (text_recall or embedding_recall) + post_filter
- conjunctive_filters: 应用在 query.bool.filter(影响结果和聚合)
- disjunctive_filters: 应用在 post_filter(只影响结果,不影响聚合)
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
170
|
- text_recall: 文本相关性召回(按 search_langs 动态语言字段)
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
171
172
|
- embedding_recall: 向量召回(KNN)
- function_score: 包装召回部分,支持提权字段
|
be52af70
tangwang
first commit
|
173
174
175
176
|
Args:
query_text: Query text for BM25 matching
query_vector: Query embedding for KNN search
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
177
178
179
|
filters: Exact match filters
range_filters: Range filters for numeric fields (always applied in query)
facet_configs: Facet configurations (used to identify multi-select facets)
|
be52af70
tangwang
first commit
|
180
181
182
183
184
185
186
187
188
189
|
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
"""
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
190
|
# Boolean AST path has been removed; keep a single text strategy.
|
be52af70
tangwang
first commit
|
191
192
193
194
195
|
es_query = {
"size": size,
"from": from_
}
|
26b910bd
tangwang
refactor service ...
|
196
197
|
# Add _source filtering with explicit tri-state semantics.
self._apply_source_filter(es_query)
|
13377199
tangwang
接口优化
|
198
|
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
199
200
201
202
203
|
# 1. Build recall queries (text or embedding)
recall_clauses = []
# Text recall (always include if query_text exists)
if query_text:
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
204
205
|
# Unified text query strategy
text_query = self._build_advanced_text_query(query_text, parsed_query)
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
206
207
208
209
210
|
recall_clauses.append(text_query)
# Embedding recall (KNN - separate from query, handled below)
has_embedding = enable_knn and query_vector is not None and self.text_embedding_field
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
211
212
213
214
215
216
217
|
# 2. Split filters for multi-select faceting
conjunctive_filters, disjunctive_filters = self._split_filters_for_faceting(
filters, facet_configs
)
# Build filter clauses for query (conjunctive filters + range filters)
filter_clauses = self._build_filters(conjunctive_filters, range_filters)
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
|
# 3. Build main query structure: filters and recall
if recall_clauses:
# Combine text recalls with OR logic (if multiple)
if len(recall_clauses) == 1:
recall_query = recall_clauses[0]
else:
recall_query = {
"bool": {
"should": recall_clauses,
"minimum_should_match": 1
}
}
# Wrap recall with function_score for boosting
recall_query = self._wrap_with_function_score(recall_query)
# Combine filters and recall
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
236
237
238
|
if filter_clauses:
es_query["query"] = {
"bool": {
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
239
|
"must": [recall_query],
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
240
241
|
"filter": filter_clauses
}
|
be52af70
tangwang
first commit
|
242
|
}
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
243
|
else:
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
244
|
es_query["query"] = recall_query
|
be52af70
tangwang
first commit
|
245
|
else:
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
246
247
248
249
250
251
252
253
254
255
|
# No recall queries, only filters (match_all filtered)
if filter_clauses:
es_query["query"] = {
"bool": {
"must": [{"match_all": {}}],
"filter": filter_clauses
}
}
else:
es_query["query"] = {"match_all": {}}
|
be52af70
tangwang
first commit
|
256
|
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
257
|
# 4. Add KNN search if enabled (separate from query, ES will combine)
|
ea118f2b
tangwang
build_query:根据 qu...
|
258
|
# Adjust KNN k, num_candidates, boost by query_tokens (short query: less KNN; long: more)
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
259
|
if has_embedding:
|
ea118f2b
tangwang
build_query:根据 qu...
|
260
261
262
263
264
265
266
267
268
269
270
271
272
273
|
knn_boost = self.knn_boost
if parsed_query:
query_tokens = getattr(parsed_query, 'query_tokens', None) or []
token_count = len(query_tokens)
if token_count <= 2:
knn_k, knn_num_candidates = 30, 100
knn_boost = self.knn_boost * 0.6 # Lower weight for short queries
elif token_count >= 5:
knn_k, knn_num_candidates = 80, 300
knn_boost = self.knn_boost * 1.4 # Higher weight for long queries
else:
knn_k, knn_num_candidates = 50, 200
else:
knn_k, knn_num_candidates = 50, 200
|
be52af70
tangwang
first commit
|
274
275
276
277
|
knn_clause = {
"field": self.text_embedding_field,
"query_vector": query_vector.tolist(),
"k": knn_k,
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
278
|
"num_candidates": knn_num_candidates,
|
a47416ec
tangwang
把融合逻辑改成乘法公式,并把 ES...
|
279
|
"boost": knn_boost,
|
a8261ece
tangwang
检索效果优化
|
280
|
"_name": "knn_query",
|
be52af70
tangwang
first commit
|
281
|
}
|
7fbca0d7
tangwang
启动脚本优化
|
282
283
284
285
286
287
288
289
290
291
292
|
# Top-level knn does not inherit query.bool.filter automatically.
# Apply conjunctive + range filters here so vector recall respects hard filters.
if filter_clauses:
if len(filter_clauses) == 1:
knn_clause["filter"] = filter_clauses[0]
else:
knn_clause["filter"] = {
"bool": {
"filter": filter_clauses
}
}
|
be52af70
tangwang
first commit
|
293
294
|
es_query["knn"] = knn_clause
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
295
296
297
298
299
300
301
302
303
304
305
306
|
# 5. Add post_filter for disjunctive (multi-select) filters
if disjunctive_filters:
post_filter_clauses = self._build_filters(disjunctive_filters, None)
if post_filter_clauses:
if len(post_filter_clauses) == 1:
es_query["post_filter"] = post_filter_clauses[0]
else:
es_query["post_filter"] = {
"bool": {"filter": post_filter_clauses}
}
# 6. Add minimum score filter
|
be52af70
tangwang
first commit
|
307
308
309
310
|
if min_score is not None:
es_query["min_score"] = min_score
return es_query
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
|
def _wrap_with_function_score(self, query: Dict[str, Any]) -> Dict[str, Any]:
"""
Wrap query with function_score for boosting fields.
Args:
query: Base query to wrap
Returns:
Function score query or original query if no functions configured
"""
functions = self._build_score_functions()
# If no functions configured, return original query
if not functions:
return query
# Build function_score query
|
9f96d6f3
tangwang
短query不用语义搜索
|
329
330
331
|
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"
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
332
333
334
335
|
function_score_query = {
"function_score": {
"query": query,
"functions": functions,
|
9f96d6f3
tangwang
短query不用语义搜索
|
336
337
|
"score_mode": score_mode,
"boost_mode": boost_mode
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
338
339
340
341
342
343
344
345
346
347
348
349
350
|
}
}
return function_score_query
def _build_score_functions(self) -> List[Dict[str, Any]]:
"""
Build function_score functions from config.
Returns:
List of function score functions
"""
functions = []
|
9f96d6f3
tangwang
短query不用语义搜索
|
351
352
353
354
|
if not self.function_score_config:
return functions
config_functions = self.function_score_config.functions or []
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
|
for func_config in 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"]
}
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
}
})
return functions
|
be52af70
tangwang
first commit
|
399
400
401
402
|
def _build_text_query(self, query_text: str) -> Dict[str, Any]:
"""
Build simple text matching query (BM25).
|
be52af70
tangwang
first commit
|
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
|
Args:
query_text: Query text
Returns:
ES query clause
"""
return {
"multi_match": {
"query": query_text,
"fields": self.match_fields,
"minimum_should_match": "67%",
"tie_breaker": 0.9,
"boost": 1.0,
"_name": "base_query"
}
}
|
7bc756c5
tangwang
优化 ES 查询构建
|
420
|
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
421
422
423
|
def _format_field_with_boost(self, field_name: str, boost: float) -> str:
if abs(float(boost) - 1.0) < 1e-9:
return field_name
|
6823fe3e
tangwang
feat(search): 混合语...
|
424
|
return f"{field_name}^{round(boost, 2)}"
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
425
426
427
428
429
430
431
432
433
434
435
|
def _get_field_boost(self, base_field: str, language: Optional[str] = None) -> float:
# Language-specific override first (e.g. title.de), then base field (e.g. title)
if language:
lang_key = f"{base_field}.{language}"
if lang_key in self.field_boosts:
return float(self.field_boosts[lang_key])
if base_field in self.field_boosts:
return float(self.field_boosts[base_field])
return 1.0
|
6823fe3e
tangwang
feat(search): 混合语...
|
436
|
def _build_match_field_specs(self, language: str) -> Tuple[List[MatchFieldSpec], List[MatchFieldSpec]]:
|
7bc756c5
tangwang
优化 ES 查询构建
|
437
|
"""
|
6823fe3e
tangwang
feat(search): 混合语...
|
438
439
|
Per-language match targets as (field_path, boost). Single source of truth before string formatting.
Returns (all_fields, core_fields); core_fields are for phrase/keyword strategies elsewhere.
|
7bc756c5
tangwang
优化 ES 查询构建
|
440
|
"""
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
441
|
lang = (language or "").strip().lower()
|
6823fe3e
tangwang
feat(search): 混合语...
|
442
443
|
all_specs: List[MatchFieldSpec] = []
core_specs: List[MatchFieldSpec] = []
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
444
445
446
|
for base in self.multilingual_fields:
field = f"{base}.{lang}"
|
6823fe3e
tangwang
feat(search): 混合语...
|
447
|
all_specs.append((field, self._get_field_boost(base, lang)))
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
448
449
|
for shared in self.shared_fields:
|
6823fe3e
tangwang
feat(search): 混合语...
|
450
|
all_specs.append((shared, self._get_field_boost(shared, None)))
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
451
452
453
|
for base in self.core_multilingual_fields:
field = f"{base}.{lang}"
|
6823fe3e
tangwang
feat(search): 混合语...
|
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
|
core_specs.append((field, self._get_field_boost(base, lang)))
return all_specs, core_specs
def _format_match_field_specs(self, specs: List[MatchFieldSpec]) -> List[str]:
"""Format (field_path, boost) pairs for Elasticsearch multi_match ``fields``."""
return [self._format_field_with_boost(path, boost) for path, boost in specs]
def _merge_supplemental_lang_field_specs(
self,
specs: List[MatchFieldSpec],
supplemental_lang: str,
) -> List[MatchFieldSpec]:
"""Append supplemental-language columns; boosts multiplied by mixed_script scale."""
scale = float(self.mixed_script_merged_field_boost_scale)
extra_all, _ = self._build_match_field_specs(supplemental_lang)
seen = {path for path, _ in specs}
out = list(specs)
for path, boost in extra_all:
if path not in seen:
out.append((path, boost * scale))
seen.add(path)
return out
def _expand_match_field_specs_for_mixed_script(
self,
lang: str,
specs: List[MatchFieldSpec],
contains_chinese: bool,
contains_english: bool,
index_languages: List[str],
) -> List[MatchFieldSpec]:
"""
When the query mixes scripts, widen each clause to indexed fields for the other script
(e.g. zh clause also searches title.en when the query contains an English word token).
"""
norm = {str(x or "").strip().lower() for x in (index_languages or []) if str(x or "").strip()}
allow = norm or {"zh", "en"}
def can_use(lcode: str) -> bool:
return lcode in allow if norm else True
out = list(specs)
lnorm = (lang or "").strip().lower()
if contains_english and lnorm != "en" and can_use("en"):
out = self._merge_supplemental_lang_field_specs(out, "en")
if contains_chinese and lnorm != "zh" and can_use("zh"):
out = self._merge_supplemental_lang_field_specs(out, "zh")
return out
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
503
|
|
7bc756c5
tangwang
优化 ES 查询构建
|
504
505
506
507
508
509
510
|
def _get_embedding_field(self, language: str) -> str:
"""Get embedding field name for a language."""
# Currently using unified embedding field
return self.text_embedding_field or "title_embedding"
def _build_advanced_text_query(self, query_text: str, parsed_query: Optional[Any] = None) -> Dict[str, Any]:
"""
|
c90f80ed
tangwang
相关性优化
|
511
512
|
Build advanced text query using should clauses with primary and fallback lexical strategies.
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
513
514
515
|
Unified implementation:
- base_query: source-language clause
- translation queries: target-language clauses from search_langs/query_text_by_lang
|
7bc756c5
tangwang
优化 ES 查询构建
|
516
517
518
519
520
521
522
523
524
525
526
527
|
- KNN query: added separately in build_query
Args:
query_text: Query text
parsed_query: ParsedQuery object with analysis results
Returns:
ES bool query with should clauses
"""
should_clauses = []
# Get query analysis from parsed_query
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
528
529
530
531
|
query_text_by_lang: Dict[str, str] = {}
search_langs: List[str] = []
source_lang = self.default_language
source_in_index_languages = True
|
bcada818
tangwang
last
|
532
|
index_languages: List[str] = []
|
c90f80ed
tangwang
相关性优化
|
533
|
|
6823fe3e
tangwang
feat(search): 混合语...
|
534
535
|
contains_chinese = False
contains_english = False
|
7bc756c5
tangwang
优化 ES 查询构建
|
536
|
if parsed_query:
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
537
538
539
540
541
542
543
|
query_text_by_lang = getattr(parsed_query, "query_text_by_lang", None) or {}
search_langs = getattr(parsed_query, "search_langs", None) or []
detected_lang = getattr(parsed_query, "detected_language", None)
source_lang = detected_lang if detected_lang and detected_lang != "unknown" else self.default_language
source_in_index_languages = bool(
getattr(parsed_query, "source_in_index_languages", True)
)
|
bcada818
tangwang
last
|
544
|
index_languages = getattr(parsed_query, "index_languages", None) or []
|
6823fe3e
tangwang
feat(search): 混合语...
|
545
546
|
contains_chinese = bool(getattr(parsed_query, "contains_chinese", False))
contains_english = bool(getattr(parsed_query, "contains_english", False))
|
c90f80ed
tangwang
相关性优化
|
547
|
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
548
549
550
551
552
553
|
if not query_text_by_lang:
query_text_by_lang = {source_lang: query_text}
if source_lang not in query_text_by_lang and query_text:
query_text_by_lang[source_lang] = query_text
if not search_langs:
search_langs = list(query_text_by_lang.keys())
|
c90f80ed
tangwang
相关性优化
|
554
|
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
555
556
557
558
559
|
# Base + translated clauses based on language plan.
for lang in search_langs:
lang_query = query_text_by_lang.get(lang)
if not lang_query:
continue
|
6823fe3e
tangwang
feat(search): 混合语...
|
560
561
562
563
564
565
566
567
568
|
all_specs, _ = self._build_match_field_specs(lang)
expanded_specs = self._expand_match_field_specs_for_mixed_script(
lang,
all_specs,
contains_chinese,
contains_english,
index_languages,
)
match_fields = self._format_match_field_specs(expanded_specs)
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
|
if not match_fields:
continue
is_source = (lang == source_lang)
clause_boost = 1.0
clause_name = "base_query" if is_source else f"base_query_trans_{lang}"
minimum_should_match = (
self.base_minimum_should_match if is_source else self.translation_minimum_should_match
)
if is_source and not source_in_index_languages:
clause_boost = self.source_boost_when_missing
elif not is_source:
clause_boost = (
self.translation_boost
if source_in_index_languages
else self.translation_boost_when_source_missing
)
clause = {
|
7bc756c5
tangwang
优化 ES 查询构建
|
588
|
"multi_match": {
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
589
|
"_name": clause_name,
|
7bc756c5
tangwang
优化 ES 查询构建
|
590
591
|
"fields": match_fields,
"minimum_should_match": minimum_should_match,
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
592
593
|
"query": lang_query,
"tie_breaker": self.tie_breaker_base_query,
|
7bc756c5
tangwang
优化 ES 查询构建
|
594
|
}
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
595
596
597
598
599
|
}
if abs(clause_boost - 1.0) > 1e-9:
clause["multi_match"]["boost"] = clause_boost
should_clauses.append({
"multi_match": clause["multi_match"]
|
7bc756c5
tangwang
优化 ES 查询构建
|
600
|
})
|
ea118f2b
tangwang
build_query:根据 qu...
|
601
|
|
bcada818
tangwang
last
|
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
|
# Fallback: source language is not indexed and translation for some index languages is missing.
# Use original query text on missing index-language fields with a low boost.
if not source_in_index_languages and query_text and index_languages:
normalized_index_langs: List[str] = []
seen_langs = set()
for lang in index_languages:
norm_lang = str(lang or "").strip().lower()
if not norm_lang or norm_lang in seen_langs:
continue
seen_langs.add(norm_lang)
normalized_index_langs.append(norm_lang)
for lang in normalized_index_langs:
if lang == source_lang:
continue
if lang in query_text_by_lang:
continue
|
6823fe3e
tangwang
feat(search): 混合语...
|
619
620
621
622
623
624
625
626
627
|
fb_specs, _ = self._build_match_field_specs(lang)
expanded_fb = self._expand_match_field_specs_for_mixed_script(
lang,
fb_specs,
contains_chinese,
contains_english,
index_languages,
)
match_fields = self._format_match_field_specs(expanded_fb)
|
bcada818
tangwang
last
|
628
629
630
631
632
633
634
635
636
637
638
639
640
|
if not match_fields:
continue
should_clauses.append({
"multi_match": {
"_name": f"fallback_original_query_{lang}",
"query": query_text,
"fields": match_fields,
"minimum_should_match": self.translation_minimum_should_match,
"tie_breaker": self.tie_breaker_base_query,
"boost": self.original_query_fallback_boost_when_translation_missing,
}
})
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
641
642
643
644
645
646
647
648
649
650
651
652
653
|
# Fallback to a simple query when language fields cannot be resolved.
if not should_clauses:
fallback_fields = self.match_fields or ["title.en^1.0"]
return {
"multi_match": {
"_name": "base_query_fallback",
"query": query_text,
"fields": fallback_fields,
"minimum_should_match": self.base_minimum_should_match,
"tie_breaker": self.tie_breaker_base_query,
}
}
|
7bc756c5
tangwang
优化 ES 查询构建
|
654
655
656
657
658
659
660
661
662
663
|
# Return bool query with should clauses
if len(should_clauses) == 1:
return should_clauses[0]
return {
"bool": {
"should": should_clauses,
"minimum_should_match": 1
}
}
|
be52af70
tangwang
first commit
|
664
|
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
665
666
667
|
def _build_filters(
self,
filters: Optional[Dict[str, Any]] = None,
|
43f1139f
tangwang
refactor: ES查询结构重...
|
668
|
range_filters: Optional[Dict[str, 'RangeFilter']] = None
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
669
|
) -> List[Dict[str, Any]]:
|
be52af70
tangwang
first commit
|
670
|
"""
|
43f1139f
tangwang
refactor: ES查询结构重...
|
671
|
构建过滤子句。
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
672
|
|
be52af70
tangwang
first commit
|
673
|
Args:
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
674
|
filters: 精确匹配过滤器字典
|
43f1139f
tangwang
refactor: ES查询结构重...
|
675
|
range_filters: 范围过滤器(Dict[str, RangeFilter],RangeFilter 是 Pydantic 模型)
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
676
|
|
be52af70
tangwang
first commit
|
677
|
Returns:
|
43f1139f
tangwang
refactor: ES查询结构重...
|
678
|
ES filter 子句列表
|
be52af70
tangwang
first commit
|
679
680
|
"""
filter_clauses = []
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
681
682
683
684
|
# 1. 处理精确匹配过滤
if filters:
for field, value in filters.items():
|
f7d3cf70
tangwang
更新文档
|
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
|
# 特殊处理:specifications 嵌套过滤
if field == "specifications":
if isinstance(value, dict):
# 单个规格过滤:{"name": "color", "value": "green"}
name = value.get("name")
spec_value = value.get("value")
if name and spec_value:
filter_clauses.append({
"nested": {
"path": "specifications",
"query": {
"bool": {
"must": [
{"term": {"specifications.name": name}},
{"term": {"specifications.value": spec_value}}
]
}
}
}
})
elif isinstance(value, list):
|
85f08823
tangwang
过滤逻辑
|
706
707
708
709
710
|
# 多个规格过滤:按 name 分组,相同维度 OR,不同维度 AND
# 例如:[{"name": "size", "value": "3"}, {"name": "size", "value": "4"}, {"name": "color", "value": "green"}]
# 应该生成:(size=3 OR size=4) AND color=green
from collections import defaultdict
specs_by_name = defaultdict(list)
|
f7d3cf70
tangwang
更新文档
|
711
712
713
714
715
|
for spec in value:
if isinstance(spec, dict):
name = spec.get("name")
spec_value = spec.get("value")
if name and spec_value:
|
85f08823
tangwang
过滤逻辑
|
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
|
specs_by_name[name].append(spec_value)
# 为每个 name 维度生成一个过滤子句
for name, values in specs_by_name.items():
if len(values) == 1:
# 单个值,直接生成 term 查询
filter_clauses.append({
"nested": {
"path": "specifications",
"query": {
"bool": {
"must": [
{"term": {"specifications.name": name}},
{"term": {"specifications.value": values[0]}}
]
|
f7d3cf70
tangwang
更新文档
|
731
732
|
}
}
|
85f08823
tangwang
过滤逻辑
|
733
734
735
736
737
738
739
740
741
742
743
744
745
|
}
})
else:
# 多个值,使用 should (OR) 连接
should_clauses = []
for spec_value in values:
should_clauses.append({
"bool": {
"must": [
{"term": {"specifications.name": name}},
{"term": {"specifications.value": spec_value}}
]
}
|
f7d3cf70
tangwang
更新文档
|
746
|
})
|
85f08823
tangwang
过滤逻辑
|
747
748
749
750
751
752
753
754
755
756
757
|
filter_clauses.append({
"nested": {
"path": "specifications",
"query": {
"bool": {
"should": should_clauses,
"minimum_should_match": 1
}
}
}
})
|
f7d3cf70
tangwang
更新文档
|
758
759
|
continue
|
985d7fe3
tangwang
为 filters 中所有字段加上...
|
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
|
# *_all 语义:多值时为 AND(必须同时匹配所有值)
if field.endswith("_all"):
es_field = field[:-4] # 去掉 _all 后缀
if es_field == "specifications" and isinstance(value, list):
# specifications_all: 列表内每个规格条件都要满足(AND)
must_nested = []
for spec in value:
if isinstance(spec, dict):
name = spec.get("name")
spec_value = spec.get("value")
if name and spec_value:
must_nested.append({
"nested": {
"path": "specifications",
"query": {
"bool": {
"must": [
{"term": {"specifications.name": name}},
{"term": {"specifications.value": spec_value}}
]
}
}
}
})
if must_nested:
filter_clauses.append({"bool": {"must": must_nested}})
else:
# 普通字段 _all:多值用 must + 多个 term
if isinstance(value, list):
if value:
filter_clauses.append({
"bool": {
"must": [{"term": {es_field: v}} for v in value]
}
})
else:
filter_clauses.append({"term": {es_field: value}})
continue
# 普通字段过滤(默认多值为 OR)
|
c86c8237
tangwang
支持聚合。过滤项补充了逻辑,但是有问题
|
800
|
if isinstance(value, list):
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
801
|
# 多值匹配(OR)
|
be52af70
tangwang
first commit
|
802
|
filter_clauses.append({
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
803
|
"terms": {field: value}
|
be52af70
tangwang
first commit
|
804
|
})
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
805
806
807
808
809
810
|
else:
# 单值精确匹配
filter_clauses.append({
"term": {field: value}
})
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
811
|
# 2. 处理范围过滤(支持 RangeFilter Pydantic 模型或字典)
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
812
|
if range_filters:
|
43f1139f
tangwang
refactor: ES查询结构重...
|
813
|
for field, range_filter in range_filters.items():
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
814
815
816
817
818
819
820
821
822
823
|
# 支持 Pydantic 模型或字典格式
if hasattr(range_filter, 'model_dump'):
# Pydantic 模型
range_dict = range_filter.model_dump(exclude_none=True)
elif isinstance(range_filter, dict):
# 已经是字典格式
range_dict = {k: v for k, v in range_filter.items() if v is not None}
else:
# 其他格式,跳过
continue
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
824
|
|
43f1139f
tangwang
refactor: ES查询结构重...
|
825
|
if range_dict:
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
826
|
filter_clauses.append({
|
43f1139f
tangwang
refactor: ES查询结构重...
|
827
|
"range": {field: range_dict}
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
828
829
|
})
|
be52af70
tangwang
first commit
|
830
831
|
return filter_clauses
|
c86c8237
tangwang
支持聚合。过滤项补充了逻辑,但是有问题
|
832
833
834
835
836
837
838
839
840
841
842
|
def add_sorting(
self,
es_query: Dict[str, Any],
sort_by: str,
sort_order: str = "desc"
) -> Dict[str, Any]:
"""
Add sorting to ES query.
Args:
es_query: Existing ES query
|
13320ac6
tangwang
分面接口修改:
|
843
|
sort_by: Field name for sorting (支持 'price' 自动映射)
|
c86c8237
tangwang
支持聚合。过滤项补充了逻辑,但是有问题
|
844
845
846
847
848
849
850
851
852
853
854
|
sort_order: Sort order: 'asc' or 'desc'
Returns:
Modified ES query
"""
if not sort_by:
return es_query
if not sort_order:
sort_order = "desc"
|
13320ac6
tangwang
分面接口修改:
|
855
856
857
858
859
860
861
|
# Auto-map 'price' to 'min_price' or 'max_price' based on sort_order
if sort_by == "price":
if sort_order.lower() == "asc":
sort_by = "min_price" # 价格从低到高
else:
sort_by = "max_price" # 价格从高到低
|
c86c8237
tangwang
支持聚合。过滤项补充了逻辑,但是有问题
|
862
863
864
865
866
867
868
869
870
871
872
873
874
|
if "sort" not in es_query:
es_query["sort"] = []
# Add the specified sort
sort_field = {
sort_by: {
"order": sort_order.lower()
}
}
es_query["sort"].append(sort_field)
return es_query
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
875
|
def build_facets(
|
be52af70
tangwang
first commit
|
876
|
self,
|
d8ca3b13
tangwang
修复 分面结果 各个选项结果数 和...
|
877
878
|
facet_configs: Optional[List['FacetConfig']] = None,
use_reverse_nested: bool = True
|
be52af70
tangwang
first commit
|
879
880
|
) -> Dict[str, Any]:
"""
|
ff5325fa
tangwang
修复:直接在 Searcher 层...
|
881
|
构建分面聚合。
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
882
|
|
be52af70
tangwang
first commit
|
883
|
Args:
|
13320ac6
tangwang
分面接口修改:
|
884
|
facet_configs: 分面配置对象列表
|
d8ca3b13
tangwang
修复 分面结果 各个选项结果数 和...
|
885
886
|
use_reverse_nested: 是否使用 reverse_nested 统计产品数量(默认 True)
如果为 False,将统计嵌套文档数量(性能更好但计数可能不准确)
|
13320ac6
tangwang
分面接口修改:
|
887
888
889
890
891
|
支持的字段类型:
- 普通字段: 如 "category1_name"(terms 或 range 类型)
- specifications: "specifications"(返回所有规格名称及其值)
- specifications.{name}: 如 "specifications.color"(返回指定规格名称的值)
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
892
|
|
be52af70
tangwang
first commit
|
893
|
Returns:
|
ff5325fa
tangwang
修复:直接在 Searcher 层...
|
894
|
ES aggregations 字典
|
d8ca3b13
tangwang
修复 分面结果 各个选项结果数 和...
|
895
896
897
898
|
性能说明:
- use_reverse_nested=True: 统计产品数量,准确性高但性能略差(通常影响 < 20%)
- use_reverse_nested=False: 统计嵌套文档数量,性能更好但计数可能不准确
|
be52af70
tangwang
first commit
|
899
|
"""
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
900
901
902
903
904
905
|
if not facet_configs:
return {}
aggs = {}
for config in facet_configs:
|
13320ac6
tangwang
分面接口修改:
|
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
|
field = config.field
size = config.size
facet_type = config.type
# 处理 specifications(所有规格名称)
if field == "specifications":
aggs["specifications_facet"] = {
"nested": {"path": "specifications"},
"aggs": {
"by_name": {
"terms": {
"field": "specifications.name",
"size": 20,
"order": {"_count": "desc"}
},
"aggs": {
"value_counts": {
"terms": {
"field": "specifications.value",
"size": size,
"order": {"_count": "desc"}
|
bf89b597
tangwang
feat(search): ada...
|
927
928
929
930
931
|
}
}
}
}
}
|
13320ac6
tangwang
分面接口修改:
|
932
933
934
935
936
937
938
|
}
continue
# 处理 specifications.{name}(指定规格名称)
if field.startswith("specifications."):
name = field[len("specifications."):]
agg_name = f"specifications_{name}_facet"
|
d8ca3b13
tangwang
修复 分面结果 各个选项结果数 和...
|
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
|
# 使用 reverse_nested 统计产品(父文档)数量,而不是规格条目(嵌套文档)数量
# 这样可以确保分面计数反映实际的产品数量,与搜索结果数量一致
base_value_counts = {
"terms": {
"field": "specifications.value",
"size": size,
"order": {"_count": "desc"}
}
}
# 如果启用 reverse_nested,添加子聚合统计产品数量
if use_reverse_nested:
base_value_counts["aggs"] = {
"product_count": {
"reverse_nested": {}
}
}
|
13320ac6
tangwang
分面接口修改:
|
957
958
959
960
961
962
|
aggs[agg_name] = {
"nested": {"path": "specifications"},
"aggs": {
"filter_by_name": {
"filter": {"term": {"specifications.name": name}},
"aggs": {
|
d8ca3b13
tangwang
修复 分面结果 各个选项结果数 和...
|
963
|
"value_counts": base_value_counts
|
f7d3cf70
tangwang
更新文档
|
964
965
966
|
}
}
}
|
13320ac6
tangwang
分面接口修改:
|
967
968
969
970
971
|
}
continue
# 处理普通字段
agg_name = f"{field}_facet"
|
bf89b597
tangwang
feat(search): ada...
|
972
|
|
13320ac6
tangwang
分面接口修改:
|
973
|
if facet_type == 'terms':
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
974
975
976
|
aggs[agg_name] = {
"terms": {
"field": field,
|
13320ac6
tangwang
分面接口修改:
|
977
|
"size": size,
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
978
979
|
"order": {"_count": "desc"}
}
|
be52af70
tangwang
first commit
|
980
|
}
|
13320ac6
tangwang
分面接口修改:
|
981
982
|
elif facet_type == 'range':
if config.ranges:
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
983
|
aggs[agg_name] = {
|
13320ac6
tangwang
分面接口修改:
|
984
|
"range": {
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
985
|
"field": field,
|
13320ac6
tangwang
分面接口修改:
|
986
|
"ranges": config.ranges
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
987
988
|
}
}
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
989
990
|
return aggs
|