| 1 |
.. _autocomplete-label: |
| 2 |
|
| 3 |
Autocomplete |
| 4 |
============ |
| 5 |
|
| 6 |
Some kind of data such as ie. cities and zip codes could be useful to autocomplete. |
| 7 |
We have a Django REST Framework filter for performing autocomplete queries. It works |
| 8 |
quite like the regular :class:`drf_haystack.filters.HaystackFilter` but *must* be run |
| 9 |
against an ``NgramField`` or ``EdgeNgramField`` in order to work properly. The main |
| 10 |
difference is that while the HaystackFilter performs a bitwise ``OR`` on terms for the |
| 11 |
same parameters, the :class:`drf_haystack.filters.HaystackAutocompleteFilter` reduce query |
| 12 |
parameters down to a single filter (using an ``SQ`` object), and performs a bitwise ``AND``. |
| 13 |
|
| 14 |
By adding a list or tuple of ``ignore_fields`` to the serializer's Meta class, |
| 15 |
we can tell the REST framework to ignore these fields. This is handy in cases, |
| 16 |
where you do not want to serialize and transfer the content of a text, or n-gram |
| 17 |
index down to the client. |
| 18 |
|
| 19 |
An example using the autocomplete filter might look something like this. |
| 20 |
|
| 21 |
|
| 22 |
.. code-block:: python |
| 23 |
|
| 24 |
from drf_haystack.filters import HaystackAutocompleteFilter |
| 25 |
from drf_haystack.serializers import HaystackSerializer |
| 26 |
from drf_haystack.viewsets import HaystackViewSet |
| 27 |
|
| 28 |
class AutocompleteSerializer(HaystackSerializer): |
| 29 |
|
| 30 |
class Meta: |
| 31 |
index_classes = [LocationIndex] |
| 32 |
fields = ["address", "city", "zip_code", "autocomplete"] |
| 33 |
ignore_fields = ["autocomplete"] |
| 34 |
|
| 35 |
# The `field_aliases` attribute can be used in order to alias a |
| 36 |
# query parameter to a field attribute. In this case a query like |
| 37 |
# /search/?q=oslo would alias the `q` parameter to the `autocomplete` |
| 38 |
# field on the index. |
| 39 |
field_aliases = { |
| 40 |
"q": "autocomplete" |
| 41 |
} |
| 42 |
|
| 43 |
class AutocompleteSearchViewSet(HaystackViewSet): |
| 44 |
|
| 45 |
index_models = [Location] |
| 46 |
serializer_class = AutocompleteSerializer |
| 47 |
filter_backends = [HaystackAutocompleteFilter] |
| 48 |
|