2
0

searching.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. .. _wagtailsearch_searching:
  2. =========
  3. Searching
  4. =========
  5. .. _wagtailsearch_searching_pages:
  6. Searching QuerySets
  7. ===================
  8. Wagtail search is built on Django's `QuerySet API <https://docs.djangoproject.com/en/stable/ref/models/querysets/>`_. You should be able to search any Django QuerySet provided the model and the fields being filtered on have been added to the search index.
  9. Searching Pages
  10. ---------------
  11. Wagtail provides a shortcut for searching pages: the ``.search()`` ``QuerySet`` method. You can call this on any ``PageQuerySet``. For example:
  12. .. code-block:: python
  13. # Search future EventPages
  14. >>> from wagtail.core.models import EventPage
  15. >>> EventPage.objects.filter(date__gt=timezone.now()).search("Hello world!")
  16. All other methods of ``PageQuerySet`` can be used with ``search()``. For example:
  17. .. code-block:: python
  18. # Search all live EventPages that are under the events index
  19. >>> EventPage.objects.live().descendant_of(events_index).search("Event")
  20. [<EventPage: Event 1>, <EventPage: Event 2>]
  21. .. note::
  22. The ``search()`` method will convert your ``QuerySet`` into an instance of one of Wagtail's ``SearchResults`` classes (depending on backend). This means that you must perform filtering before calling ``search()``.
  23. .. _wagtailsearch_images_documents_custom_models:
  24. Searching Images, Documents and custom models
  25. ---------------------------------------------
  26. Wagtail's document and image models provide a ``search`` method on their QuerySets, just as pages do:
  27. .. code-block:: python
  28. >>> from wagtail.images.models import Image
  29. >>> Image.objects.filter(uploaded_by_user=user).search("Hello")
  30. [<Image: Hello>, <Image: Hello world!>]
  31. :ref:`Custom models <wagtailsearch_indexing_models>` can be searched by using the ``search`` method on the search backend directly:
  32. .. code-block:: python
  33. >>> from myapp.models import Book
  34. >>> from wagtail.search.backends import get_search_backend
  35. # Search books
  36. >>> s = get_search_backend()
  37. >>> s.search("Great", Book)
  38. [<Book: Great Expectations>, <Book: The Great Gatsby>]
  39. You can also pass a QuerySet into the ``search`` method which allows you to add filters to your search results:
  40. .. code-block:: python
  41. >>> from myapp.models import Book
  42. >>> from wagtail.search.backends import get_search_backend
  43. # Search books
  44. >>> s = get_search_backend()
  45. >>> s.search("Great", Book.objects.filter(published_date__year__lt=1900))
  46. [<Book: Great Expectations>]
  47. .. _wagtailsearch_specifying_fields:
  48. Specifying the fields to search
  49. -------------------------------
  50. By default, Wagtail will search all fields that have been indexed using ``index.SearchField``.
  51. This can be limited to a certain set of fields by using the ``fields`` keyword argument:
  52. .. code-block:: python
  53. # Search just the title field
  54. >>> EventPage.objects.search("Event", fields=["title"])
  55. [<EventPage: Event 1>, <EventPage: Event 2>]
  56. .. _wagtailsearch_faceted_search:
  57. Faceted search
  58. --------------
  59. Wagtail supports faceted search which is a kind of filtering based on a taxonomy
  60. field (such as category or page type).
  61. The ``.facet(field_name)`` method returns an ``OrderedDict``. The keys are
  62. the IDs of the related objects that have been referenced by the specified field, and the
  63. values are the number of references found for each ID. The results are ordered by number
  64. of references descending.
  65. For example, to find the most common page types in the search results:
  66. .. code-block:: python
  67. >>> Page.objects.search("Test").facet("content_type_id")
  68. # Note: The keys correspond to the ID of a ContentType object; the values are the
  69. # number of pages returned for that type
  70. OrderedDict([
  71. ('2', 4), # 4 pages have content_type_id == 2
  72. ('1', 2), # 2 pages have content_type_id == 1
  73. ])
  74. Changing search behaviour
  75. -------------------------
  76. Search operator
  77. ^^^^^^^^^^^^^^^
  78. The search operator specifies how search should behave when the user has typed in multiple search terms. There are two possible values:
  79. - "or" - The results must match at least one term (default for Elasticsearch)
  80. - "and" - The results must match all terms (default for database search)
  81. Both operators have benefits and drawbacks. The "or" operator will return many more results but will likely contain a lot of results that aren't relevant. The "and" operator only returns results that contain all search terms, but require the user to be more precise with their query.
  82. We recommend using the "or" operator when ordering by relevance and the "and" operator when ordering by anything else (note: the database backend doesn't currently support ordering by relevance).
  83. Here's an example of using the ``operator`` keyword argument:
  84. .. code-block:: python
  85. # The database contains a "Thing" model with the following items:
  86. # - Hello world
  87. # - Hello
  88. # - World
  89. # Search with the "or" operator
  90. >>> s = get_search_backend()
  91. >>> s.search("Hello world", Things, operator="or")
  92. # All records returned as they all contain either "hello" or "world"
  93. [<Thing: Hello World>, <Thing: Hello>, <Thing: World>]
  94. # Search with the "and" operator
  95. >>> s = get_search_backend()
  96. >>> s.search("Hello world", Things, operator="and")
  97. # Only "hello world" returned as that's the only item that contains both terms
  98. [<Thing: Hello world>]
  99. For page, image and document models, the ``operator`` keyword argument is also supported on the QuerySet's ``search`` method:
  100. .. code-block:: python
  101. >>> Page.objects.search("Hello world", operator="or")
  102. # All pages containing either "hello" or "world" are returned
  103. [<Page: Hello World>, <Page: Hello>, <Page: World>]
  104. Phrase searching
  105. ^^^^^^^^^^^^^^^^
  106. Phrase searching is used for finding whole sentence or phrase rather than individual terms.
  107. The terms must appear together and in the same order.
  108. For example:
  109. .. code-block:: python
  110. >>> from wagtail.search.query import Phrase
  111. >>> Page.objects.search(Phrase("Hello world"))
  112. [<Page: Hello World>]
  113. >>> Page.objects.search(Phrase("World hello"))
  114. [<Page: World Hello day>]
  115. If you are looking to implement phrase queries using the double-quote syntax, see :ref:`wagtailsearch_query_string_parsing`.
  116. .. _wagtailsearch_complex_queries:
  117. Complex search queries
  118. ^^^^^^^^^^^^^^^^^^^^^^
  119. Through the use of search query classes, Wagtail also supports building search queries as Python
  120. objects which can be wrapped by and combined with other search queries. The following classes are
  121. available:
  122. ``PlainText(query_string, operator=None, boost=1.0)``
  123. This class wraps a string of separate terms. This is the same as searching without query classes.
  124. It takes a query string, operator and boost.
  125. For example:
  126. .. code-block:: python
  127. >>> from wagtail.search.query import PlainText
  128. >>> Page.objects.search(PlainText("Hello world"))
  129. # Multiple plain text queries can be combined. This example will match both "hello world" and "Hello earth"
  130. >>> Page.objects.search(PlainText("Hello") & (PlainText("world") | PlainText("earth")))
  131. ``Phrase(query_string)``
  132. This class wraps a string containing a phrase. See previous section for how this works.
  133. For example:
  134. .. code-block:: python
  135. # This example will match both the phrases "hello world" and "Hello earth"
  136. >>> Page.objects.search(Phrase("Hello world") | Phrase("Hello earth"))
  137. ``Boost(query, boost)``
  138. This class boosts the score of another query.
  139. For example:
  140. .. code-block:: python
  141. >>> from wagtail.search.query import PlainText, Boost
  142. # This example will match both the phrases "hello world" and "Hello earth" but matches for "hello world" will be ranked higher
  143. >>> Page.objects.search(Boost(Phrase("Hello world"), 10.0) | Phrase("Hello earth"))
  144. Note that this isn't supported by the PostgreSQL or database search backends.
  145. .. _wagtailsearch_query_string_parsing:
  146. Query string parsing
  147. ^^^^^^^^^^^^^^^^^^^^
  148. The previous sections show how to construct a phrase search query manually, but a lot of search engines (Wagtail admin included, try it!)
  149. support writing phrase queries by wrapping the phrase with double-quotes. In addition to phrases, you might also want to allow users to
  150. add filters into the query using the colon syntax (``hello world published:yes``).
  151. These two features can be implemented using the ``parse_query_string`` utility function. This function takes a query string that a user
  152. typed and returns a query object and dictionary of filters:
  153. For example:
  154. .. code-block:: python
  155. >>> from wagtail.search.utils import parse_query_string
  156. >>> filters, query = parse_query_string('my query string "this is a phrase" this-is-a:filter', operator='and')
  157. >>> filters
  158. {
  159. 'this-is-a': 'filter',
  160. }
  161. >>> query
  162. And([
  163. PlainText("my query string", operator='and'),
  164. Phrase("this is a phrase"),
  165. ])
  166. Here's an example of how this function can be used in a search view:
  167. .. code-block:: python
  168. from wagtail.search.utils import parse_query_string
  169. def search(request):
  170. query_string = request.GET['query']
  171. # Parse query
  172. filters, query = parse_query_string(query_string, operator='and')
  173. # Published filter
  174. # An example filter that accepts either `published:yes` or `published:no` and filters the pages accordingly
  175. published_filter = filters.get('published')
  176. published_filter = published_filter and published_filter.lower()
  177. if published_filter in ['yes', 'true']:
  178. pages = pages.filter(live=True)
  179. elif published_filter in ['no', 'false']:
  180. pages = pages.filter(live=False)
  181. # Search
  182. pages = pages.search(query)
  183. return render(request, 'search_results.html', {'pages': pages})
  184. Custom ordering
  185. ^^^^^^^^^^^^^^^
  186. By default, search results are ordered by relevance, if the backend supports it. To preserve the QuerySet's existing ordering, the ``order_by_relevance`` keyword argument needs to be set to ``False`` on the ``search()`` method.
  187. For example:
  188. .. code-block:: python
  189. # Get a list of events ordered by date
  190. >>> EventPage.objects.order_by('date').search("Event", order_by_relevance=False)
  191. # Events ordered by date
  192. [<EventPage: Easter>, <EventPage: Halloween>, <EventPage: Christmas>]
  193. .. _wagtailsearch_annotating_results_with_score:
  194. Annotating results with score
  195. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  196. For each matched result, Elasticsearch calculates a "score", which is a number
  197. that represents how relevant the result is based on the user's query. The
  198. results are usually ordered based on the score.
  199. There are some cases where having access to the score is useful (such as
  200. programmatically combining two queries for different models). You can add the
  201. score to each result by calling the ``.annotate_score(field)`` method on the
  202. ``SearchQuerySet``.
  203. For example:
  204. .. code-block:: python
  205. >>> events = EventPage.objects.search("Event").annotate_score("_score")
  206. >>> for event in events:
  207. ... print(event.title, event._score)
  208. ...
  209. ("Easter", 2.5),
  210. ("Haloween", 1.7),
  211. ("Christmas", 1.5),
  212. Note that the score itself is arbitrary and it is only useful for comparison
  213. of results for the same query.
  214. .. _wagtailsearch_frontend_views:
  215. An example page search view
  216. ===========================
  217. Here's an example Django view that could be used to add a "search" page to your site:
  218. .. code-block:: python
  219. # views.py
  220. from django.shortcuts import render
  221. from wagtail.core.models import Page
  222. from wagtail.search.models import Query
  223. def search(request):
  224. # Search
  225. search_query = request.GET.get('query', None)
  226. if search_query:
  227. search_results = Page.objects.live().search(search_query)
  228. # Log the query so Wagtail can suggest promoted results
  229. Query.get(search_query).add_hit()
  230. else:
  231. search_results = Page.objects.none()
  232. # Render template
  233. return render(request, 'search_results.html', {
  234. 'search_query': search_query,
  235. 'search_results': search_results,
  236. })
  237. And here's a template to go with it:
  238. .. code-block:: html
  239. {% extends "base.html" %}
  240. {% load wagtailcore_tags %}
  241. {% block title %}Search{% endblock %}
  242. {% block content %}
  243. <form action="{% url 'search' %}" method="get">
  244. <input type="text" name="query" value="{{ search_query }}">
  245. <input type="submit" value="Search">
  246. </form>
  247. {% if search_results %}
  248. <ul>
  249. {% for result in search_results %}
  250. <li>
  251. <h4><a href="{% pageurl result %}">{{ result }}</a></h4>
  252. {% if result.search_description %}
  253. {{ result.search_description|safe }}
  254. {% endif %}
  255. </li>
  256. {% endfor %}
  257. </ul>
  258. {% elif search_query %}
  259. No results found
  260. {% else %}
  261. Please type something into the search box
  262. {% endif %}
  263. {% endblock %}
  264. Promoted search results
  265. =======================
  266. "Promoted search results" allow editors to explicitly link relevant content to search terms, so results pages can contain curated content in addition to results from the search engine.
  267. This functionality is provided by the :mod:`~wagtail.contrib.search_promotions` contrib module.