Blame view

search/es_query_builder.py 18 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
  """
  
ff5325fa   tangwang   修复:直接在 Searcher 层...
11
  from typing import Dict, Any, List, Optional, Union
be52af70   tangwang   first commit
12
13
  import numpy as np
  from .boolean_parser import QueryNode
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
14
  from .query_config import FUNCTION_SCORE_CONFIG
be52af70   tangwang   first commit
15
16
17
18
19
20
21
22
23
24
  
  
  class ESQueryBuilder:
      """Builds Elasticsearch DSL queries."""
  
      def __init__(
          self,
          index_name: str,
          match_fields: List[str],
          text_embedding_field: Optional[str] = None,
13377199   tangwang   接口优化
25
26
          image_embedding_field: Optional[str] = None,
          source_fields: Optional[List[str]] = None
be52af70   tangwang   first commit
27
28
29
30
31
32
33
34
35
      ):
          """
          Initialize query builder.
  
          Args:
              index_name: ES index name
              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   接口优化
36
              source_fields: Fields to return in search results (_source includes)
be52af70   tangwang   first commit
37
38
39
40
41
          """
          self.index_name = index_name
          self.match_fields = match_fields
          self.text_embedding_field = text_embedding_field
          self.image_embedding_field = image_embedding_field
13377199   tangwang   接口优化
42
          self.source_fields = source_fields
be52af70   tangwang   first commit
43
44
45
46
47
48
49
  
      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 应该能自动...
50
          range_filters: Optional[Dict[str, Any]] = None,
be52af70   tangwang   first commit
51
52
53
54
55
56
57
58
          size: int = 10,
          from_: int = 0,
          enable_knn: bool = True,
          knn_k: int = 50,
          knn_num_candidates: int = 200,
          min_score: Optional[float] = None
      ) -> Dict[str, Any]:
          """
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
59
60
61
62
63
64
65
          Build complete ES query (简化版).
  
          结构:filters and (text_recall or embedding_recall)
          - filters: 前端传递的过滤条件永远起作用
          - text_recall: 文本相关性召回(中英文字段都用)
          - embedding_recall: 向量召回(KNN
          - function_score: 包装召回部分,支持提权字段
be52af70   tangwang   first commit
66
67
68
69
70
  
          Args:
              query_text: Query text for BM25 matching
              query_vector: Query embedding for KNN search
              query_node: Parsed boolean expression tree
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
71
72
              filters: Exact match filters (always applied)
              range_filters: Range filters for numeric fields (always applied)
be52af70   tangwang   first commit
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
              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   接口优化
88
89
90
91
92
93
          # Add _source filtering if source_fields are configured
          if self.source_fields:
              es_query["_source"] = {
                  "includes": self.source_fields
              }
  
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
          # 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:
                  # Simple text query
                  text_query = self._build_text_query(query_text)
              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
          
          # 2. Build filter clauses (always applied)
          filter_clauses = self._build_filters(filters, range_filters)
          
          # 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 应该能自动...
130
131
132
              if filter_clauses:
                  es_query["query"] = {
                      "bool": {
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
133
                          "must": [recall_query],
6aa246be   tangwang   问题:Pydantic 应该能自动...
134
135
                          "filter": filter_clauses
                      }
be52af70   tangwang   first commit
136
                  }
6aa246be   tangwang   问题:Pydantic 应该能自动...
137
              else:
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
138
                  es_query["query"] = recall_query
be52af70   tangwang   first commit
139
          else:
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
140
141
142
143
144
145
146
147
148
149
              # 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
150
  
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
151
152
          # 4. Add KNN search if enabled (separate from query, ES will combine)
          if has_embedding:
be52af70   tangwang   first commit
153
154
155
156
              knn_clause = {
                  "field": self.text_embedding_field,
                  "query_vector": query_vector.tolist(),
                  "k": knn_k,
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
157
158
                  "num_candidates": knn_num_candidates,
                  "boost": 0.2  # Lower boost for embedding recall
be52af70   tangwang   first commit
159
160
161
              }
              es_query["knn"] = knn_clause
  
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
162
          # 5. Add minimum score filter
be52af70   tangwang   first commit
163
164
165
166
          if min_score is not None:
              es_query["min_score"] = min_score
  
          return es_query
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
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
216
217
218
219
220
221
222
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
      
      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
          function_score_query = {
              "function_score": {
                  "query": query,
                  "functions": functions,
                  "score_mode": FUNCTION_SCORE_CONFIG.get("score_mode", "sum"),
                  "boost_mode": FUNCTION_SCORE_CONFIG.get("boost_mode", "multiply")
              }
          }
          
          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 = []
          config_functions = FUNCTION_SCORE_CONFIG.get("functions", [])
          
          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
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
  
      def _build_text_query(self, query_text: str) -> Dict[str, Any]:
          """
          Build simple text matching query (BM25).
  
          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"
              }
          }
  
      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 应该能自动...
335
336
337
      def _build_filters(
          self, 
          filters: Optional[Dict[str, Any]] = None,
43f1139f   tangwang   refactor: ES查询结构重...
338
          range_filters: Optional[Dict[str, 'RangeFilter']] = None
6aa246be   tangwang   问题:Pydantic 应该能自动...
339
      ) -> List[Dict[str, Any]]:
be52af70   tangwang   first commit
340
          """
43f1139f   tangwang   refactor: ES查询结构重...
341
          构建过滤子句。
6aa246be   tangwang   问题:Pydantic 应该能自动...
342
          
be52af70   tangwang   first commit
343
          Args:
6aa246be   tangwang   问题:Pydantic 应该能自动...
344
              filters: 精确匹配过滤器字典
43f1139f   tangwang   refactor: ES查询结构重...
345
              range_filters: 范围过滤器(Dict[str, RangeFilter]RangeFilter  Pydantic 模型)
6aa246be   tangwang   问题:Pydantic 应该能自动...
346
          
be52af70   tangwang   first commit
347
          Returns:
43f1139f   tangwang   refactor: ES查询结构重...
348
              ES filter 子句列表
be52af70   tangwang   first commit
349
350
          """
          filter_clauses = []
6aa246be   tangwang   问题:Pydantic 应该能自动...
351
352
353
354
          
          # 1. 处理精确匹配过滤
          if filters:
              for field, value in filters.items():
c86c8237   tangwang   支持聚合。过滤项补充了逻辑,但是有问题
355
                  if isinstance(value, list):
6aa246be   tangwang   问题:Pydantic 应该能自动...
356
                      # 多值匹配(OR)
be52af70   tangwang   first commit
357
                      filter_clauses.append({
6aa246be   tangwang   问题:Pydantic 应该能自动...
358
                          "terms": {field: value}
be52af70   tangwang   first commit
359
                      })
6aa246be   tangwang   问题:Pydantic 应该能自动...
360
361
362
363
364
365
                  else:
                      # 单值精确匹配
                      filter_clauses.append({
                          "term": {field: value}
                      })
          
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
366
          # 2. 处理范围过滤(支持 RangeFilter Pydantic 模型或字典)
6aa246be   tangwang   问题:Pydantic 应该能自动...
367
          if range_filters:
43f1139f   tangwang   refactor: ES查询结构重...
368
              for field, range_filter in range_filters.items():
f0d020c3   tangwang   多语言查询改为只支持中英文两种,f...
369
370
371
372
373
374
375
376
377
378
                  # 支持 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 应该能自动...
379
                  
43f1139f   tangwang   refactor: ES查询结构重...
380
                  if range_dict:
6aa246be   tangwang   问题:Pydantic 应该能自动...
381
                      filter_clauses.append({
43f1139f   tangwang   refactor: ES查询结构重...
382
                          "range": {field: range_dict}
6aa246be   tangwang   问题:Pydantic 应该能自动...
383
384
                      })
          
be52af70   tangwang   first commit
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
          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   支持聚合。过滤项补充了逻辑,但是有问题
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
      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
              sort_by: Field name for sorting
              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"
  
          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 应该能自动...
462
      def build_facets(
be52af70   tangwang   first commit
463
          self,
ff5325fa   tangwang   修复:直接在 Searcher 层...
464
          facet_configs: Optional[List[Union[str, 'FacetConfig']]] = None
be52af70   tangwang   first commit
465
466
      ) -> Dict[str, Any]:
          """
ff5325fa   tangwang   修复:直接在 Searcher 层...
467
          构建分面聚合。
6aa246be   tangwang   问题:Pydantic 应该能自动...
468
          
bf89b597   tangwang   feat(search): ada...
469
470
471
472
          支持:
          1. 分类分面:category1_name, category2_name, category3_name, category_name
          2. specifications分面:嵌套聚合,按name聚合,然后按value聚合
          
be52af70   tangwang   first commit
473
          Args:
ff5325fa   tangwang   修复:直接在 Searcher 层...
474
475
476
              facet_configs: 分面配置列表(标准格式):
                  - str: 字段名,使用默认 terms 配置
                  - FacetConfig: 详细的分面配置对象
bf89b597   tangwang   feat(search): ada...
477
                  - 特殊值 "specifications": 构建specifications嵌套分面
6aa246be   tangwang   问题:Pydantic 应该能自动...
478
          
be52af70   tangwang   first commit
479
          Returns:
ff5325fa   tangwang   修复:直接在 Searcher 层...
480
              ES aggregations 字典
be52af70   tangwang   first commit
481
          """
6aa246be   tangwang   问题:Pydantic 应该能自动...
482
483
484
485
486
487
          if not facet_configs:
              return {}
          
          aggs = {}
          
          for config in facet_configs:
bf89b597   tangwang   feat(search): ada...
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
              # 特殊处理:specifications嵌套分面
              if isinstance(config, str) and config == "specifications":
                  # 构建specifications嵌套分面(按name聚合,然后按value聚合)
                  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": 10,
                                          "order": {"_count": "desc"}
                                      }
                                  }
                              }
                          }
                      }
                  }
                  continue
              
ff5325fa   tangwang   修复:直接在 Searcher 层...
516
              # 简单模式:只有字段名(字符串)
6aa246be   tangwang   问题:Pydantic 应该能自动...
517
518
519
520
521
522
              if isinstance(config, str):
                  field = config
                  agg_name = f"{field}_facet"
                  aggs[agg_name] = {
                      "terms": {
                          "field": field,
ff5325fa   tangwang   修复:直接在 Searcher 层...
523
                          "size": 10,
6aa246be   tangwang   问题:Pydantic 应该能自动...
524
525
                          "order": {"_count": "desc"}
                      }
be52af70   tangwang   first commit
526
                  }
6aa246be   tangwang   问题:Pydantic 应该能自动...
527
              
ff5325fa   tangwang   修复:直接在 Searcher 层...
528
529
530
531
532
533
              # 高级模式:FacetConfig 对象
              else:
                  # 此时 config 应该是 FacetConfig 对象
                  field = config.field
                  facet_type = config.type
                  size = config.size
6aa246be   tangwang   问题:Pydantic 应该能自动...
534
535
536
                  agg_name = f"{field}_facet"
                  
                  if facet_type == 'terms':
6aa246be   tangwang   问题:Pydantic 应该能自动...
537
538
539
540
541
542
543
544
545
                      aggs[agg_name] = {
                          "terms": {
                              "field": field,
                              "size": size,
                              "order": {"_count": "desc"}
                          }
                      }
                  
                  elif facet_type == 'range':
ff5325fa   tangwang   修复:直接在 Searcher 层...
546
                      if config.ranges:
6aa246be   tangwang   问题:Pydantic 应该能自动...
547
548
549
                          aggs[agg_name] = {
                              "range": {
                                  "field": field,
ff5325fa   tangwang   修复:直接在 Searcher 层...
550
                                  "ranges": config.ranges
6aa246be   tangwang   问题:Pydantic 应该能自动...
551
552
553
554
                              }
                          }
          
          return aggs