search.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. ================
  2. Full text search
  3. ================
  4. The database functions in the ``django.contrib.postgres.search`` module ease
  5. the use of PostgreSQL's `full text search engine
  6. <https://www.postgresql.org/docs/current/textsearch.html>`_.
  7. For the examples in this document, we'll use the models defined in
  8. :doc:`/topics/db/queries`.
  9. .. seealso::
  10. For a high-level overview of searching, see the :doc:`topic documentation
  11. </topics/db/search>`.
  12. .. currentmodule:: django.contrib.postgres.search
  13. The ``search`` lookup
  14. =====================
  15. .. fieldlookup:: search
  16. A common way to use full text search is to search a single term against a
  17. single column in the database. For example::
  18. >>> Entry.objects.filter(body_text__search='Cheese')
  19. [<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>]
  20. This creates a ``to_tsvector`` in the database from the ``body_text`` field
  21. and a ``plainto_tsquery`` from the search term ``'Cheese'``, both using the
  22. default database search configuration. The results are obtained by matching the
  23. query and the vector.
  24. To use the ``search`` lookup, ``'django.contrib.postgres'`` must be in your
  25. :setting:`INSTALLED_APPS`.
  26. ``SearchVector``
  27. ================
  28. .. class:: SearchVector(*expressions, config=None, weight=None)
  29. Searching against a single field is great but rather limiting. The ``Entry``
  30. instances we're searching belong to a ``Blog``, which has a ``tagline`` field.
  31. To query against both fields, use a ``SearchVector``::
  32. >>> from django.contrib.postgres.search import SearchVector
  33. >>> Entry.objects.annotate(
  34. ... search=SearchVector('body_text', 'blog__tagline'),
  35. ... ).filter(search='Cheese')
  36. [<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>]
  37. The arguments to ``SearchVector`` can be any
  38. :class:`~django.db.models.Expression` or the name of a field. Multiple
  39. arguments will be concatenated together using a space so that the search
  40. document includes them all.
  41. ``SearchVector`` objects can be combined together, allowing you to reuse them.
  42. For example::
  43. >>> Entry.objects.annotate(
  44. ... search=SearchVector('body_text') + SearchVector('blog__tagline'),
  45. ... ).filter(search='Cheese')
  46. [<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>]
  47. See :ref:`postgresql-fts-search-configuration` and
  48. :ref:`postgresql-fts-weighting-queries` for an explanation of the ``config``
  49. and ``weight`` parameters.
  50. ``SearchQuery``
  51. ===============
  52. .. class:: SearchQuery(value, config=None, search_type='plain')
  53. ``SearchQuery`` translates the terms the user provides into a search query
  54. object that the database compares to a search vector. By default, all the words
  55. the user provides are passed through the stemming algorithms, and then it
  56. looks for matches for all of the resulting terms.
  57. If ``search_type`` is ``'plain'``, which is the default, the terms are treated
  58. as separate keywords. If ``search_type`` is ``'phrase'``, the terms are treated
  59. as a single phrase. If ``search_type`` is ``'raw'``, then you can provide a
  60. formatted search query with terms and operators. If ``search_type`` is
  61. ``'websearch'``, then you can provide a formatted search query, similar to the
  62. one used by web search engines. ``'websearch'`` requires PostgreSQL ≥ 11. Read
  63. PostgreSQL's `Full Text Search docs`_ to learn about differences and syntax.
  64. Examples:
  65. .. _Full Text Search docs: https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES
  66. >>> from django.contrib.postgres.search import SearchQuery
  67. >>> SearchQuery('red tomato') # two keywords
  68. >>> SearchQuery('tomato red') # same results as above
  69. >>> SearchQuery('red tomato', search_type='phrase') # a phrase
  70. >>> SearchQuery('tomato red', search_type='phrase') # a different phrase
  71. >>> SearchQuery("'tomato' & ('red' | 'green')", search_type='raw') # boolean operators
  72. >>> SearchQuery("'tomato' ('red' OR 'green')", search_type='websearch') # websearch operators
  73. ``SearchQuery`` terms can be combined logically to provide more flexibility::
  74. >>> from django.contrib.postgres.search import SearchQuery
  75. >>> SearchQuery('meat') & SearchQuery('cheese') # AND
  76. >>> SearchQuery('meat') | SearchQuery('cheese') # OR
  77. >>> ~SearchQuery('meat') # NOT
  78. See :ref:`postgresql-fts-search-configuration` for an explanation of the
  79. ``config`` parameter.
  80. ``SearchRank``
  81. ==============
  82. .. class:: SearchRank(vector, query, weights=None, normalization=None, cover_density=False)
  83. So far, we've returned the results for which any match between the vector and
  84. the query are possible. It's likely you may wish to order the results by some
  85. sort of relevancy. PostgreSQL provides a ranking function which takes into
  86. account how often the query terms appear in the document, how close together
  87. the terms are in the document, and how important the part of the document is
  88. where they occur. The better the match, the higher the value of the rank. To
  89. order by relevancy::
  90. >>> from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
  91. >>> vector = SearchVector('body_text')
  92. >>> query = SearchQuery('cheese')
  93. >>> Entry.objects.annotate(rank=SearchRank(vector, query)).order_by('-rank')
  94. [<Entry: Cheese on Toast recipes>, <Entry: Pizza recipes>]
  95. See :ref:`postgresql-fts-weighting-queries` for an explanation of the
  96. ``weights`` parameter.
  97. Set the ``cover_density`` parameter to ``True`` to enable the cover density
  98. ranking, which means that the proximity of matching query terms is taken into
  99. account.
  100. Provide an integer to the ``normalization`` parameter to control rank
  101. normalization. This integer is a bit mask, so you can combine multiple
  102. behaviors::
  103. >>> from django.db.models import Value
  104. >>> Entry.objects.annotate(
  105. ... rank=SearchRank(
  106. ... vector,
  107. ... query,
  108. ... normalization=Value(2).bitor(Value(4)),
  109. ... )
  110. ... )
  111. The PostgreSQL documentation has more details about `different rank
  112. normalization options`_.
  113. .. _different rank normalization options: https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING
  114. ``SearchHeadline``
  115. ==================
  116. .. class:: SearchHeadline(expression, query, config=None, start_sel=None, stop_sel=None, max_words=None, min_words=None, short_word=None, highlight_all=None, max_fragments=None, fragment_delimiter=None)
  117. Accepts a single text field or an expression, a query, a config, and a set of
  118. options. Returns highlighted search results.
  119. Set the ``start_sel`` and ``stop_sel`` parameters to the string values to be
  120. used to wrap highlighted query terms in the document. PostgreSQL's defaults are
  121. ``<b>`` and ``</b>``.
  122. Provide integer values to the ``max_words`` and ``min_words`` parameters to
  123. determine the longest and shortest headlines. PostgreSQL's defaults are 35 and
  124. 15.
  125. Provide an integer value to the ``short_word`` parameter to discard words of
  126. this length or less in each headline. PostgreSQL's default is 3.
  127. Set the ``highlight_all`` parameter to ``True`` to use the whole document in
  128. place of a fragment and ignore ``max_words``, ``min_words``, and ``short_word``
  129. parameters. That's disabled by default in PostgreSQL.
  130. Provide a non-zero integer value to the ``max_fragments`` to set the maximum
  131. number of fragments to display. That's disabled by default in PostgreSQL.
  132. Set the ``fragment_delimiter`` string parameter to configure the delimiter
  133. between fragments. PostgreSQL's default is ``" ... "``.
  134. The PostgreSQL documentation has more details on `highlighting search
  135. results`_.
  136. Usage example::
  137. >>> from django.contrib.postgres.search import SearchHeadline, SearchQuery
  138. >>> query = SearchQuery('red tomato')
  139. >>> entry = Entry.objects.annotate(
  140. ... headline=SearchHeadline(
  141. ... 'body_text',
  142. ... query,
  143. ... start_sel='<span>',
  144. ... stop_sel='</span>',
  145. ... ),
  146. ... ).get()
  147. >>> print(entry.headline)
  148. Sandwich with <span>tomato</span> and <span>red</span> cheese.
  149. See :ref:`postgresql-fts-search-configuration` for an explanation of the
  150. ``config`` parameter.
  151. .. _highlighting search results: https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-HEADLINE
  152. .. _postgresql-fts-search-configuration:
  153. Changing the search configuration
  154. =================================
  155. You can specify the ``config`` attribute to a :class:`SearchVector` and
  156. :class:`SearchQuery` to use a different search configuration. This allows using
  157. different language parsers and dictionaries as defined by the database::
  158. >>> from django.contrib.postgres.search import SearchQuery, SearchVector
  159. >>> Entry.objects.annotate(
  160. ... search=SearchVector('body_text', config='french'),
  161. ... ).filter(search=SearchQuery('œuf', config='french'))
  162. [<Entry: Pain perdu>]
  163. The value of ``config`` could also be stored in another column::
  164. >>> from django.db.models import F
  165. >>> Entry.objects.annotate(
  166. ... search=SearchVector('body_text', config=F('blog__language')),
  167. ... ).filter(search=SearchQuery('œuf', config=F('blog__language')))
  168. [<Entry: Pain perdu>]
  169. .. _postgresql-fts-weighting-queries:
  170. Weighting queries
  171. =================
  172. Every field may not have the same relevance in a query, so you can set weights
  173. of various vectors before you combine them::
  174. >>> from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
  175. >>> vector = SearchVector('body_text', weight='A') + SearchVector('blog__tagline', weight='B')
  176. >>> query = SearchQuery('cheese')
  177. >>> Entry.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.3).order_by('rank')
  178. The weight should be one of the following letters: D, C, B, A. By default,
  179. these weights refer to the numbers ``0.1``, ``0.2``, ``0.4``, and ``1.0``,
  180. respectively. If you wish to weight them differently, pass a list of four
  181. floats to :class:`SearchRank` as ``weights`` in the same order above::
  182. >>> rank = SearchRank(vector, query, weights=[0.2, 0.4, 0.6, 0.8])
  183. >>> Entry.objects.annotate(rank=rank).filter(rank__gte=0.3).order_by('-rank')
  184. Performance
  185. ===========
  186. Special database configuration isn't necessary to use any of these functions,
  187. however, if you're searching more than a few hundred records, you're likely to
  188. run into performance problems. Full text search is a more intensive process
  189. than comparing the size of an integer, for example.
  190. In the event that all the fields you're querying on are contained within one
  191. particular model, you can create a functional index which matches the search
  192. vector you wish to use. The PostgreSQL documentation has details on
  193. `creating indexes for full text search
  194. <https://www.postgresql.org/docs/current/textsearch-tables.html#TEXTSEARCH-TABLES-INDEX>`_.
  195. ``SearchVectorField``
  196. ---------------------
  197. .. class:: SearchVectorField
  198. If this approach becomes too slow, you can add a ``SearchVectorField`` to your
  199. model. You'll need to keep it populated with triggers, for example, as
  200. described in the `PostgreSQL documentation`_. You can then query the field as
  201. if it were an annotated ``SearchVector``::
  202. >>> Entry.objects.update(search_vector=SearchVector('body_text'))
  203. >>> Entry.objects.filter(search_vector='cheese')
  204. [<Entry: Cheese on Toast recipes>, <Entry: Pizza recipes>]
  205. .. _PostgreSQL documentation: https://www.postgresql.org/docs/current/textsearch-features.html#TEXTSEARCH-UPDATE-TRIGGERS
  206. Trigram similarity
  207. ==================
  208. Another approach to searching is trigram similarity. A trigram is a group of
  209. three consecutive characters. In addition to the :lookup:`trigram_similar` and
  210. :lookup:`trigram_word_similar` lookups, you can use a couple of other
  211. expressions.
  212. To use them, you need to activate the `pg_trgm extension
  213. <https://www.postgresql.org/docs/current/pgtrgm.html>`_ on PostgreSQL. You can
  214. install it using the
  215. :class:`~django.contrib.postgres.operations.TrigramExtension` migration
  216. operation.
  217. ``TrigramSimilarity``
  218. ---------------------
  219. .. class:: TrigramSimilarity(expression, string, **extra)
  220. Accepts a field name or expression, and a string or expression. Returns the
  221. trigram similarity between the two arguments.
  222. Usage example::
  223. >>> from django.contrib.postgres.search import TrigramSimilarity
  224. >>> Author.objects.create(name='Katy Stevens')
  225. >>> Author.objects.create(name='Stephen Keats')
  226. >>> test = 'Katie Stephens'
  227. >>> Author.objects.annotate(
  228. ... similarity=TrigramSimilarity('name', test),
  229. ... ).filter(similarity__gt=0.3).order_by('-similarity')
  230. [<Author: Katy Stevens>, <Author: Stephen Keats>]
  231. ``TrigramWordSimilarity``
  232. -------------------------
  233. .. versionadded:: 4.0
  234. .. class:: TrigramWordSimilarity(string, expression, **extra)
  235. Accepts a string or expression, and a field name or expression. Returns the
  236. trigram word similarity between the two arguments.
  237. Usage example::
  238. >>> from django.contrib.postgres.search import TrigramWordSimilarity
  239. >>> Author.objects.create(name='Katy Stevens')
  240. >>> Author.objects.create(name='Stephen Keats')
  241. >>> test = 'Kat'
  242. >>> Author.objects.annotate(
  243. ... similarity=TrigramWordSimilarity(test, 'name'),
  244. ... ).filter(similarity__gt=0.3).order_by('-similarity')
  245. [<Author: Katy Stevens>]
  246. ``TrigramDistance``
  247. -------------------
  248. .. class:: TrigramDistance(expression, string, **extra)
  249. Accepts a field name or expression, and a string or expression. Returns the
  250. trigram distance between the two arguments.
  251. Usage example::
  252. >>> from django.contrib.postgres.search import TrigramDistance
  253. >>> Author.objects.create(name='Katy Stevens')
  254. >>> Author.objects.create(name='Stephen Keats')
  255. >>> test = 'Katie Stephens'
  256. >>> Author.objects.annotate(
  257. ... distance=TrigramDistance('name', test),
  258. ... ).filter(distance__lte=0.7).order_by('distance')
  259. [<Author: Katy Stevens>, <Author: Stephen Keats>]
  260. ``TrigramWordDistance``
  261. -----------------------
  262. .. versionadded:: 4.0
  263. .. class:: TrigramWordDistance(string, expression, **extra)
  264. Accepts a string or expression, and a field name or expression. Returns the
  265. trigram word distance between the two arguments.
  266. Usage example::
  267. >>> from django.contrib.postgres.search import TrigramWordDistance
  268. >>> Author.objects.create(name='Katy Stevens')
  269. >>> Author.objects.create(name='Stephen Keats')
  270. >>> test = 'Kat'
  271. >>> Author.objects.annotate(
  272. ... distance=TrigramWordDistance(test, 'name'),
  273. ... ).filter(distance__lte=0.7).order_by('distance')
  274. [<Author: Katy Stevens>]