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
|
"""
|
47452e1d
tangwang
feat(search): 支持可...
|
11
|
from dataclasses import dataclass
|
35da3813
tangwang
中英混写query的优化逻辑,不适...
|
12
|
from typing import Dict, Any, List, Optional, Tuple
|
6823fe3e
tangwang
feat(search): 混合语...
|
13
|
|
be52af70
tangwang
first commit
|
14
|
import numpy as np
|
9f96d6f3
tangwang
短query不用语义搜索
|
15
|
from config import FunctionScoreConfig
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
16
|
from query.keyword_extractor import KEYWORDS_QUERY_BASE_KEY
|
be52af70
tangwang
first commit
|
17
|
|
be52af70
tangwang
first commit
|
18
19
20
21
22
23
|
class ESQueryBuilder:
"""Builds Elasticsearch DSL queries."""
def __init__(
self,
|
be52af70
tangwang
first commit
|
24
|
match_fields: List[str],
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
25
26
27
28
|
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
|
29
|
text_embedding_field: Optional[str] = None,
|
13377199
tangwang
接口优化
|
30
|
image_embedding_field: Optional[str] = None,
|
9f96d6f3
tangwang
短query不用语义搜索
|
31
|
source_fields: Optional[List[str]] = None,
|
7bc756c5
tangwang
优化 ES 查询构建
|
32
|
function_score_config: Optional[FunctionScoreConfig] = None,
|
2739b281
tangwang
多语言索引调整
|
33
|
default_language: str = "en",
|
ed13851c
tangwang
图片文本两个knn召回相关参数配置
|
34
35
36
37
38
39
40
41
|
knn_text_boost: float = 20.0,
knn_image_boost: float = 20.0,
knn_text_k: int = 120,
knn_text_num_candidates: int = 400,
knn_text_k_long: int = 160,
knn_text_num_candidates_long: int = 500,
knn_image_k: int = 120,
knn_image_num_candidates: int = 400,
|
418b6a4a
tangwang
调参
|
42
43
44
|
base_minimum_should_match: str = "66%",
translation_minimum_should_match: str = "66%",
keywords_minimum_should_match: str = "60%",
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
45
|
translation_boost: float = 0.4,
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
46
|
tie_breaker_base_query: float = 0.9,
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
47
48
|
best_fields_boosts: Optional[Dict[str, float]] = None,
best_fields_clause_boost: float = 2.0,
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
49
|
phrase_field_boosts: Optional[Dict[str, float]] = None,
|
69881ecb
tangwang
相关性调参、enrich内容解析优化
|
50
|
phrase_match_base_fields: Optional[Tuple[str, ...]] = None,
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
51
52
|
phrase_match_slop: int = 0,
phrase_match_tie_breaker: float = 0.0,
|
69881ecb
tangwang
相关性调参、enrich内容解析优化
|
53
|
phrase_match_boost: float = 3.0,
|
be52af70
tangwang
first commit
|
54
55
56
57
|
):
"""
Initialize query builder.
|
24e92141
tangwang
delete enable_mul...
|
58
|
Multi-language search (translation-based cross-language recall) is always enabled:
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
59
|
queries are matched against detected-language and translated target-language clauses.
|
24e92141
tangwang
delete enable_mul...
|
60
|
|
be52af70
tangwang
first commit
|
61
|
Args:
|
be52af70
tangwang
first commit
|
62
63
64
|
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
接口优化
|
65
|
source_fields: Fields to return in search results (_source includes)
|
9f96d6f3
tangwang
短query不用语义搜索
|
66
|
function_score_config: Function score configuration
|
a5a6bab8
tangwang
多语言查询优化
|
67
|
default_language: Default language to use when detection fails or returns "unknown"
|
ed13851c
tangwang
图片文本两个knn召回相关参数配置
|
68
69
|
knn_text_boost: Boost for text-embedding KNN clause
knn_image_boost: Boost for image-embedding KNN clause
|
be52af70
tangwang
first commit
|
70
|
"""
|
be52af70
tangwang
first commit
|
71
|
self.match_fields = match_fields
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
72
|
self.field_boosts = field_boosts or {}
|
445496cd
tangwang
fix last up: 每个翻译...
|
73
74
75
|
self.multilingual_fields = multilingual_fields or []
self.shared_fields = shared_fields or []
self.core_multilingual_fields = core_multilingual_fields or []
|
be52af70
tangwang
first commit
|
76
77
|
self.text_embedding_field = text_embedding_field
self.image_embedding_field = image_embedding_field
|
13377199
tangwang
接口优化
|
78
|
self.source_fields = source_fields
|
9f96d6f3
tangwang
短query不用语义搜索
|
79
|
self.function_score_config = function_score_config
|
a5a6bab8
tangwang
多语言查询优化
|
80
|
self.default_language = default_language
|
ed13851c
tangwang
图片文本两个knn召回相关参数配置
|
81
82
83
84
85
86
87
88
|
self.knn_text_boost = float(knn_text_boost)
self.knn_image_boost = float(knn_image_boost)
self.knn_text_k = int(knn_text_k)
self.knn_text_num_candidates = int(knn_text_num_candidates)
self.knn_text_k_long = int(knn_text_k_long)
self.knn_text_num_candidates_long = int(knn_text_num_candidates_long)
self.knn_image_k = int(knn_image_k)
self.knn_image_num_candidates = int(knn_image_num_candidates)
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
89
90
|
self.base_minimum_should_match = base_minimum_should_match
self.translation_minimum_should_match = translation_minimum_should_match
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
91
|
self.keywords_minimum_should_match = str(keywords_minimum_should_match)
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
92
|
self.translation_boost = float(translation_boost)
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
93
|
self.tie_breaker_base_query = float(tie_breaker_base_query)
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
default_best_fields = {
base: self._get_field_boost(base)
for base in self.core_multilingual_fields
if base in self.multilingual_fields
}
self.best_fields_boosts = {
str(base): float(boost)
for base, boost in (best_fields_boosts or default_best_fields).items()
}
self.best_fields_clause_boost = float(best_fields_clause_boost)
default_phrase_base_fields = tuple(phrase_match_base_fields or ("title", "qanchors"))
default_phrase_fields = {
base: self._get_field_boost(base)
for base in default_phrase_base_fields
if base in self.multilingual_fields
}
self.phrase_field_boosts = {
str(base): float(boost)
for base, boost in (phrase_field_boosts or default_phrase_fields).items()
}
|
69881ecb
tangwang
相关性调参、enrich内容解析优化
|
114
115
116
|
self.phrase_match_slop = int(phrase_match_slop)
self.phrase_match_tie_breaker = float(phrase_match_tie_breaker)
self.phrase_match_boost = float(phrase_match_boost)
|
be52af70
tangwang
first commit
|
117
|
|
47452e1d
tangwang
feat(search): 支持可...
|
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
|
@dataclass(frozen=True)
class KNNClausePlan:
field: str
boost: float
k: Optional[int] = None
num_candidates: Optional[int] = None
nested_path: Optional[str] = None
@staticmethod
def _vector_to_list(vector: Any) -> List[float]:
if vector is None:
return []
if hasattr(vector, "tolist"):
values = vector.tolist()
else:
values = list(vector)
return [float(v) for v in values]
@staticmethod
def _query_token_count(parsed_query: Optional[Any]) -> int:
if parsed_query is None:
return 0
query_tokens = getattr(parsed_query, "query_tokens", None) or []
return len(query_tokens)
def get_text_knn_plan(self, parsed_query: Optional[Any] = None) -> Optional[KNNClausePlan]:
if not self.text_embedding_field:
return None
boost = self.knn_text_boost
final_knn_k = self.knn_text_k
final_knn_num_candidates = self.knn_text_num_candidates
if self._query_token_count(parsed_query) >= 5:
final_knn_k = self.knn_text_k_long
final_knn_num_candidates = self.knn_text_num_candidates_long
boost = self.knn_text_boost * 1.4
return self.KNNClausePlan(
field=str(self.text_embedding_field),
boost=float(boost),
k=int(final_knn_k),
num_candidates=int(final_knn_num_candidates),
)
def get_image_knn_plan(self) -> Optional[KNNClausePlan]:
if not self.image_embedding_field:
return None
nested_path, _, _ = str(self.image_embedding_field).rpartition(".")
return self.KNNClausePlan(
field=str(self.image_embedding_field),
boost=float(self.knn_image_boost),
k=int(self.knn_image_k),
num_candidates=int(self.knn_image_num_candidates),
nested_path=nested_path or None,
)
def build_text_knn_clause(
self,
query_vector: Any,
*,
parsed_query: Optional[Any] = None,
query_name: str = "knn_query",
) -> Optional[Dict[str, Any]]:
plan = self.get_text_knn_plan(parsed_query)
if plan is None or query_vector is None:
return None
return {
"knn": {
"field": plan.field,
"query_vector": self._vector_to_list(query_vector),
"k": plan.k,
"num_candidates": plan.num_candidates,
"boost": plan.boost,
"_name": query_name,
}
}
def build_image_knn_clause(
self,
image_query_vector: Any,
*,
query_name: str = "image_knn_query",
) -> Optional[Dict[str, Any]]:
plan = self.get_image_knn_plan()
if plan is None or image_query_vector is None:
return None
image_knn_query = {
"field": plan.field,
"query_vector": self._vector_to_list(image_query_vector),
"k": plan.k,
"num_candidates": plan.num_candidates,
"boost": plan.boost,
}
if plan.nested_path:
return {
"nested": {
"path": plan.nested_path,
"_name": query_name,
"query": {"knn": image_knn_query},
"score_mode": "max",
|
5c9baf91
tangwang
feat(search): 款式意...
|
216
217
218
219
220
221
222
|
# Expose the best-matching image entry (url, score) so SKU selection
# can promote the SKU whose image_src matches the winning url.
"inner_hits": {
"name": f"{query_name}_hits",
"size": 1,
"_source": ["url"],
},
|
47452e1d
tangwang
feat(search): 支持可...
|
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
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
284
285
|
}
}
return {
"knn": {
**image_knn_query,
"_name": query_name,
}
}
def build_exact_text_knn_rescore_clause(
self,
query_vector: Any,
*,
parsed_query: Optional[Any] = None,
query_name: str = "exact_text_knn_query",
) -> Optional[Dict[str, Any]]:
plan = self.get_text_knn_plan(parsed_query)
if plan is None or query_vector is None:
return None
return {
"script_score": {
"_name": query_name,
"query": {"exists": {"field": plan.field}},
"script": {
"source": (
f"((dotProduct(params.query_vector, '{plan.field}') + 1.0) / 2.0) * params.boost"
),
"params": {
"query_vector": self._vector_to_list(query_vector),
"boost": float(plan.boost),
},
},
}
}
def build_exact_image_knn_rescore_clause(
self,
image_query_vector: Any,
*,
query_name: str = "exact_image_knn_query",
) -> Optional[Dict[str, Any]]:
plan = self.get_image_knn_plan()
if plan is None or image_query_vector is None:
return None
script_score_query = {
"query": {"exists": {"field": plan.field}},
"script": {
"source": (
f"((dotProduct(params.query_vector, '{plan.field}') + 1.0) / 2.0) * params.boost"
),
"params": {
"query_vector": self._vector_to_list(image_query_vector),
"boost": float(plan.boost),
},
},
}
if plan.nested_path:
return {
"nested": {
"path": plan.nested_path,
"_name": query_name,
"score_mode": "max",
"query": {"script_score": script_score_query},
|
5c9baf91
tangwang
feat(search): 款式意...
|
286
287
288
289
290
291
292
|
# Same rationale as build_image_knn_clause: carry the winning url + score
# so downstream SKU selection can consume it without a second ES round-trip.
"inner_hits": {
"name": f"{query_name}_hits",
"size": 1,
"_source": ["url"],
},
|
47452e1d
tangwang
feat(search): 支持可...
|
293
294
295
296
|
}
}
return {"script_score": {"_name": query_name, **script_score_query}}
|
26b910bd
tangwang
refactor service ...
|
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
|
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...
|
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
|
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
|
331
|
facet_configs: Facet configurations with disjunctive flags
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
332
333
334
335
336
337
338
339
340
341
|
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
|
342
|
if getattr(fc, 'disjunctive', False):
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
|
# 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
|
361
362
363
364
|
def build_query(
self,
query_text: str,
query_vector: Optional[np.ndarray] = None,
|
dc403578
tangwang
多模态搜索
|
365
|
image_query_vector: Optional[np.ndarray] = None,
|
be52af70
tangwang
first commit
|
366
|
filters: Optional[Dict[str, Any]] = None,
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
367
|
range_filters: Optional[Dict[str, Any]] = None,
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
368
|
facet_configs: Optional[List[Any]] = None,
|
be52af70
tangwang
first commit
|
369
370
371
|
size: int = 10,
from_: int = 0,
enable_knn: bool = True,
|
7bc756c5
tangwang
优化 ES 查询构建
|
372
|
min_score: Optional[float] = None,
|
ef5baa86
tangwang
混杂语言处理
|
373
|
parsed_query: Optional[Any] = None,
|
be52af70
tangwang
first commit
|
374
375
|
) -> Dict[str, Any]:
"""
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
376
|
Build complete ES query with post_filter support for multi-select faceting.
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
377
|
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
378
379
380
|
结构:filters and (text_recall or embedding_recall) + post_filter
- conjunctive_filters: 应用在 query.bool.filter(影响结果和聚合)
- disjunctive_filters: 应用在 post_filter(只影响结果,不影响聚合)
|
0536222c
tangwang
query parser优化
|
381
|
- text_recall: 文本相关性召回(按实际 clause 语言动态字段)
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
382
383
|
- embedding_recall: 向量召回(KNN)
- function_score: 包装召回部分,支持提权字段
|
be52af70
tangwang
first commit
|
384
385
386
387
|
Args:
query_text: Query text for BM25 matching
query_vector: Query embedding for KNN search
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
388
389
390
|
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
|
391
392
393
|
size: Number of results
from_: Offset for pagination
enable_knn: Whether to use KNN search
|
be52af70
tangwang
first commit
|
394
395
396
397
398
|
min_score: Minimum score threshold
Returns:
ES query DSL dictionary
"""
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
399
|
# Boolean AST path has been removed; keep a single text strategy.
|
be52af70
tangwang
first commit
|
400
401
402
403
404
|
es_query = {
"size": size,
"from": from_
}
|
26b910bd
tangwang
refactor service ...
|
405
406
|
# Add _source filtering with explicit tri-state semantics.
self._apply_source_filter(es_query)
|
13377199
tangwang
接口优化
|
407
|
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
408
409
|
# 1. Build recall queries (text or embedding)
recall_clauses = []
|
dc403578
tangwang
多模态搜索
|
410
|
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
411
412
|
# Text recall (always include if query_text exists)
if query_text:
|
dc403578
tangwang
多模态搜索
|
413
414
415
|
recall_clauses.extend(self._build_advanced_text_query(query_text, parsed_query))
# Embedding recall
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
416
|
has_embedding = enable_knn and query_vector is not None and self.text_embedding_field
|
dc403578
tangwang
多模态搜索
|
417
|
has_image_embedding = enable_knn and image_query_vector is not None and self.image_embedding_field
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
418
|
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
419
420
421
422
423
424
425
|
# 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)
|
74fdf9bd
tangwang
1.
|
426
427
428
429
|
product_title_exclusion_filter = self._build_product_title_exclusion_filter(parsed_query)
if product_title_exclusion_filter:
filter_clauses.append(product_title_exclusion_filter)
|
dc403578
tangwang
多模态搜索
|
430
|
# 3. Add KNN search clauses alongside lexical clauses under the same bool.should
|
ed13851c
tangwang
图片文本两个knn召回相关参数配置
|
431
|
# Text KNN: k / num_candidates from config; long queries use *_long and higher boost
|
dc403578
tangwang
多模态搜索
|
432
|
if has_embedding:
|
47452e1d
tangwang
feat(search): 支持可...
|
433
434
435
436
437
438
439
|
text_knn_clause = self.build_text_knn_clause(
query_vector,
parsed_query=parsed_query,
query_name="knn_query",
)
if text_knn_clause:
recall_clauses.append(text_knn_clause)
|
dc403578
tangwang
多模态搜索
|
440
441
|
if has_image_embedding:
|
47452e1d
tangwang
feat(search): 支持可...
|
442
443
444
445
446
447
|
image_knn_clause = self.build_image_knn_clause(
image_query_vector,
query_name="image_knn_query",
)
if image_knn_clause:
recall_clauses.append(image_knn_clause)
|
dc403578
tangwang
多模态搜索
|
448
449
|
# 4. Build main query structure: filters and recall
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
450
|
if recall_clauses:
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
451
452
453
454
455
456
457
458
459
|
if len(recall_clauses) == 1:
recall_query = recall_clauses[0]
else:
recall_query = {
"bool": {
"should": recall_clauses,
"minimum_should_match": 1
}
}
|
dc403578
tangwang
多模态搜索
|
460
|
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
461
|
recall_query = self._wrap_with_function_score(recall_query)
|
dc403578
tangwang
多模态搜索
|
462
|
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
463
464
465
|
if filter_clauses:
es_query["query"] = {
"bool": {
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
466
|
"must": [recall_query],
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
467
468
|
"filter": filter_clauses
}
|
be52af70
tangwang
first commit
|
469
|
}
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
470
|
else:
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
471
|
es_query["query"] = recall_query
|
be52af70
tangwang
first commit
|
472
|
else:
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
473
474
475
476
477
478
479
480
481
|
if filter_clauses:
es_query["query"] = {
"bool": {
"must": [{"match_all": {}}],
"filter": filter_clauses
}
}
else:
es_query["query"] = {"match_all": {}}
|
be52af70
tangwang
first commit
|
482
|
|
c581becd
tangwang
feat: 实现 Multi-Se...
|
483
484
485
486
487
488
489
490
491
492
493
494
|
# 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
|
495
496
497
498
|
if min_score is not None:
es_query["min_score"] = min_score
return es_query
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
|
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不用语义搜索
|
517
518
519
|
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...
|
520
521
522
523
|
function_score_query = {
"function_score": {
"query": query,
"functions": functions,
|
9f96d6f3
tangwang
短query不用语义搜索
|
524
525
|
"score_mode": score_mode,
"boost_mode": boost_mode
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
526
527
528
529
530
531
532
533
534
535
536
537
538
|
}
}
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不用语义搜索
|
539
540
541
542
|
if not self.function_score_config:
return functions
config_functions = self.function_score_config.functions or []
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
|
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
|
587
|
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
588
589
590
|
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): 混合语...
|
591
|
return f"{field_name}^{round(boost, 2)}"
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
592
593
594
595
596
597
598
599
600
601
602
|
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
|
35da3813
tangwang
中英混写query的优化逻辑,不适...
|
603
|
def _match_field_strings(
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
604
605
606
607
608
609
|
self,
language: str,
*,
multilingual_fields: Optional[List[str]] = None,
shared_fields: Optional[List[str]] = None,
boost_overrides: Optional[Dict[str, float]] = None,
|
35da3813
tangwang
中英混写query的优化逻辑,不适...
|
610
611
|
) -> List[str]:
"""Build ``multi_match`` / ``combined_fields`` field entries for one language code."""
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
612
|
lang = (language or "").strip().lower()
|
35da3813
tangwang
中英混写query的优化逻辑,不适...
|
613
|
text_bases = multilingual_fields if multilingual_fields is not None else self.multilingual_fields
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
614
615
|
term_fields = shared_fields if shared_fields is not None else self.shared_fields
overrides = boost_overrides or {}
|
35da3813
tangwang
中英混写query的优化逻辑,不适...
|
616
617
618
|
out: List[str] = []
for base in text_bases:
path = f"{base}.{lang}"
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
619
|
boost = float(overrides.get(base, self._get_field_boost(base, lang)))
|
35da3813
tangwang
中英混写query的优化逻辑,不适...
|
620
|
out.append(self._format_field_with_boost(path, boost))
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
621
622
|
for shared in term_fields:
boost = float(overrides.get(shared, self._get_field_boost(shared, None)))
|
35da3813
tangwang
中英混写query的优化逻辑,不适...
|
623
|
out.append(self._format_field_with_boost(shared, boost))
|
6823fe3e
tangwang
feat(search): 混合语...
|
624
|
return out
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
625
|
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
626
|
def _build_best_fields_clause(self, language: str, query_text: str) -> Optional[Dict[str, Any]]:
|
35da3813
tangwang
中英混写query的优化逻辑,不适...
|
627
|
fields = self._match_field_strings(
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
628
629
630
631
632
|
language,
multilingual_fields=list(self.best_fields_boosts),
shared_fields=[],
boost_overrides=self.best_fields_boosts,
)
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
633
634
635
636
637
638
639
640
641
642
643
644
|
if not fields:
return None
return {
"multi_match": {
"query": query_text,
"type": "best_fields",
"fields": fields,
"boost": self.best_fields_clause_boost,
}
}
def _build_phrase_clause(self, language: str, query_text: str) -> Optional[Dict[str, Any]]:
|
35da3813
tangwang
中英混写query的优化逻辑,不适...
|
645
|
fields = self._match_field_strings(
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
646
647
648
649
650
|
language,
multilingual_fields=list(self.phrase_field_boosts),
shared_fields=[],
boost_overrides=self.phrase_field_boosts,
)
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
|
if not fields:
return None
clause: Dict[str, Any] = {
"multi_match": {
"query": query_text,
"type": "phrase",
"fields": fields,
"boost": self.phrase_match_boost,
}
}
if self.phrase_match_slop > 0:
clause["multi_match"]["slop"] = self.phrase_match_slop
if self.phrase_match_tie_breaker > 0:
clause["multi_match"]["tie_breaker"] = self.phrase_match_tie_breaker
return clause
def _build_lexical_language_clause(
self,
lang: str,
lang_query: str,
clause_name: str,
*,
is_source: bool,
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
674
|
keywords_query: Optional[str] = None,
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
675
|
) -> Optional[Dict[str, Any]]:
|
35da3813
tangwang
中英混写query的优化逻辑,不适...
|
676
|
combined_fields = self._match_field_strings(lang)
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
677
678
679
680
681
|
if not combined_fields:
return None
minimum_should_match = (
self.base_minimum_should_match if is_source else self.translation_minimum_should_match
)
|
f8219b5e
tangwang
1.
|
682
683
684
|
kw = (keywords_query or "").strip()
main_query = (lang_query or "").strip()
combined_must: List[Dict[str, Any]] = [
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
685
686
|
{
"combined_fields": {
|
f8219b5e
tangwang
1.
|
687
|
"query": main_query,
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
688
689
|
"fields": combined_fields,
"minimum_should_match": minimum_should_match,
|
f8219b5e
tangwang
1.
|
690
|
"boost": 2.0,
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
691
692
693
|
}
}
]
|
f8219b5e
tangwang
1.
|
694
695
|
if kw and kw != main_query:
combined_must.append(
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
696
697
698
699
700
|
{
"combined_fields": {
"query": kw,
"fields": combined_fields,
"minimum_should_match": self.keywords_minimum_should_match,
|
418b6a4a
tangwang
调参
|
701
|
"boost": 0.8,
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
702
703
704
|
}
}
)
|
f8219b5e
tangwang
1.
|
705
|
optional_mm = [
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
706
707
|
clause
for clause in (
|
f8219b5e
tangwang
1.
|
708
709
|
self._build_best_fields_clause(lang, main_query),
self._build_phrase_clause(lang, main_query),
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
710
711
712
|
)
if clause
]
|
f8219b5e
tangwang
1.
|
713
714
|
should_clauses: List[Dict[str, Any]] = [{"bool": {"must": combined_must}}]
should_clauses.extend(optional_mm)
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
715
716
717
|
clause: Dict[str, Any] = {
"bool": {
"_name": clause_name,
|
f8219b5e
tangwang
1.
|
718
719
|
"should": should_clauses,
"minimum_should_match": 1,
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
720
721
|
}
}
|
e756b18e
tangwang
重构了文本召回构建器,现在每个 b...
|
722
723
724
725
|
if not is_source:
clause["bool"]["boost"] = float(self.translation_boost)
return clause
|
ef5baa86
tangwang
混杂语言处理
|
726
727
728
729
|
def _build_advanced_text_query(
self,
query_text: str,
parsed_query: Optional[Any] = None,
|
dc403578
tangwang
多模态搜索
|
730
|
) -> List[Dict[str, Any]]:
|
7bc756c5
tangwang
优化 ES 查询构建
|
731
|
"""
|
ef5baa86
tangwang
混杂语言处理
|
732
|
Build advanced text query using base and translated lexical clauses.
|
c90f80ed
tangwang
相关性优化
|
733
|
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
734
735
|
Unified implementation:
- base_query: source-language clause
|
ef5baa86
tangwang
混杂语言处理
|
736
|
- translation queries: target-language clauses from translations
|
dc403578
tangwang
多模态搜索
|
737
|
|
7bc756c5
tangwang
优化 ES 查询构建
|
738
739
740
741
742
|
Args:
query_text: Query text
parsed_query: ParsedQuery object with analysis results
Returns:
|
dc403578
tangwang
多模态搜索
|
743
|
Flat recall clauses to be merged with KNN clauses under query.bool.should
|
7bc756c5
tangwang
优化 ES 查询构建
|
744
745
|
"""
should_clauses = []
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
746
|
source_lang = self.default_language
|
ef5baa86
tangwang
混杂语言处理
|
747
|
translations: Dict[str, str] = {}
|
ef5baa86
tangwang
混杂语言处理
|
748
|
|
7bc756c5
tangwang
优化 ES 查询构建
|
749
|
if parsed_query:
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
750
751
|
detected_lang = getattr(parsed_query, "detected_language", None)
source_lang = detected_lang if detected_lang and detected_lang != "unknown" else self.default_language
|
ef5baa86
tangwang
混杂语言处理
|
752
|
translations = getattr(parsed_query, "translations", None) or {}
|
c90f80ed
tangwang
相关性优化
|
753
|
|
ef5baa86
tangwang
混杂语言处理
|
754
|
source_lang = str(source_lang or self.default_language).strip().lower() or self.default_language
|
ef5baa86
tangwang
混杂语言处理
|
755
756
757
|
base_query_text = (
getattr(parsed_query, "rewritten_query", None) if parsed_query else None
) or query_text
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
758
759
760
761
762
|
kw_by_variant: Dict[str, str] = (
getattr(parsed_query, "keywords_queries", None) or {}
if parsed_query
else {}
)
|
ef5baa86
tangwang
混杂语言处理
|
763
|
|
ef5baa86
tangwang
混杂语言处理
|
764
|
if base_query_text:
|
35da3813
tangwang
中英混写query的优化逻辑,不适...
|
765
766
767
768
769
|
base_clause = self._build_lexical_language_clause(
source_lang,
base_query_text,
"base_query",
is_source=True,
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
770
|
keywords_query=(kw_by_variant.get(KEYWORDS_QUERY_BASE_KEY) or "").strip(),
|
35da3813
tangwang
中英混写query的优化逻辑,不适...
|
771
772
773
|
)
if base_clause:
should_clauses.append(base_clause)
|
ef5baa86
tangwang
混杂语言处理
|
774
775
776
777
778
779
780
781
|
for lang, translated_text in translations.items():
normalized_lang = str(lang or "").strip().lower()
normalized_text = str(translated_text or "").strip()
if not normalized_lang or not normalized_text:
continue
if normalized_lang == source_lang and normalized_text == base_query_text:
continue
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
782
|
trans_kw = (kw_by_variant.get(normalized_lang) or "").strip()
|
35da3813
tangwang
中英混写query的优化逻辑,不适...
|
783
784
785
786
787
|
trans_clause = self._build_lexical_language_clause(
normalized_lang,
normalized_text,
f"base_query_trans_{normalized_lang}",
is_source=False,
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
788
|
keywords_query=trans_kw,
|
35da3813
tangwang
中英混写query的优化逻辑,不适...
|
789
790
791
|
)
if trans_clause:
should_clauses.append(trans_clause)
|
bcada818
tangwang
last
|
792
|
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
793
794
795
|
# 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"]
|
69881ecb
tangwang
相关性调参、enrich内容解析优化
|
796
|
fallback_lexical = {
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
797
798
799
800
801
|
"multi_match": {
"_name": "base_query_fallback",
"query": query_text,
"fields": fallback_fields,
"minimum_should_match": self.base_minimum_should_match,
|
69881ecb
tangwang
相关性调参、enrich内容解析优化
|
802
803
|
}
}
|
dc403578
tangwang
多模态搜索
|
804
|
return [fallback_lexical]
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
805
|
|
dc403578
tangwang
多模态搜索
|
806
|
return should_clauses
|
be52af70
tangwang
first commit
|
807
|
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
808
809
810
|
def _build_filters(
self,
filters: Optional[Dict[str, Any]] = None,
|
43f1139f
tangwang
refactor: ES查询结构重...
|
811
|
range_filters: Optional[Dict[str, 'RangeFilter']] = None
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
812
|
) -> List[Dict[str, Any]]:
|
be52af70
tangwang
first commit
|
813
|
"""
|
43f1139f
tangwang
refactor: ES查询结构重...
|
814
|
构建过滤子句。
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
815
|
|
be52af70
tangwang
first commit
|
816
|
Args:
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
817
|
filters: 精确匹配过滤器字典
|
43f1139f
tangwang
refactor: ES查询结构重...
|
818
|
range_filters: 范围过滤器(Dict[str, RangeFilter],RangeFilter 是 Pydantic 模型)
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
819
|
|
be52af70
tangwang
first commit
|
820
|
Returns:
|
43f1139f
tangwang
refactor: ES查询结构重...
|
821
|
ES filter 子句列表
|
be52af70
tangwang
first commit
|
822
823
|
"""
filter_clauses = []
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
824
825
826
827
|
# 1. 处理精确匹配过滤
if filters:
for field, value in filters.items():
|
f7d3cf70
tangwang
更新文档
|
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
|
# 特殊处理: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
过滤逻辑
|
849
850
851
852
853
|
# 多个规格过滤:按 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
更新文档
|
854
855
856
857
858
|
for spec in value:
if isinstance(spec, dict):
name = spec.get("name")
spec_value = spec.get("value")
if name and spec_value:
|
85f08823
tangwang
过滤逻辑
|
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
|
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
更新文档
|
874
875
|
}
}
|
85f08823
tangwang
过滤逻辑
|
876
877
878
879
880
881
882
883
884
885
886
887
888
|
}
})
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
更新文档
|
889
|
})
|
85f08823
tangwang
过滤逻辑
|
890
891
892
893
894
895
896
897
898
899
900
|
filter_clauses.append({
"nested": {
"path": "specifications",
"query": {
"bool": {
"should": should_clauses,
"minimum_should_match": 1
}
}
}
})
|
f7d3cf70
tangwang
更新文档
|
901
902
|
continue
|
985d7fe3
tangwang
为 filters 中所有字段加上...
|
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
|
# *_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
支持聚合。过滤项补充了逻辑,但是有问题
|
943
|
if isinstance(value, list):
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
944
|
# 多值匹配(OR)
|
be52af70
tangwang
first commit
|
945
|
filter_clauses.append({
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
946
|
"terms": {field: value}
|
be52af70
tangwang
first commit
|
947
|
})
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
948
949
950
951
952
953
|
else:
# 单值精确匹配
filter_clauses.append({
"term": {field: value}
})
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
954
|
# 2. 处理范围过滤(支持 RangeFilter Pydantic 模型或字典)
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
955
|
if range_filters:
|
43f1139f
tangwang
refactor: ES查询结构重...
|
956
|
for field, range_filter in range_filters.items():
|
f0d020c3
tangwang
多语言查询改为只支持中英文两种,f...
|
957
958
959
960
961
962
963
964
965
966
|
# 支持 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 应该能自动...
|
967
|
|
43f1139f
tangwang
refactor: ES查询结构重...
|
968
|
if range_dict:
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
969
|
filter_clauses.append({
|
43f1139f
tangwang
refactor: ES查询结构重...
|
970
|
"range": {field: range_dict}
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
971
972
|
})
|
be52af70
tangwang
first commit
|
973
974
|
return filter_clauses
|
74fdf9bd
tangwang
1.
|
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
|
@staticmethod
def _build_product_title_exclusion_filter(parsed_query: Optional[Any]) -> Optional[Dict[str, Any]]:
if parsed_query is None:
return None
profile = getattr(parsed_query, "product_title_exclusion_profile", None)
if not profile or not getattr(profile, "is_active", False):
return None
should_clauses: List[Dict[str, Any]] = []
for term in profile.all_zh_title_exclusions():
should_clauses.append({"match_phrase": {"title.zh": {"query": term}}})
for term in profile.all_en_title_exclusions():
should_clauses.append({"match_phrase": {"title.en": {"query": term}}})
if not should_clauses:
return None
return {
"bool": {
"must_not": [
{
"bool": {
"should": should_clauses,
"minimum_should_match": 1,
}
}
]
}
}
|
c86c8237
tangwang
支持聚合。过滤项补充了逻辑,但是有问题
|
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
|
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
分面接口修改:
|
1017
|
sort_by: Field name for sorting (支持 'price' 自动映射)
|
c86c8237
tangwang
支持聚合。过滤项补充了逻辑,但是有问题
|
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
|
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
分面接口修改:
|
1029
1030
1031
1032
1033
1034
1035
|
# 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
支持聚合。过滤项补充了逻辑,但是有问题
|
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
|
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 应该能自动...
|
1049
|
def build_facets(
|
be52af70
tangwang
first commit
|
1050
|
self,
|
d8ca3b13
tangwang
修复 分面结果 各个选项结果数 和...
|
1051
1052
|
facet_configs: Optional[List['FacetConfig']] = None,
use_reverse_nested: bool = True
|
be52af70
tangwang
first commit
|
1053
1054
|
) -> Dict[str, Any]:
"""
|
ff5325fa
tangwang
修复:直接在 Searcher 层...
|
1055
|
构建分面聚合。
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
1056
|
|
be52af70
tangwang
first commit
|
1057
|
Args:
|
13320ac6
tangwang
分面接口修改:
|
1058
|
facet_configs: 分面配置对象列表
|
d8ca3b13
tangwang
修复 分面结果 各个选项结果数 和...
|
1059
1060
|
use_reverse_nested: 是否使用 reverse_nested 统计产品数量(默认 True)
如果为 False,将统计嵌套文档数量(性能更好但计数可能不准确)
|
13320ac6
tangwang
分面接口修改:
|
1061
1062
1063
1064
1065
|
支持的字段类型:
- 普通字段: 如 "category1_name"(terms 或 range 类型)
- specifications: "specifications"(返回所有规格名称及其值)
- specifications.{name}: 如 "specifications.color"(返回指定规格名称的值)
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
1066
|
|
be52af70
tangwang
first commit
|
1067
|
Returns:
|
ff5325fa
tangwang
修复:直接在 Searcher 层...
|
1068
|
ES aggregations 字典
|
d8ca3b13
tangwang
修复 分面结果 各个选项结果数 和...
|
1069
1070
1071
1072
|
性能说明:
- use_reverse_nested=True: 统计产品数量,准确性高但性能略差(通常影响 < 20%)
- use_reverse_nested=False: 统计嵌套文档数量,性能更好但计数可能不准确
|
be52af70
tangwang
first commit
|
1073
|
"""
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
1074
1075
1076
1077
1078
1079
|
if not facet_configs:
return {}
aggs = {}
for config in facet_configs:
|
13320ac6
tangwang
分面接口修改:
|
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
|
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...
|
1101
1102
1103
1104
1105
|
}
}
}
}
}
|
13320ac6
tangwang
分面接口修改:
|
1106
1107
1108
1109
1110
1111
1112
|
}
continue
# 处理 specifications.{name}(指定规格名称)
if field.startswith("specifications."):
name = field[len("specifications."):]
agg_name = f"specifications_{name}_facet"
|
d8ca3b13
tangwang
修复 分面结果 各个选项结果数 和...
|
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
|
# 使用 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
分面接口修改:
|
1131
1132
1133
1134
1135
1136
|
aggs[agg_name] = {
"nested": {"path": "specifications"},
"aggs": {
"filter_by_name": {
"filter": {"term": {"specifications.name": name}},
"aggs": {
|
d8ca3b13
tangwang
修复 分面结果 各个选项结果数 和...
|
1137
|
"value_counts": base_value_counts
|
f7d3cf70
tangwang
更新文档
|
1138
1139
1140
|
}
}
}
|
13320ac6
tangwang
分面接口修改:
|
1141
1142
1143
1144
1145
|
}
continue
# 处理普通字段
agg_name = f"{field}_facet"
|
bf89b597
tangwang
feat(search): ada...
|
1146
|
|
13320ac6
tangwang
分面接口修改:
|
1147
|
if facet_type == 'terms':
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
1148
1149
1150
|
aggs[agg_name] = {
"terms": {
"field": field,
|
13320ac6
tangwang
分面接口修改:
|
1151
|
"size": size,
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
1152
1153
|
"order": {"_count": "desc"}
}
|
be52af70
tangwang
first commit
|
1154
|
}
|
13320ac6
tangwang
分面接口修改:
|
1155
1156
|
elif facet_type == 'range':
if config.ranges:
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
1157
|
aggs[agg_name] = {
|
13320ac6
tangwang
分面接口修改:
|
1158
|
"range": {
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
1159
|
"field": field,
|
13320ac6
tangwang
分面接口修改:
|
1160
|
"ranges": config.ranges
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
1161
1162
|
}
}
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
1163
1164
|
return aggs
|