2
0

indexing.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. .. _wagtailsearch_indexing:
  2. ========
  3. Indexing
  4. ========
  5. To make a model searchable, you'll need to add it into the search index. All pages, images and documents are indexed for you, so you can start searching them right away.
  6. If you have created some extra fields in a subclass of Page or Image, you may want to add these new fields to the search index too so that a user's search query will match on their content. See :ref:`wagtailsearch_indexing_fields` for info on how to do this.
  7. If you have a custom model that you would like to make searchable, see :ref:`wagtailsearch_indexing_models`.
  8. .. _wagtailsearch_indexing_update:
  9. Updating the index
  10. ==================
  11. If the search index is kept separate from the database (when using Elasticsearch for example), you need to keep them both in sync. There are two ways to do this: using the search signal handlers, or calling the ``update_index`` command periodically. For best speed and reliability, it's best to use both if possible.
  12. Signal handlers
  13. ---------------
  14. ``wagtailsearch`` provides some signal handlers which bind to the save/delete signals of all indexed models. This would automatically add and delete them from all backends you have registered in ``WAGTAILSEARCH_BACKENDS``. These signal handlers are automatically registered when the ``wagtail.search`` app is loaded.
  15. In some cases, you may not want your content to be automatically reindexed and instead rely on the ``update_index`` command for indexing. If you need to disable these signal handlers, use one of the following methods:
  16. Disabling auto update signal handlers for a model
  17. `````````````````````````````````````````````````
  18. You can disable the signal handlers for an individual model by adding ``search_auto_update = False`` as an attribute on the model class.
  19. Disabling auto update signal handlers for a search backend/whole site
  20. `````````````````````````````````````````````````````````````````````
  21. You can disable the signal handlers for a whole search backend by setting the ``AUTO_UPDATE`` setting on the backend to ``False``.
  22. If all search backends have ``AUTO_UPDATE`` set to ``False``, the signal handlers will be completely disabled for the whole site.
  23. For documentation on the ``AUTO_UPDATE`` setting, see :ref:`wagtailsearch_backends_auto_update`.
  24. The ``update_index`` command
  25. ----------------------------
  26. Wagtail also provides a command for rebuilding the index from scratch.
  27. :code:`./manage.py update_index`
  28. It is recommended to run this command once a week and at the following times:
  29. - whenever any pages have been created through a script (after an import, for example)
  30. - whenever any changes have been made to models or search configuration
  31. The search may not return any results while this command is running, so avoid running it at peak times.
  32. .. note::
  33. The ``update_index`` command is also aliased as ``wagtail_update_index``, for use when another installed package (such as `Haystack <https://haystacksearch.org/>`_) provides a conflicting ``update_index`` command. In this case, the other package's entry in ``INSTALLED_APPS`` should appear above ``wagtail.search`` so that its ``update_index`` command takes precedence over Wagtail's.
  34. .. _wagtailsearch_indexing_fields:
  35. Indexing extra fields
  36. =====================
  37. Fields must be explicitly added to the ``search_fields`` property of your ``Page``-derived model, in order for you to be able to search/filter on them. This is done by overriding ``search_fields`` to append a list of extra ``SearchField``/``FilterField`` objects to it.
  38. Example
  39. -------
  40. This creates an ``EventPage`` model with two fields: ``description`` and ``date``. ``description`` is indexed as a ``SearchField`` and ``date`` is indexed as a ``FilterField``
  41. .. code-block:: python
  42. from wagtail.search import index
  43. from django.utils import timezone
  44. class EventPage(Page):
  45. description = models.TextField()
  46. date = models.DateField()
  47. search_fields = Page.search_fields + [ # Inherit search_fields from Page
  48. index.SearchField('description'),
  49. index.FilterField('date'),
  50. ]
  51. # Get future events which contain the string "Christmas" in the title or description
  52. >>> EventPage.objects.filter(date__gt=timezone.now()).search("Christmas")
  53. .. _wagtailsearch_index_searchfield:
  54. ``index.SearchField``
  55. ---------------------
  56. These are used for performing full-text searches on your models, usually for text fields.
  57. Options
  58. ```````
  59. - **partial_match** (``boolean``) - Setting this to true allows results to be matched on parts of words. For example, this is set on the title field by default, so a page titled ``Hello World!`` will be found if the user only types ``Hel`` into the search box.
  60. - **boost** (``int/float``) - This allows you to set fields as being more important than others. Setting this to a high number on a field will cause pages with matches in that field to be ranked higher. By default, this is set to 2 on the Page title field and 1 on all other fields.
  61. - **es_extra** (``dict``) - This field is to allow the developer to set or override any setting on the field in the Elasticsearch mapping. Use this if you want to make use of any Elasticsearch features that are not yet supported in Wagtail.
  62. .. _wagtailsearch_index_filterfield:
  63. ``index.AutocompleteField``
  64. ---------------------------
  65. These are used for autocomplete queries which match partial words. For example, a page titled ``Hello World!`` will be found if the user only types ``Hel`` into the search box.
  66. This takes the exact same options as ``index.SearchField`` (with the exception of ``partial_match``, which has no effect).
  67. .. tip::
  68. Only index fields that are displayed in the search results with ``index.AutocompleteField``. This allows users to see any words that were partial-matched on.
  69. ``index.FilterField``
  70. ---------------------
  71. These are added to the search index but are not used for full-text searches. Instead, they allow you to run filters on your search results.
  72. .. _wagtailsearch_index_relatedfields:
  73. ``index.RelatedFields``
  74. -----------------------
  75. This allows you to index fields from related objects. It works on all types of related fields, including their reverse accessors.
  76. For example, if we have a book that has a ``ForeignKey`` to its author, we can nest the author's ``name`` and ``date_of_birth`` fields inside the book:
  77. .. code-block:: python
  78. from wagtail.search import index
  79. class Book(models.Model, index.Indexed):
  80. ...
  81. search_fields = [
  82. index.SearchField('title'),
  83. index.FilterField('published_date'),
  84. index.RelatedFields('author', [
  85. index.SearchField('name'),
  86. index.FilterField('date_of_birth'),
  87. ]),
  88. ]
  89. This will allow you to search for books by their author's name.
  90. It works the other way around as well. You can index an author's books, allowing an author to be searched for by the titles of books they've published:
  91. .. code-block:: python
  92. from wagtail.search import index
  93. class Author(models.Model, index.Indexed):
  94. ...
  95. search_fields = [
  96. index.SearchField('name'),
  97. index.FilterField('date_of_birth'),
  98. index.RelatedFields('books', [
  99. index.SearchField('title'),
  100. index.FilterField('published_date'),
  101. ]),
  102. ]
  103. .. topic:: Filtering on ``index.RelatedFields``
  104. It's not possible to filter on any ``index.FilterFields`` within ``index.RelatedFields`` using the ``QuerySet`` API. However, the fields are indexed, so it should be possible to use them by querying Elasticsearch manually.
  105. Filtering on ``index.RelatedFields`` with the ``QuerySet`` API is planned for a future release of Wagtail.
  106. .. _wagtailsearch_indexing_callable_fields:
  107. Indexing callables and other attributes
  108. ---------------------------------------
  109. .. note::
  110. This is not supported in the :ref:`wagtailsearch_backends_database`
  111. Search/filter fields do not need to be Django model fields. They can also be any method or attribute on your model class.
  112. One use for this is indexing the ``get_*_display`` methods Django creates automatically for fields with choices.
  113. .. code-block:: python
  114. from wagtail.search import index
  115. class EventPage(Page):
  116. IS_PRIVATE_CHOICES = (
  117. (False, "Public"),
  118. (True, "Private"),
  119. )
  120. is_private = models.BooleanField(choices=IS_PRIVATE_CHOICES)
  121. search_fields = Page.search_fields + [
  122. # Index the human-readable string for searching.
  123. index.SearchField('get_is_private_display'),
  124. # Index the boolean value for filtering.
  125. index.FilterField('is_private'),
  126. ]
  127. Callables also provide a way to index fields from related models. In the example from :ref:`inline_panels`, to index each BookPage by the titles of its related_links:
  128. .. code-block:: python
  129. class BookPage(Page):
  130. # ...
  131. def get_related_link_titles(self):
  132. # Get list of titles and concatenate them
  133. return '\n'.join(self.related_links.all().values_list('name', flat=True))
  134. search_fields = Page.search_fields + [
  135. # ...
  136. index.SearchField('get_related_link_titles'),
  137. ]
  138. .. _wagtailsearch_indexing_models:
  139. Indexing custom models
  140. ======================
  141. Any Django model can be indexed and searched.
  142. To do this, inherit from ``index.Indexed`` and add some ``search_fields`` to the model.
  143. .. code-block:: python
  144. from wagtail.search import index
  145. class Book(index.Indexed, models.Model):
  146. title = models.CharField(max_length=255)
  147. genre = models.CharField(max_length=255, choices=GENRE_CHOICES)
  148. author = models.ForeignKey(Author, on_delete=models.CASCADE)
  149. published_date = models.DateTimeField()
  150. search_fields = [
  151. index.SearchField('title', partial_match=True, boost=10),
  152. index.SearchField('get_genre_display'),
  153. index.FilterField('genre'),
  154. index.FilterField('author'),
  155. index.FilterField('published_date'),
  156. ]
  157. # As this model doesn't have a search method in its QuerySet, we have to call search directly on the backend
  158. >>> from wagtail.search.backends import get_search_backend
  159. >>> s = get_search_backend()
  160. # Run a search for a book by Roald Dahl
  161. >>> roald_dahl = Author.objects.get(name="Roald Dahl")
  162. >>> s.search("chocolate factory", Book.objects.filter(author=roald_dahl))
  163. [<Book: Charlie and the chocolate factory>]