Debian Codegraph @

drf_haystack/query.py

raw
1 # -*- coding: utf-8 -*-
2
3 from __future__ import absolute_import, unicode_literals
4
5 import operator
6 import six
7 import warnings
8 from itertools import chain
9
10
11 from six.moves import zip
12 from dateutil import parser
13
14 from drf_haystack import constants
15 from drf_haystack.utils import merge_dict
16
17
18 class BaseQueryBuilder(object):
19 """
20 Query builder base class.
21 """
22
23 def __init__(self, backend, view):
24 self.backend = backend
25 self.view = view
26
27 def build_query(self, **filters):
28 """
29 :param dict[str, list[str]] filters: is an expanded QueryDict or
30 a mapping of keys to a list of parameters.
31 """
32 raise NotImplementedError("You should override this method in subclasses.")
33
34 @staticmethod
35 def tokenize(stream, separator):
36 """
37 Tokenize and yield query parameter values.
38
39 :param stream: Input value
40 :param separator: Character to use to separate the tokens.
41 :return:
42 """
43 for value in stream:
44 for token in value.split(separator):
45 if token:
46 yield token.strip()
47
48
49 class BoostQueryBuilder(BaseQueryBuilder):
50 """
51 Query builder class for adding boost to queries.
52 """
53
54 def build_query(self, **filters):
55
56 applicable_filters = None
57 query_param = getattr(self.backend, "query_param", None)
58
59 value = filters.pop(query_param, None)
60 if value:
61 try:
62 term, val = chain.from_iterable(zip(self.tokenize(value, self.view.lookup_sep)))
63 except ValueError:
64 raise ValueError("Cannot convert the '%s' query parameter to a valid boost filter."
65 % query_param)
66 else:
67 try:
68 applicable_filters = {"term": term, "boost": float(val)}
69 except ValueError:
70 raise ValueError("Cannot convert boost to float value. Make sure to provide a "
71 "numerical boost value.")
72
73 return applicable_filters
74
75
76 class FilterQueryBuilder(BaseQueryBuilder):
77 """
78 Query builder class suitable for doing basic filtering.
79 """
80
81 def __init__(self, backend, view):
82 super(FilterQueryBuilder, self).__init__(backend, view)
83
84 assert getattr(self.backend, "default_operator", None) in (operator.and_, operator.or_), (
85 "%(cls)s.default_operator must be either 'operator.and_' or 'operator.or_'." % {
86 "cls": self.backend.__class__.__name__
87 })
88 self.default_operator = self.backend.default_operator
89 self.default_same_param_operator = getattr(self.backend, "default_same_param_operator", self.default_operator)
90
91 def get_same_param_operator(self, param):
92 """
93 Helper method to allow per param configuration of which operator should be used when multiple filters for the
94 same param are found.
95
96 :param str param: is the param for which you want to get the operator
97 :return: Either operator.or_ or operator.and_
98 """
99 return self.default_same_param_operator
100
101 def build_query(self, **filters):
102 """
103 Creates a single SQ filter from querystring parameters that correspond to the SearchIndex fields
104 that have been "registered" in `view.fields`.
105
106 Default behavior is to `OR` terms for the same parameters, and `AND` between parameters. Any
107 querystring parameters that are not registered in `view.fields` will be ignored.
108
109 :param dict[str, list[str]] filters: is an expanded QueryDict or a mapping of keys to a list of
110 parameters.
111 """
112
113 applicable_filters = []
114 applicable_exclusions = []
115
116 for param, value in filters.items():
117 excluding_term = False
118 param_parts = param.split("__")
119 base_param = param_parts[0] # only test against field without lookup
120 negation_keyword = constants.DRF_HAYSTACK_NEGATION_KEYWORD
121 if len(param_parts) > 1 and param_parts[1] == negation_keyword:
122 excluding_term = True
123 param = param.replace("__%s" % negation_keyword, "") # haystack wouldn't understand our negation
124
125 if self.view.serializer_class:
126 if hasattr(self.view.serializer_class.Meta, 'field_aliases'):
127 old_base = base_param
128 base_param = self.view.serializer_class.Meta.field_aliases.get(base_param, base_param)
129 param = param.replace(old_base, base_param) # need to replace the alias
130
131 fields = getattr(self.view.serializer_class.Meta, 'fields', [])
132 exclude = getattr(self.view.serializer_class.Meta, 'exclude', [])
133 search_fields = getattr(self.view.serializer_class.Meta, 'search_fields', [])
134
135 # Skip if the parameter is not listed in the serializer's `fields`
136 # or if it's in the `exclude` list.
137 if ((fields or search_fields) and base_param not in
138 chain(fields, search_fields)) or base_param in exclude or not value:
139 continue
140
141 param_queries = []
142 if len(param_parts) > 1 and param_parts[-1] in ('in', 'range'):
143 # `in` and `range` filters expects a list of values
144 param_queries.append(self.view.query_object((param, list(self.tokenize(value, self.view.lookup_sep)))))
145 else:
146 for token in self.tokenize(value, self.view.lookup_sep):
147 param_queries.append(self.view.query_object((param, token)))
148
149 param_queries = [pq for pq in param_queries if pq]
150 if len(param_queries) > 0:
151 term = six.moves.reduce(self.get_same_param_operator(param), param_queries)
152 if excluding_term:
153 applicable_exclusions.append(term)
154 else:
155 applicable_filters.append(term)
156
157 applicable_filters = six.moves.reduce(
158 self.default_operator, filter(lambda x: x, applicable_filters)) if applicable_filters else self.view.query_object()
159
160 applicable_exclusions = six.moves.reduce(
161 self.default_operator, filter(lambda x: x, applicable_exclusions)) if applicable_exclusions else self.view.query_object()
162
163 return applicable_filters, applicable_exclusions
164
165
166 class FacetQueryBuilder(BaseQueryBuilder):
167 """
168 Query builder class suitable for constructing faceted queries.
169 """
170
171 def build_query(self, **filters):
172 """
173 Creates a dict of dictionaries suitable for passing to the SearchQuerySet `facet`,
174 `date_facet` or `query_facet` method. All key word arguments should be wrapped in a list.
175
176 :param view: API View
177 :param dict[str, list[str]] filters: is an expanded QueryDict or a mapping
178 of keys to a list of parameters.
179 """
180 field_facets = {}
181 date_facets = {}
182 query_facets = {}
183 facet_serializer_cls = self.view.get_facet_serializer_class()
184
185 if self.view.lookup_sep == ":":
186 raise AttributeError("The %(cls)s.lookup_sep attribute conflicts with the HaystackFacetFilter "
187 "query parameter parser. Please choose another `lookup_sep` attribute "
188 "for %(cls)s." % {"cls": self.view.__class__.__name__})
189
190 fields = facet_serializer_cls.Meta.fields
191 exclude = facet_serializer_cls.Meta.exclude
192 field_options = facet_serializer_cls.Meta.field_options
193
194 for field, options in filters.items():
195
196 if field not in fields or field in exclude:
197 continue
198
199 field_options = merge_dict(field_options, {field: self.parse_field_options(self.view.lookup_sep, *options)})
200
201 valid_gap = ("year", "month", "day", "hour", "minute", "second")
202 for field, options in field_options.items():
203 if any([k in options for k in ("start_date", "end_date", "gap_by", "gap_amount")]):
204
205 if not all(("start_date", "end_date", "gap_by" in options)):
206 raise ValueError("Date faceting requires at least 'start_date', 'end_date' "
207 "and 'gap_by' to be set.")
208
209 if not options["gap_by"] in valid_gap:
210 raise ValueError("The 'gap_by' parameter must be one of %s." % ", ".join(valid_gap))
211
212 options.setdefault("gap_amount", 1)
213 date_facets[field] = field_options[field]
214
215 else:
216 field_facets[field] = field_options[field]
217
218 return {
219 "date_facets": date_facets,
220 "field_facets": field_facets,
221 "query_facets": query_facets
222 }
223
224 def parse_field_options(self, *options):
225 """
226 Parse the field options query string and return it as a dictionary.
227 """
228 defaults = {}
229 for option in options:
230 if isinstance(option, six.text_type):
231 tokens = [token.strip() for token in option.split(self.view.lookup_sep)]
232
233 for token in tokens:
234 if not len(token.split(":")) == 2:
235 warnings.warn("The %s token is not properly formatted. Tokens need to be "
236 "formatted as 'token:value' pairs." % token)
237 continue
238
239 param, value = token.split(":", 1)
240
241 if any([k == param for k in ("start_date", "end_date", "gap_amount")]):
242
243 if param in ("start_date", "end_date"):
244 value = parser.parse(value)
245
246 if param == "gap_amount":
247 value = int(value)
248
249 defaults[param] = value
250
251 return defaults
252
253
254 class SpatialQueryBuilder(BaseQueryBuilder):
255 """
256 Query builder class suitable for construction spatial queries.
257 """
258
259 def __init__(self, backend, view):
260 super(SpatialQueryBuilder, self).__init__(backend, view)
261
262 assert getattr(self.backend, "point_field", None) is not None, (
263 "%(cls)s.point_field cannot be None. Set the %(cls)s.point_field "
264 "to the name of the `LocationField` you want to filter on your index class." % {
265 "cls": self.backend.__class__.__name__
266 })
267
268 try:
269 from haystack.utils.geo import D, Point
270 self.D = D
271 self.Point = Point
272 except ImportError:
273 warnings.warn("Make sure you've installed the `libgeos` library. "
274 "Run `apt-get install libgeos` on debian based linux systems, "
275 "or `brew install geos` on OS X.")
276 raise
277
278 def build_query(self, **filters):
279 """
280 Build queries for geo spatial filtering.
281
282 Expected query parameters are:
283 - a `unit=value` parameter where the unit is a valid UNIT in the
284 `django.contrib.gis.measure.Distance` class.
285 - `from` which must be a comma separated latitude and longitude.
286
287 Example query:
288 /api/v1/search/?km=10&from=59.744076,10.152045
289
290 Will perform a `dwithin` query within 10 km from the point
291 with latitude 59.744076 and longitude 10.152045.
292 """
293
294 applicable_filters = None
295
296 filters = dict((k, filters[k]) for k in chain(self.D.UNITS.keys(),
297 [constants.DRF_HAYSTACK_SPATIAL_QUERY_PARAM]) if k in filters)
298 distance = dict((k, v) for k, v in filters.items() if k in self.D.UNITS.keys())
299
300 try:
301 latitude, longitude = map(float, self.tokenize(filters[constants.DRF_HAYSTACK_SPATIAL_QUERY_PARAM],
302 self.view.lookup_sep))
303 point = self.Point(longitude, latitude, srid=constants.GEO_SRID)
304 except ValueError:
305 raise ValueError("Cannot convert `from=latitude,longitude` query parameter to "
306 "float values. Make sure to provide numerical values only!")
307 except KeyError:
308 # If the user has not provided any `from` query string parameter,
309 # just return.
310 pass
311 else:
312 for unit in distance.keys():
313 if not len(distance[unit]) == 1:
314 raise ValueError("Each unit must have exactly one value.")
315 distance[unit] = float(distance[unit][0])
316
317 if point and distance:
318 applicable_filters = {
319 "dwithin": {
320 "field": self.backend.point_field,
321 "point": point,
322 "distance": self.D(**distance)
323 },
324 "distance": {
325 "field": self.backend.point_field,
326 "point": point
327 }
328 }
329
330 return applicable_filters