Debian Codegraph @

docs/07_faceting.rst

raw
1 .. _faceting-label:
2
3 Faceting
4 ========
5
6 Faceting is a way of grouping and narrowing search results by a common factor, for example we can group
7 all results which are registered on a certain date. Similar to :ref:`more-like-this-label`, the faceting
8 functionality is implemented by setting up a special ``^search/facets/$`` route on any view which inherits from the
9 :class:`drf_haystack.mixins.FacetMixin` class.
10
11
12 .. note::
13
14 Options used for faceting is **not** portable across search backends. Make sure to provide
15 options suitable for the backend you're using.
16
17
18 First, read the `Haystack faceting docs <https://django-haystack.readthedocs.io/en/latest/faceting.html>`_ and set up
19 your search index for faceting.
20
21 Serializing faceted counts
22 --------------------------
23
24 Faceting is a little special in terms that it *does not* care about SearchQuerySet filtering. Faceting is performed
25 by calling the ``SearchQuerySet().facet(field, **options)`` and ``SearchQuerySet().date_facet(field, **options)``
26 methods, which will apply facets to the SearchQuerySet. Next we need to call the ``SearchQuerySet().facet_counts()``
27 in order to retrieve a dictionary with all the *counts* for the faceted fields.
28 We have a special :class:`drf_haystack.serializers.HaystackFacetSerializer` class which is designed to serialize
29 these results.
30
31 .. tip::
32
33 It *is* possible to perform faceting on a subset of the queryset, in which case you'd have to override the
34 ``get_queryset()`` method of the view to limit the queryset before it is passed on to the
35 ``filter_facet_queryset()`` method.
36
37 Any serializer subclassed from the ``HaystackFacetSerializer`` is expected to have a ``field_options`` dictionary
38 containing a set of default options passed to ``facet()`` and ``date_facet()``.
39
40 **Facet serializer example**
41
42 .. code-block:: python
43
44 class PersonFacetSerializer(HaystackFacetSerializer):
45
46 serialize_objects = False # Setting this to True will serialize the
47 # queryset into an `objects` list. This
48 # is useful if you need to display the faceted
49 # results. Defaults to False.
50 class Meta:
51 index_classes = [PersonIndex]
52 fields = ["firstname", "lastname", "created"]
53 field_options = {
54 "firstname": {},
55 "lastname": {},
56 "created": {
57 "start_date": datetime.now() - timedelta(days=3 * 365),
58 "end_date": datetime.now(),
59 "gap_by": "month",
60 "gap_amount": 3
61 }
62 }
63
64 The declared ``field_options`` will be used as default options when faceting is applied to the queryset, but can be
65 overridden by supplying query string parameters in the following format.
66
67 .. code-block:: none
68
69 ?firstname=limit:1&created=start_date:20th May 2014,gap_by:year
70
71 Each field can be fed options as ``key:value`` pairs. Multiple ``key:value`` pairs can be supplied and
72 will be separated by the ``view.lookup_sep`` attribute (which defaults to comma). Any ``start_date`` and ``end_date``
73 parameters will be parsed by the python-dateutil
74 `parser() <https://labix.org/python-dateutil#head-a23e8ae0a661d77b89dfb3476f85b26f0b30349c>`_ (which can handle most
75 common date formats).
76
77 .. note::
78
79 - The ``HaystackFacetFilter`` parses query string parameter options, separated with the ``view.lookup_sep``
80 attribute. Each option is parsed as ``key:value`` pairs where the ``:`` is a hardcoded separator. Setting
81 the ``view.lookup_sep`` attribute to ``":"`` will raise an AttributeError.
82
83 - The date parsing in the ``HaystackFacetFilter`` does intentionally blow up if fed a string format it can't
84 handle. No exception handling is done, so make sure to convert values to a format you know it can handle
85 before passing it to the filter. Ie., don't let your users feed their own values in here ;)
86
87 .. warning::
88
89 Do *not* use the ``HaystackFacetFilter`` in the regular ``filter_backends`` list on the serializer.
90 It will almost certainly produce errors or weird results. Faceting filters should go in the
91 ``facet_filter_backends`` list.
92
93 **Example serialized content**
94
95 The serialized content will look a little different than the default Haystack faceted output.
96 The top level items will *always* be **queries**, **fields** and **dates**, each containing a subset of fields
97 matching the category. In the example below, we have faceted on the fields *firstname* and *lastname*, which will
98 make them appear under the **fields** category. We also have faceted on the date field *created*, which will show up
99 under the **dates** category. Next, each faceted result will have a ``text``, ``count`` and ``narrow_url``
100 attribute which should be quite self explaining.
101
102 .. code-block:: json
103
104 {
105 "queries": {},
106 "fields": {
107 "firstname": [
108 {
109 "text": "John",
110 "count": 3,
111 "narrow_url": "http://example.com/api/v1/search/facets/?selected_facets=firstname_exact%3AJohn"
112 },
113 {
114 "text": "Randall",
115 "count": 2,
116 "narrow_url": "http://example.com/api/v1/search/facets/?selected_facets=firstname_exact%3ARandall"
117 },
118 {
119 "text": "Nehru",
120 "count": 2,
121 "narrow_url": "http://example.com/api/v1/search/facets/?selected_facets=firstname_exact%3ANehru"
122 }
123 ],
124 "lastname": [
125 {
126 "text": "Porter",
127 "count": 2,
128 "narrow_url": "http://example.com/api/v1/search/facets/?selected_facets=lastname_exact%3APorter"
129 },
130 {
131 "text": "Odonnell",
132 "count": 2,
133 "narrow_url": "http://example.com/api/v1/search/facets/?selected_facets=lastname_exact%3AOdonnell"
134 },
135 {
136 "text": "Hood",
137 "count": 2,
138 "narrow_url": "http://example.com/api/v1/search/facets/?selected_facets=lastname_exact%3AHood"
139 }
140 ]
141 },
142 "dates": {
143 "created": [
144 {
145 "text": "2015-05-15T00:00:00",
146 "count": 100,
147 "narrow_url": "http://example.com/api/v1/search/facets/?selected_facets=created_exact%3A2015-05-15+00%3A00%3A00"
148 }
149 ]
150 }
151 }
152
153
154 Serializing faceted results
155 ---------------------------
156
157 When a ``HaystackFacetSerializer`` class determines what fields to serialize, it will check
158 the ``serialize_objects`` class attribute to see if it is ``True`` or ``False``. Setting this value to ``True``
159 will add an additional ``objects`` field to the serialized results, which will contain the results for the
160 faceted ``SearchQuerySet``. The results will by default be serialized using the view's ``serializer_class``.
161 If you wish to use a different serializer for serializing the results, set the
162 :attr:`drf_haystack.mixins.FacetMixin.facet_objects_serializer_class` class attribute to whatever serializer you want
163 to use, or override the :meth:`drf_haystack.mixins.FacetMixin.get_facet_objects_serializer_class` method.
164
165 **Example faceted results with paginated serialized objects**
166
167 .. code-block:: json
168
169 {
170 "fields": {
171 "firstname": [
172 {"...": "..."}
173 ],
174 "lastname": [
175 {"...": "..."}
176 ]
177 },
178 "dates": {
179 "created": [
180 {"...": "..."}
181 ]
182 },
183 "queries": {},
184 "objects": {
185 "count": 3,
186 "next": "http://example.com/api/v1/search/facets/?page=2&selected_facets=firstname_exact%3AJohn",
187 "previous": null,
188 "results": [
189 {
190 "lastname": "Baker",
191 "firstname": "John",
192 "full_name": "John Baker",
193 "text": "John Baker\n"
194 },
195 {
196 "lastname": "McClane",
197 "firstname": "John",
198 "full_name": "John McClane",
199 "text": "John McClane\n"
200 }
201 ]
202 }
203 }
204
205
206
207 Setting up the view
208 -------------------
209
210 Any view that inherits the :class:`drf_haystack.mixins.FacetMixin` will have a special
211 `action route <http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing>`_ added as
212 ``^<view-url>/facets/$``. This view action will not care about regular filtering but will by default use the
213 ``HaystackFacetFilter`` to perform filtering.
214
215 .. note::
216
217 In order to avoid confusing the filtering mechanisms in Django Rest Framework, the ``FacetMixin``
218 class has a couple of hooks for dealing with faceting, namely:
219
220 - :attr:`drf_haystack.mixins.FacetMixin.facet_filter_backends` - A list of filter backends that will be used to
221 apply faceting to the queryset. Defaults to :class:`drf_haystack.filters.HaystackFacetFilter`, which should be
222 sufficient in most cases.
223 - :attr:`drf_haystack.mixins.FacetMixin.facet_serializer_class` - The :class:`drf_haystack.serializers.HaystackFacetSerializer`
224 instance that will be used for serializing the result.
225 - :attr:`drf_haystack.mixins.FacetMixin.facet_objects_serializer_class` - Optional. Set to the serializer class
226 which should be used for serializing faceted objects. If not set, defaults to ``self.serializer_class``.
227 - :attr:`drf_haystack.mixins.FacetMixin.filter_facet_queryset()` - Works exactly as the normal
228 :meth:`drf_haystack.generics.HaystackGenericAPIView.filter_queryset` method, but will only filter on
229 backends in the ``self.facet_filter_backends`` list.
230 - :meth:`drf_haystack.mixins.FacetMixin.get_facet_serializer_class` - Returns the ``self.facet_serializer_class``
231 class attribute.
232 - :meth:`drf_haystack.mixins.FacetMixin.get_facet_serializer` - Instantiates and returns the
233 :class:`drf_haystack.serializers.HaystackFacetSerializer` class returned from
234 :meth:`drf_haystack.mixins.FacetMixin.get_facet_serializer_class` method.
235 - :meth:`drf_haystack.mixins.FacetMixin.get_facet_objects_serializer` - Instantiates and returns the serializer
236 class which will be used to serialize faceted objects.
237 - :meth:`drf_haystack.mixins.FacetMixin.get_facet_objects_serializer_class` - Returns the
238 ``self.facet_objects_serializer_class``, or if not set, the ``self.serializer_class``.
239
240
241 In order to set up a view which can respond to regular queries under ie ``^search/$`` and faceted queries under
242 ``^search/facets/$``, we could do something like this.
243
244 We can also change the query param text from ``selected_facets`` to our own choice like ``params`` or ``p``. For this
245 to make happen please provide ``facet_query_params_text`` attribute as shown in the example.
246
247 .. code-block:: python
248
249 class SearchPersonViewSet(FacetMixin, HaystackViewSet):
250
251 index_models = [MockPerson]
252
253 # This will be used to filter and serialize regular queries as well
254 # as the results if the `facet_serializer_class` has the
255 # `serialize_objects = True` set.
256 serializer_class = SearchSerializer
257 filter_backends = [HaystackHighlightFilter, HaystackAutocompleteFilter]
258
259 # This will be used to filter and serialize faceted results
260 facet_serializer_class = PersonFacetSerializer # See example above!
261 facet_filter_backends = [HaystackFacetFilter] # This is the default facet filter, and
262 # can be left out.
263 facet_query_params_text = 'params' #Default is 'selected_facets'
264
265
266 Narrowing
267 ---------
268
269 As we have seen in the examples above, the ``HaystackFacetSerializer`` will add a ``narrow_url`` attribute to each
270 result it serializes. Follow that link to narrow the search result.
271
272 The ``narrow_url`` is constructed like this:
273
274 - Read all query parameters from the request
275 - Get a list of ``selected_facets``
276 - Update the query parameters by adding the current item to ``selected_facets``
277 - Pop the :attr:`drf_haystack.serializers.HaystackFacetSerializer.paginate_by_param` parameter if any in order to
278 always start at the first page if returning a paginated result.
279 - Return a ``serializers.Hyperlink`` with URL encoded query parameters
280
281 This means that for each drill-down performed, the original query parameters will be kept in order to make
282 the ``HaystackFacetFilter`` happy. Additionally, all the previous ``selected_facets`` will be kept and applied
283 to narrow the ``SearchQuerySet`` properly.
284
285 **Example narrowed result**
286
287 .. code-block:: json
288
289 {
290 "queries": {},
291 "fields": {
292 "firstname": [
293 {
294 "text": "John",
295 "count": 1,
296 "narrow_url": "http://example.com/api/v1/search/facets/?selected_facets=firstname_exact%3AJohn&selected_facets=lastname_exact%3AMcLaughlin"
297 }
298 ],
299 "lastname": [
300 {
301 "text": "McLaughlin",
302 "count": 1,
303 "narrow_url": "http://example.com/api/v1/search/facets/?selected_facets=firstname_exact%3AJohn&selected_facets=lastname_exact%3AMcLaughlin"
304 }
305 ]
306 },
307 "dates": {
308 "created": [
309 {
310 "text": "2015-05-15T00:00:00",
311 "count": 1,
312 "narrow_url": "http://example.com/api/v1/search/facets/?selected_facets=firstname_exact%3AJohn&selected_facets=lastname_exact%3AMcLaughlin&selected_facets=created_exact%3A2015-05-15+00%3A00%3A00"
313 }
314 ]
315 }
316 }