File: 05_more_like_this.rst

package info (click to toggle)
drf-haystack 1.8.4-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 584 kB
  • sloc: python: 2,594; makefile: 147
file content (64 lines) | stat: -rw-r--r-- 2,077 bytes parent folder | download
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
.. _more-like-this-label:

More Like This
==============

Some search backends supports ``More Like This`` features. In order to take advantage of this,
we have a mixin class :class:`drf_haystack.mixins.MoreLikeThisMixin`, which will append a ``more-like-this``
detail route to the base name of the ViewSet. Lets say you have a router which looks like this:

.. code-block:: python

    router = routers.DefaultRouter()
    router.register("search", viewset=SearchViewSet, base_name="search")  # MLT name will be 'search-more-like-this'.

    urlpatterns = patterns(
        "",
        url(r"^", include(router.urls))
    )

The important thing here is that the ``SearchViewSet`` class inherits from the
:class:`drf_haystack.mixins.MoreLikeThisMixin` class in order to get the ``more-like-this`` route automatically added.
The view name will be ``{base_name}-more-like-this``, which in this case would be for example ``search-more-like-this``.


Serializing the More Like This URL
----------------------------------

In order to include the ``more-like-this`` url in your result you only have to add a ``HyperlinkedIdentityField``
to your serializer.
Something like this should work okay.

**Example serializer with More Like This**

.. code-block:: python

    class SearchSerializer(HaystackSerializer):

        more_like_this = serializers.HyperlinkedIdentityField(view_name="search-more-like-this", read_only=True)

        class Meta:
            index_classes = [PersonIndex]
            fields = ["firstname", "lastname", "full_name"]


    class SearchViewSet(MoreLikeThisMixin, HaystackViewSet):
        index_models = [Person]
        serializer_class = SearchSerializer


Now, every result you render with this serializer will include a ``more_like_this`` field containing the url
for similar results.

Example response

.. code-block:: json

    [
        {
            "full_name": "Jeremy Rowland",
            "lastname": "Rowland",
            "firstname": "Jeremy",
            "more_like_this": "http://example.com/search/5/more-like-this/"
        }
    ]