| 1 |
.. _more-like-this-label: |
| 2 |
|
| 3 |
More Like This |
| 4 |
============== |
| 5 |
|
| 6 |
Some search backends supports ``More Like This`` features. In order to take advantage of this, |
| 7 |
we have a mixin class :class:`drf_haystack.mixins.MoreLikeThisMixin`, which will append a ``more-like-this`` |
| 8 |
detail route to the base name of the ViewSet. Lets say you have a router which looks like this: |
| 9 |
|
| 10 |
.. code-block:: python |
| 11 |
|
| 12 |
router = routers.DefaultRouter() |
| 13 |
router.register("search", viewset=SearchViewSet, basename="search") # MLT name will be 'search-more-like-this'. |
| 14 |
|
| 15 |
urlpatterns = patterns( |
| 16 |
"", |
| 17 |
url(r"^", include(router.urls)) |
| 18 |
) |
| 19 |
|
| 20 |
The important thing here is that the ``SearchViewSet`` class inherits from the |
| 21 |
:class:`drf_haystack.mixins.MoreLikeThisMixin` class in order to get the ``more-like-this`` route automatically added. |
| 22 |
The view name will be ``{basename}-more-like-this``, which in this case would be for example ``search-more-like-this``. |
| 23 |
|
| 24 |
|
| 25 |
Serializing the More Like This URL |
| 26 |
---------------------------------- |
| 27 |
|
| 28 |
In order to include the ``more-like-this`` url in your result you only have to add a ``HyperlinkedIdentityField`` |
| 29 |
to your serializer. |
| 30 |
Something like this should work okay. |
| 31 |
|
| 32 |
**Example serializer with More Like This** |
| 33 |
|
| 34 |
.. code-block:: python |
| 35 |
|
| 36 |
class SearchSerializer(HaystackSerializer): |
| 37 |
|
| 38 |
more_like_this = serializers.HyperlinkedIdentityField(view_name="search-more-like-this", read_only=True) |
| 39 |
|
| 40 |
class Meta: |
| 41 |
index_classes = [PersonIndex] |
| 42 |
fields = ["firstname", "lastname", "full_name"] |
| 43 |
|
| 44 |
|
| 45 |
class SearchViewSet(MoreLikeThisMixin, HaystackViewSet): |
| 46 |
index_models = [Person] |
| 47 |
serializer_class = SearchSerializer |
| 48 |
|
| 49 |
|
| 50 |
Now, every result you render with this serializer will include a ``more_like_this`` field containing the url |
| 51 |
for similar results. |
| 52 |
|
| 53 |
Example response |
| 54 |
|
| 55 |
.. code-block:: json |
| 56 |
|
| 57 |
[ |
| 58 |
{ |
| 59 |
"full_name": "Jeremy Rowland", |
| 60 |
"lastname": "Rowland", |
| 61 |
"firstname": "Jeremy", |
| 62 |
"more_like_this": "http://example.com/search/5/more-like-this/" |
| 63 |
} |
| 64 |
] |