Blame view

search/es_query_builder.py 37.5 KB
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
be52af70   tangwang   first commit
12
13
  import numpy as np
  from .boolean_parser import QueryNode
9f96d6f3   tangwang   短query不用语义搜索
14
  from config import FunctionScoreConfig
be52af70   tangwang   first commit
15
16
17
18
19
20
21
  
  
  class ESQueryBuilder:
      """Builds Elasticsearch DSL queries."""
  
      def __init__(
          self,
be52af70   tangwang   first commit
22
23
          match_fields: List[str],
          text_embedding_field: Optional[str] = None,
13377199   tangwang   接口优化
24
          image_embedding_field: Optional[str] = None,
9f96d6f3   tangwang   短query不用语义搜索
25
          source_fields: Optional[List[str]] = None,
7bc756c5   tangwang   优化 ES 查询构建
26
          function_score_config: Optional[FunctionScoreConfig] = None,
a5a6bab8   tangwang   多语言查询优化
27
          enable_multilang_search: bool = True,
2739b281   tangwang   多语言索引调整
28
          default_language: str = "en",
70dab99f   tangwang   add logs
29
          knn_boost: float = 0.25
be52af70   tangwang   first commit
30
31
32
33
34
      ):
          """
          Initialize query builder.
  
          Args:
be52af70   tangwang   first commit
35
36
37
              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   接口优化
38
              source_fields: Fields to return in search results (_source includes)
9f96d6f3   tangwang   短query不用语义搜索
39
              function_score_config: Function score configuration
7bc756c5   tangwang   优化 ES 查询构建
40
              enable_multilang_search: Enable multi-language search using translations
a5a6bab8   tangwang   多语言查询优化
41
              default_language: Default language to use when detection fails or returns "unknown"
70dab99f   tangwang   add logs
42
              knn_boost: Boost value for KNN (embedding recall)
be52af70   tangwang   first commit
43
          """
be52af70   tangwang   first commit
44
45
46
          self.match_fields = match_fields
          self.text_embedding_field = text_embedding_field
          self.image_embedding_field = image_embedding_field
13377199   tangwang   接口优化
47
          self.source_fields = source_fields
9f96d6f3   tangwang   短query不用语义搜索
48
          self.function_score_config = function_score_config
7bc756c5   tangwang   优化 ES 查询构建
49
          self.enable_multilang_search = enable_multilang_search
a5a6bab8   tangwang   多语言查询优化
50
          self.default_language = default_language
70dab99f   tangwang   add logs
51
          self.knn_boost = knn_boost
be52af70   tangwang   first commit
52
  
c581becd   tangwang   feat: 实现 Multi-Se...
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
      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
71
              facet_configs: Facet configurations with disjunctive flags
c581becd   tangwang   feat: 实现 Multi-Se...
72
73
74
75
76
77
78
79
80
81
              
          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
82
              if getattr(fc, 'disjunctive', False):
c581becd   tangwang   feat: 实现 Multi-Se...
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
                  # 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
101
102
103
104
105
106
      def build_query(
          self,
          query_text: str,
          query_vector: Optional[np.ndarray] = None,
          query_node: Optional[QueryNode] = None,
          filters: Optional[Dict[str, Any]] = None,
6aa246be   tangwang   问题:Pydantic 应该能自动...
107
          range_filters: Optional[Dict[str, Any]] = None,
c581becd   tangwang   feat: 实现 Multi-Se...
108
          facet_configs: Optional[List[Any]] = None,
be52af70   tangwang   first commit
109
110
111
112
113
          size: int = 10,
          from_: int = 0,
          enable_knn: bool = True,
          knn_k: int = 50,
          knn_num_candidates: int = 200,
7bc756c5   tangwang   优化 ES 查询构建
114
115
          min_score: Optional[float] = None,
          parsed_query: Optional[Any] = None
be52af70   tangwang   first commit
116
117
      ) -> Dict[str, Any]:
          """
c581becd   tangwang   feat: 实现 Multi-Se...
118
          Build complete ES query with post_filter support for multi-select faceting.
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
119
  
c581becd   tangwang   feat: 实现 Multi-Se...
120
121
122
          结构:filters and (text_recall or embedding_recall) + post_filter
          - conjunctive_filters: 应用在 query.bool.filter(影响结果和聚合)
          - disjunctive_filters: 应用在 post_filter(只影响结果,不影响聚合)
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
123
124
125
          - text_recall: 文本相关性召回(中英文字段都用)
          - embedding_recall: 向量召回(KNN
          - function_score: 包装召回部分,支持提权字段
be52af70   tangwang   first commit
126
127
128
129
130
  
          Args:
              query_text: Query text for BM25 matching
              query_vector: Query embedding for KNN search
              query_node: Parsed boolean expression tree
c581becd   tangwang   feat: 实现 Multi-Se...
131
132
133
              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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
              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
          """
          es_query = {
              "size": size,
              "from": from_
          }
  
13377199   tangwang   接口优化
149
150
151
152
153
154
          # Add _source filtering if source_fields are configured
          if self.source_fields:
              es_query["_source"] = {
                  "includes": self.source_fields
              }
  
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
155
156
157
158
159
160
161
162
163
          # 1. Build recall queries (text or embedding)
          recall_clauses = []
          
          # Text recall (always include if query_text exists)
          if query_text:
              if query_node and query_node.operator != 'TERM':
                  # Complex boolean query
                  text_query = self._build_boolean_query(query_node)
              else:
7bc756c5   tangwang   优化 ES 查询构建
164
165
                  # Simple text query - use advanced should-based multi-query strategy
                  text_query = self._build_advanced_text_query(query_text, parsed_query)
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
166
167
168
169
170
              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...
171
172
173
174
175
176
177
          # 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...
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
          
          # 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 应该能自动...
196
197
198
              if filter_clauses:
                  es_query["query"] = {
                      "bool": {
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
199
                          "must": [recall_query],
6aa246be   tangwang   问题:Pydantic 应该能自动...
200
201
                          "filter": filter_clauses
                      }
be52af70   tangwang   first commit
202
                  }
6aa246be   tangwang   问题:Pydantic 应该能自动...
203
              else:
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
204
                  es_query["query"] = recall_query
be52af70   tangwang   first commit
205
          else:
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
206
207
208
209
210
211
212
213
214
215
              # 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
216
  
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
217
          # 4. Add KNN search if enabled (separate from query, ES will combine)
ea118f2b   tangwang   build_query:根据 qu...
218
          # Adjust KNN k, num_candidates, boost by query_tokens (short query: less KNN; long: more)
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
219
          if has_embedding:
ea118f2b   tangwang   build_query:根据 qu...
220
221
222
223
224
225
226
227
228
229
230
231
232
233
              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
234
235
236
237
              knn_clause = {
                  "field": self.text_embedding_field,
                  "query_vector": query_vector.tolist(),
                  "k": knn_k,
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
238
                  "num_candidates": knn_num_candidates,
ea118f2b   tangwang   build_query:根据 qu...
239
                  "boost": knn_boost
be52af70   tangwang   first commit
240
241
242
              }
              es_query["knn"] = knn_clause
  
c581becd   tangwang   feat: 实现 Multi-Se...
243
244
245
246
247
248
249
250
251
252
253
254
          # 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
255
256
257
258
          if min_score is not None:
              es_query["min_score"] = min_score
  
          return es_query
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
      
      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不用语义搜索
277
278
279
          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...
280
281
282
283
          function_score_query = {
              "function_score": {
                  "query": query,
                  "functions": functions,
9f96d6f3   tangwang   短query不用语义搜索
284
285
                  "score_mode": score_mode,
                  "boost_mode": boost_mode
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
286
287
288
289
290
291
292
293
294
295
296
297
298
              }
          }
          
          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不用语义搜索
299
300
301
302
          if not self.function_score_config:
              return functions
          
          config_functions = self.function_score_config.functions or []
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
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
          
          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
347
348
349
350
  
      def _build_text_query(self, query_text: str) -> Dict[str, Any]:
          """
          Build simple text matching query (BM25).
be52af70   tangwang   first commit
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
  
          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 查询构建
368
369
370
371
372
373
374
375
376
377
378
379
380
      
      def _get_match_fields(self, language: str) -> Tuple[List[str], List[str]]:
          """
          Get match fields for a specific language.
          
          Args:
              language: Language code ('zh' or 'en')
              
          Returns:
              (all_fields, core_fields) - core_fields are for phrase/keyword queries
          """
          if language == 'zh':
              all_fields = [
d7d48f52   tangwang   改动(mapping + 灌入结构)
381
382
383
384
                  "title.zh^3.0",
                  "brief.zh^1.5",
                  "description.zh",
                  "vendor.zh^1.5",
7bc756c5   tangwang   优化 ES 查询构建
385
                  "tags",
d7d48f52   tangwang   改动(mapping + 灌入结构)
386
387
                  "category_path.zh^1.5",
                  "category_name_text.zh^1.5",
7bc756c5   tangwang   优化 ES 查询构建
388
389
390
                  "option1_values^0.5"
              ]
              core_fields = [
d7d48f52   tangwang   改动(mapping + 灌入结构)
391
392
393
394
                  "title.zh^3.0",
                  "brief.zh^1.5",
                  "vendor.zh^1.5",
                  "category_name_text.zh^1.5"
7bc756c5   tangwang   优化 ES 查询构建
395
396
397
              ]
          else:  # en
              all_fields = [
d7d48f52   tangwang   改动(mapping + 灌入结构)
398
399
400
401
                  "title.en^3.0",
                  "brief.en^1.5",
                  "description.en",
                  "vendor.en^1.5",
7bc756c5   tangwang   优化 ES 查询构建
402
                  "tags",
d7d48f52   tangwang   改动(mapping + 灌入结构)
403
404
                  "category_path.en^1.5",
                  "category_name_text.en^1.5",
7bc756c5   tangwang   优化 ES 查询构建
405
406
407
                  "option1_values^0.5"
              ]
              core_fields = [
d7d48f52   tangwang   改动(mapping + 灌入结构)
408
409
410
411
                  "title.en^3.0",
                  "brief.en^1.5",
                  "vendor.en^1.5",
                  "category_name_text.en^1.5"
7bc756c5   tangwang   优化 ES 查询构建
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
              ]
          return all_fields, core_fields
      
      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]:
          """
          Build advanced text query using should clauses with multiple query strategies.
          
          Reference implementation:
          - base_query: main query with AND operator and 75% minimum_should_match
          - translation queries: lower boost (0.4) for other languages
          - phrase query: for short queries (2+ tokens)
          - keywords query: extracted nouns from query
          - 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
          translations = {}
a5a6bab8   tangwang   多语言查询优化
442
          language = self.default_language
7bc756c5   tangwang   优化 ES 查询构建
443
          keywords = ""
ea118f2b   tangwang   build_query:根据 qu...
444
          query_tokens = []
7bc756c5   tangwang   优化 ES 查询构建
445
          token_count = 0
7bc756c5   tangwang   优化 ES 查询构建
446
447
448
          
          if parsed_query:
              translations = parsed_query.translations or {}
a5a6bab8   tangwang   多语言查询优化
449
450
451
452
453
454
              # Use default language if detected_language is None or "unknown"
              detected_lang = parsed_query.detected_language
              if not detected_lang or detected_lang == "unknown":
                  language = self.default_language
              else:
                  language = detected_lang
7bc756c5   tangwang   优化 ES 查询构建
455
              keywords = getattr(parsed_query, 'keywords', '') or ""
ea118f2b   tangwang   build_query:根据 qu...
456
457
              query_tokens = getattr(parsed_query, 'query_tokens', None) or []
              token_count = len(query_tokens) or getattr(parsed_query, 'token_count', 0) or 0
7bc756c5   tangwang   优化 ES 查询构建
458
459
460
461
462
463
          
          # Get match fields for the detected language
          match_fields, core_fields = self._get_match_fields(language)
          
          # Tie breaker values
          tie_breaker_base_query = 0.9
7bc756c5   tangwang   优化 ES 查询构建
464
465
466
467
468
469
470
471
          tie_breaker_keywords = 0.9
          
          # 1. Base query - main query with AND operator
          should_clauses.append({
              "multi_match": {
                  "_name": "base_query",
                  "fields": match_fields,
                  "minimum_should_match": "75%",
70dab99f   tangwang   add logs
472
                  # "operator": "AND",
7bc756c5   tangwang   优化 ES 查询构建
473
474
475
476
477
478
479
                  "query": query_text,
                  "tie_breaker": tie_breaker_base_query
              }
          })
          
          # 2. Translation queries - lower boost (0.4) for other languages
          if self.enable_multilang_search:
a5a6bab8   tangwang   多语言查询优化
480
              if language != 'zh' and translations.get('zh'):
7bc756c5   tangwang   优化 ES 查询构建
481
482
483
484
485
                  zh_fields, _ = self._get_match_fields('zh')
                  should_clauses.append({
                      "multi_match": {
                          "query": translations['zh'],
                          "fields": zh_fields,
70dab99f   tangwang   add logs
486
                          # "operator": "AND",
7bc756c5   tangwang   优化 ES 查询构建
487
488
489
490
491
492
493
                          "minimum_should_match": "75%",
                          "tie_breaker": tie_breaker_base_query,
                          "boost": 0.4,
                          "_name": "base_query_trans_zh"
                      }
                  })
              
a5a6bab8   tangwang   多语言查询优化
494
              if language != 'en' and translations.get('en'):
7bc756c5   tangwang   优化 ES 查询构建
495
496
497
498
499
                  en_fields, _ = self._get_match_fields('en')
                  should_clauses.append({
                      "multi_match": {
                          "query": translations['en'],
                          "fields": en_fields,
70dab99f   tangwang   add logs
500
                          # "operator": "AND",
7bc756c5   tangwang   优化 ES 查询构建
501
502
503
504
505
506
                          "minimum_should_match": "75%",
                          "tie_breaker": tie_breaker_base_query,
                          "boost": 0.4,
                          "_name": "base_query_trans_en"
                      }
                  })
ea118f2b   tangwang   build_query:根据 qu...
507
  
7bc756c5   tangwang   优化 ES 查询构建
508
509
510
511
512
513
514
515
516
517
518
519
520
          if False and is_long_query:
              boost = 0.5 * pow(min(1.0, token_count / 10.0), 0.9)
              minimum_should_match = "70%"
              should_clauses.append({
                  "multi_match": {
                      "query": query_text,
                      "fields": match_fields,
                      "minimum_should_match": minimum_should_match,
                      "boost": boost,
                      "tie_breaker": tie_breaker_long_query,
                      "_name": "long_query"
                  }
              })
ea118f2b   tangwang   build_query:根据 qu...
521
522
523
  
          # 3. Short query - add phrase query (derived from query_tokens)
          # is_short: quoted or ((token_count <= 2 or len <= 4) and no space)
7bc756c5   tangwang   优化 ES 查询构建
524
          ENABLE_PHRASE_QUERY = True
ea118f2b   tangwang   build_query:根据 qu...
525
526
527
          is_quoted = query_text.startswith('"') and query_text.endswith('"')
          is_short = is_quoted or ((token_count <= 2 or len(query_text) <= 4) and ' ' not in query_text)
          if ENABLE_PHRASE_QUERY and token_count >= 2 and is_short:
7bc756c5   tangwang   优化 ES 查询构建
528
529
530
531
532
533
534
535
536
537
538
539
540
              query_length = len(query_text)
              slop = 0 if query_length < 3 else 1 if query_length < 5 else 2
              should_clauses.append({
                  "multi_match": {
                      "query": query_text,
                      "fields": core_fields,
                      "type": "phrase",
                      "slop": slop,
                      "boost": 1.0,
                      "_name": "phrase_query"
                  }
              })
          
ea118f2b   tangwang   build_query:根据 qu...
541
          # 4. Keywords query - extracted nouns from query
7bc756c5   tangwang   优化 ES 查询构建
542
543
544
545
546
          elif keywords and len(keywords.split()) <= 2 and 2 * len(keywords.replace(' ', '')) <= len(query_text):
              should_clauses.append({
                  "multi_match": {
                      "query": keywords,
                      "fields": core_fields,
70dab99f   tangwang   add logs
547
                      # "operator": "AND",
7bc756c5   tangwang   优化 ES 查询构建
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
                      "tie_breaker": tie_breaker_keywords,
                      "boost": 0.1,
                      "_name": "keywords_query"
                  }
              })
          
          # 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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
  
      def _build_boolean_query(self, node: QueryNode) -> Dict[str, Any]:
          """
          Build query from boolean expression tree.
  
          Args:
              node: Query tree node
  
          Returns:
              ES query clause
          """
          if node.operator == 'TERM':
              # Leaf node - simple text query
              return self._build_text_query(node.value)
  
          elif node.operator == 'AND':
              # All terms must match
              return {
                  "bool": {
                      "must": [
                          self._build_boolean_query(term)
                          for term in node.terms
                      ]
                  }
              }
  
          elif node.operator == 'OR':
              # Any term must match
              return {
                  "bool": {
                      "should": [
                          self._build_boolean_query(term)
                          for term in node.terms
                      ],
                      "minimum_should_match": 1
                  }
              }
  
          elif node.operator == 'ANDNOT':
              # First term must match, second must not
              if len(node.terms) >= 2:
                  return {
                      "bool": {
                          "must": [self._build_boolean_query(node.terms[0])],
                          "must_not": [self._build_boolean_query(node.terms[1])]
                      }
                  }
              else:
                  return self._build_boolean_query(node.terms[0])
  
          elif node.operator == 'RANK':
              # Like OR but for ranking (all terms contribute to score)
              return {
                  "bool": {
                      "should": [
                          self._build_boolean_query(term)
                          for term in node.terms
                      ]
                  }
              }
  
          else:
              # Unknown operator
              return {"match_all": {}}
  
6aa246be   tangwang   问题:Pydantic 应该能自动...
629
630
631
      def _build_filters(
          self, 
          filters: Optional[Dict[str, Any]] = None,
43f1139f   tangwang   refactor: ES查询结构重...
632
          range_filters: Optional[Dict[str, 'RangeFilter']] = None
6aa246be   tangwang   问题:Pydantic 应该能自动...
633
      ) -> List[Dict[str, Any]]:
be52af70   tangwang   first commit
634
          """
43f1139f   tangwang   refactor: ES查询结构重...
635
          构建过滤子句。
6aa246be   tangwang   问题:Pydantic 应该能自动...
636
          
be52af70   tangwang   first commit
637
          Args:
6aa246be   tangwang   问题:Pydantic 应该能自动...
638
              filters: 精确匹配过滤器字典
43f1139f   tangwang   refactor: ES查询结构重...
639
              range_filters: 范围过滤器(Dict[str, RangeFilter]RangeFilter  Pydantic 模型)
6aa246be   tangwang   问题:Pydantic 应该能自动...
640
          
be52af70   tangwang   first commit
641
          Returns:
43f1139f   tangwang   refactor: ES查询结构重...
642
              ES filter 子句列表
be52af70   tangwang   first commit
643
644
          """
          filter_clauses = []
6aa246be   tangwang   问题:Pydantic 应该能自动...
645
646
647
648
          
          # 1. 处理精确匹配过滤
          if filters:
              for field, value in filters.items():
f7d3cf70   tangwang   更新文档
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
                  # 特殊处理: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   过滤逻辑
670
671
672
673
674
                          # 多个规格过滤:按 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   更新文档
675
676
677
678
679
                          for spec in value:
                              if isinstance(spec, dict):
                                  name = spec.get("name")
                                  spec_value = spec.get("value")
                                  if name and spec_value:
85f08823   tangwang   过滤逻辑
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
                                      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   更新文档
695
696
                                              }
                                          }
85f08823   tangwang   过滤逻辑
697
698
699
700
701
702
703
704
705
706
707
708
709
                                      }
                                  })
                              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   更新文档
710
                                      })
85f08823   tangwang   过滤逻辑
711
712
713
714
715
716
717
718
719
720
721
                                  filter_clauses.append({
                                      "nested": {
                                          "path": "specifications",
                                          "query": {
                                              "bool": {
                                                  "should": should_clauses,
                                                  "minimum_should_match": 1
                                              }
                                          }
                                      }
                                  })
f7d3cf70   tangwang   更新文档
722
723
                      continue
                  
985d7fe3   tangwang   为 filters 中所有字段加上...
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
                  # *_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   支持聚合。过滤项补充了逻辑,但是有问题
764
                  if isinstance(value, list):
6aa246be   tangwang   问题:Pydantic 应该能自动...
765
                      # 多值匹配(OR)
be52af70   tangwang   first commit
766
                      filter_clauses.append({
6aa246be   tangwang   问题:Pydantic 应该能自动...
767
                          "terms": {field: value}
be52af70   tangwang   first commit
768
                      })
6aa246be   tangwang   问题:Pydantic 应该能自动...
769
770
771
772
773
774
                  else:
                      # 单值精确匹配
                      filter_clauses.append({
                          "term": {field: value}
                      })
          
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
775
          # 2. 处理范围过滤(支持 RangeFilter Pydantic 模型或字典)
6aa246be   tangwang   问题:Pydantic 应该能自动...
776
          if range_filters:
43f1139f   tangwang   refactor: ES查询结构重...
777
              for field, range_filter in range_filters.items():
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
778
779
780
781
782
783
784
785
786
787
                  # 支持 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 应该能自动...
788
                  
43f1139f   tangwang   refactor: ES查询结构重...
789
                  if range_dict:
6aa246be   tangwang   问题:Pydantic 应该能自动...
790
                      filter_clauses.append({
43f1139f   tangwang   refactor: ES查询结构重...
791
                          "range": {field: range_dict}
6aa246be   tangwang   问题:Pydantic 应该能自动...
792
793
                      })
          
be52af70   tangwang   first commit
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
          return filter_clauses
  
      def add_spu_collapse(
          self,
          es_query: Dict[str, Any],
          spu_field: str,
          inner_hits_size: int = 3
      ) -> Dict[str, Any]:
          """
          Add SPU aggregation/collapse to query.
  
          Args:
              es_query: Existing ES query
              spu_field: Field containing SPU ID
              inner_hits_size: Number of SKUs to return per SPU
  
          Returns:
              Modified ES query
          """
          # Add collapse
          es_query["collapse"] = {
              "field": spu_field,
              "inner_hits": {
                  "_source": False,
                  "name": "top_docs",
                  "size": inner_hits_size
              }
          }
  
          # Add cardinality aggregation to count unique SPUs
          if "aggs" not in es_query:
              es_query["aggs"] = {}
  
          es_query["aggs"]["unique_count"] = {
              "cardinality": {
                  "field": spu_field
              }
          }
  
          return es_query
  
c86c8237   tangwang   支持聚合。过滤项补充了逻辑,但是有问题
835
836
837
838
839
840
841
842
843
844
845
      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   分面接口修改:
846
              sort_by: Field name for sorting (支持 'price' 自动映射)
c86c8237   tangwang   支持聚合。过滤项补充了逻辑,但是有问题
847
848
849
850
851
852
853
854
855
856
857
              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   分面接口修改:
858
859
860
861
862
863
864
          # 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   支持聚合。过滤项补充了逻辑,但是有问题
865
866
867
868
869
870
871
872
873
874
875
876
877
          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 应该能自动...
878
      def build_facets(
be52af70   tangwang   first commit
879
          self,
d8ca3b13   tangwang   修复 分面结果 各个选项结果数 和...
880
881
          facet_configs: Optional[List['FacetConfig']] = None,
          use_reverse_nested: bool = True
be52af70   tangwang   first commit
882
883
      ) -> Dict[str, Any]:
          """
ff5325fa   tangwang   修复:直接在 Searcher 层...
884
          构建分面聚合。
6aa246be   tangwang   问题:Pydantic 应该能自动...
885
          
be52af70   tangwang   first commit
886
          Args:
13320ac6   tangwang   分面接口修改:
887
              facet_configs: 分面配置对象列表
d8ca3b13   tangwang   修复 分面结果 各个选项结果数 和...
888
889
              use_reverse_nested: 是否使用 reverse_nested 统计产品数量(默认 True
                                 如果为 False,将统计嵌套文档数量(性能更好但计数可能不准确)
13320ac6   tangwang   分面接口修改:
890
891
892
893
894
              
              支持的字段类型:
                  - 普通字段:  "category1_name"terms  range 类型)
                  - specifications: "specifications"(返回所有规格名称及其值)
                  - specifications.{name}:  "specifications.color"(返回指定规格名称的值)
6aa246be   tangwang   问题:Pydantic 应该能自动...
895
          
be52af70   tangwang   first commit
896
          Returns:
ff5325fa   tangwang   修复:直接在 Searcher 层...
897
              ES aggregations 字典
d8ca3b13   tangwang   修复 分面结果 各个选项结果数 和...
898
899
900
901
          
          性能说明:
              - use_reverse_nested=True: 统计产品数量,准确性高但性能略差(通常影响 < 20%
              - use_reverse_nested=False: 统计嵌套文档数量,性能更好但计数可能不准确
be52af70   tangwang   first commit
902
          """
6aa246be   tangwang   问题:Pydantic 应该能自动...
903
904
905
906
907
908
          if not facet_configs:
              return {}
          
          aggs = {}
          
          for config in facet_configs:
13320ac6   tangwang   分面接口修改:
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
              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...
930
931
932
933
934
                                      }
                                  }
                              }
                          }
                      }
13320ac6   tangwang   分面接口修改:
935
936
937
938
939
940
941
                  }
                  continue
              
              # 处理 specifications.{name}(指定规格名称)
              if field.startswith("specifications."):
                  name = field[len("specifications."):]
                  agg_name = f"specifications_{name}_facet"
d8ca3b13   tangwang   修复 分面结果 各个选项结果数 和...
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
                  # 使用 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   分面接口修改:
960
961
962
963
964
965
                  aggs[agg_name] = {
                      "nested": {"path": "specifications"},
                      "aggs": {
                          "filter_by_name": {
                              "filter": {"term": {"specifications.name": name}},
                              "aggs": {
d8ca3b13   tangwang   修复 分面结果 各个选项结果数 和...
966
                                  "value_counts": base_value_counts
f7d3cf70   tangwang   更新文档
967
968
969
                              }
                          }
                      }
13320ac6   tangwang   分面接口修改:
970
971
972
973
974
                  }
                  continue
              
              # 处理普通字段
              agg_name = f"{field}_facet"
bf89b597   tangwang   feat(search): ada...
975
              
13320ac6   tangwang   分面接口修改:
976
              if facet_type == 'terms':
6aa246be   tangwang   问题:Pydantic 应该能自动...
977
978
979
                  aggs[agg_name] = {
                      "terms": {
                          "field": field,
13320ac6   tangwang   分面接口修改:
980
                          "size": size,
6aa246be   tangwang   问题:Pydantic 应该能自动...
981
982
                          "order": {"_count": "desc"}
                      }
be52af70   tangwang   first commit
983
                  }
13320ac6   tangwang   分面接口修改:
984
985
              elif facet_type == 'range':
                  if config.ranges:
6aa246be   tangwang   问题:Pydantic 应该能自动...
986
                      aggs[agg_name] = {
13320ac6   tangwang   分面接口修改:
987
                          "range": {
6aa246be   tangwang   问题:Pydantic 应该能自动...
988
                              "field": field,
13320ac6   tangwang   分面接口修改:
989
                              "ranges": config.ranges
6aa246be   tangwang   问题:Pydantic 应该能自动...
990
991
                          }
                      }
6aa246be   tangwang   问题:Pydantic 应该能自动...
992
993
          
          return aggs