Blame view

search/es_query_builder.py 11.3 KB
be52af70   tangwang   first commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
  """
  Elasticsearch query builder.
  
  Converts parsed queries and search parameters into ES DSL queries.
  """
  
  from typing import Dict, Any, List, Optional
  import numpy as np
  from .boolean_parser import QueryNode
  
  
  class ESQueryBuilder:
      """Builds Elasticsearch DSL queries."""
  
      def __init__(
          self,
          index_name: str,
          match_fields: List[str],
          text_embedding_field: Optional[str] = None,
          image_embedding_field: Optional[str] = None
      ):
          """
          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
          """
          self.index_name = index_name
          self.match_fields = match_fields
          self.text_embedding_field = text_embedding_field
          self.image_embedding_field = image_embedding_field
  
      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 应该能自动...
42
          range_filters: Optional[Dict[str, Any]] = None,
be52af70   tangwang   first commit
43
44
45
46
47
48
49
50
          size: int = 10,
          from_: int = 0,
          enable_knn: bool = True,
          knn_k: int = 50,
          knn_num_candidates: int = 200,
          min_score: Optional[float] = None
      ) -> Dict[str, Any]:
          """
6aa246be   tangwang   问题:Pydantic 应该能自动...
51
          Build complete ES query (重构版).
be52af70   tangwang   first commit
52
53
54
55
56
  
          Args:
              query_text: Query text for BM25 matching
              query_vector: Query embedding for KNN search
              query_node: Parsed boolean expression tree
6aa246be   tangwang   问题:Pydantic 应该能自动...
57
58
              filters: Exact match filters
              range_filters: Range filters for numeric fields
be52af70   tangwang   first commit
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
              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_
          }
  
          # Build main query
          if query_node and query_node.operator != 'TERM':
              # Complex boolean query
              query_clause = self._build_boolean_query(query_node)
          else:
              # Simple text query
              query_clause = self._build_text_query(query_text)
  
          # Add filters if provided
6aa246be   tangwang   问题:Pydantic 应该能自动...
83
84
85
86
87
88
89
90
          if filters or range_filters:
              filter_clauses = self._build_filters(filters, range_filters)
              if filter_clauses:
                  es_query["query"] = {
                      "bool": {
                          "must": [query_clause],
                          "filter": filter_clauses
                      }
be52af70   tangwang   first commit
91
                  }
6aa246be   tangwang   问题:Pydantic 应该能自动...
92
93
              else:
                  es_query["query"] = query_clause
be52af70   tangwang   first commit
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
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
          else:
              es_query["query"] = query_clause
  
          # Add KNN search if enabled and vector provided
          if enable_knn and query_vector is not None and self.text_embedding_field:
              knn_clause = {
                  "field": self.text_embedding_field,
                  "query_vector": query_vector.tolist(),
                  "k": knn_k,
                  "num_candidates": knn_num_candidates
              }
              es_query["knn"] = knn_clause
  
          # Add minimum score filter
          if min_score is not None:
              es_query["min_score"] = min_score
  
          return es_query
  
      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 应该能自动...
198
199
200
201
202
      def _build_filters(
          self, 
          filters: Optional[Dict[str, Any]] = None,
          range_filters: Optional[Dict[str, Any]] = None
      ) -> List[Dict[str, Any]]:
be52af70   tangwang   first commit
203
          """
6aa246be   tangwang   问题:Pydantic 应该能自动...
204
205
          构建过滤子句(重构版)。
          
be52af70   tangwang   first commit
206
          Args:
6aa246be   tangwang   问题:Pydantic 应该能自动...
207
208
209
              filters: 精确匹配过滤器字典
              range_filters: 范围过滤器字典
          
be52af70   tangwang   first commit
210
          Returns:
6aa246be   tangwang   问题:Pydantic 应该能自动...
211
              ES filter子句列表
be52af70   tangwang   first commit
212
213
          """
          filter_clauses = []
6aa246be   tangwang   问题:Pydantic 应该能自动...
214
215
216
217
          
          # 1. 处理精确匹配过滤
          if filters:
              for field, value in filters.items():
c86c8237   tangwang   支持聚合。过滤项补充了逻辑,但是有问题
218
                  if isinstance(value, list):
6aa246be   tangwang   问题:Pydantic 应该能自动...
219
                      # 多值匹配(OR)
be52af70   tangwang   first commit
220
                      filter_clauses.append({
6aa246be   tangwang   问题:Pydantic 应该能自动...
221
                          "terms": {field: value}
be52af70   tangwang   first commit
222
                      })
6aa246be   tangwang   问题:Pydantic 应该能自动...
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
                  else:
                      # 单值精确匹配
                      filter_clauses.append({
                          "term": {field: value}
                      })
          
          # 2. 处理范围过滤
          if range_filters:
              for field, range_spec in range_filters.items():
                  # 构建范围查询
                  range_conditions = {}
                  if isinstance(range_spec, dict):
                      for op in ['gte', 'gt', 'lte', 'lt']:
                          if op in range_spec and range_spec[op] is not None:
                              range_conditions[op] = range_spec[op]
                  
                  if range_conditions:
                      filter_clauses.append({
                          "range": {field: range_conditions}
                      })
          
be52af70   tangwang   first commit
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
          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   支持聚合。过滤项补充了逻辑,但是有问题
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
      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 应该能自动...
321
      def build_facets(
be52af70   tangwang   first commit
322
          self,
6aa246be   tangwang   问题:Pydantic 应该能自动...
323
          facet_configs: Optional[List[Any]] = None
be52af70   tangwang   first commit
324
325
      ) -> Dict[str, Any]:
          """
6aa246be   tangwang   问题:Pydantic 应该能自动...
326
327
          构建分面聚合(重构版)。
          
be52af70   tangwang   first commit
328
          Args:
6aa246be   tangwang   问题:Pydantic 应该能自动...
329
330
331
332
              facet_configs: 分面配置列表。可以是:
                  - 字符串列表:字段名,使用默认配置
                  - 配置对象列表:详细的分面配置
          
be52af70   tangwang   first commit
333
          Returns:
6aa246be   tangwang   问题:Pydantic 应该能自动...
334
              ES aggregations字典
be52af70   tangwang   first commit
335
          """
6aa246be   tangwang   问题:Pydantic 应该能自动...
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
          if not facet_configs:
              return {}
          
          aggs = {}
          
          for config in facet_configs:
              # 1. 简单模式:只有字段名
              if isinstance(config, str):
                  field = config
                  agg_name = f"{field}_facet"
                  aggs[agg_name] = {
                      "terms": {
                          "field": field,
                          "size": 10,  # 默认大小
                          "order": {"_count": "desc"}
                      }
be52af70   tangwang   first commit
352
                  }
6aa246be   tangwang   问题:Pydantic 应该能自动...
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
              
              # 2. 高级模式:详细配置对象
              elif isinstance(config, dict):
                  field = config['field']
                  facet_type = config.get('type', 'terms')
                  size = config.get('size', 10)
                  agg_name = f"{field}_facet"
                  
                  if facet_type == 'terms':
                      # Terms 聚合(分组统计)
                      aggs[agg_name] = {
                          "terms": {
                              "field": field,
                              "size": size,
                              "order": {"_count": "desc"}
                          }
                      }
                  
                  elif facet_type == 'range':
                      # Range 聚合(范围统计)
                      ranges = config.get('ranges', [])
                      if ranges:
                          aggs[agg_name] = {
                              "range": {
                                  "field": field,
                                  "ranges": ranges
                              }
                          }
          
          return aggs