indexes.txt 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. =====================
  2. Model index reference
  3. =====================
  4. .. module:: django.db.models.indexes
  5. .. currentmodule:: django.db.models
  6. Index classes ease creating database indexes. They can be added using the
  7. :attr:`Meta.indexes <django.db.models.Options.indexes>` option. This document
  8. explains the API references of :class:`Index` which includes the `index
  9. options`_.
  10. .. admonition:: Referencing built-in indexes
  11. Indexes are defined in ``django.db.models.indexes``, but for convenience
  12. they're imported into :mod:`django.db.models`. The standard convention is
  13. to use ``from django.db import models`` and refer to the indexes as
  14. ``models.<IndexClass>``.
  15. ``Index`` options
  16. =================
  17. .. class:: Index(*expressions, fields=(), name=None, db_tablespace=None, opclasses=(), condition=None, include=None)
  18. Creates an index (B-Tree) in the database.
  19. ``expressions``
  20. ---------------
  21. .. attribute:: Index.expressions
  22. Positional argument ``*expressions`` allows creating functional indexes on
  23. expressions and database functions.
  24. For example::
  25. Index(Lower("title").desc(), "pub_date", name="lower_title_date_idx")
  26. creates an index on the lowercased value of the ``title`` field in descending
  27. order and the ``pub_date`` field in the default ascending order.
  28. Another example::
  29. Index(F("height") * F("weight"), Round("weight"), name="calc_idx")
  30. creates an index on the result of multiplying fields ``height`` and ``weight``
  31. and the ``weight`` rounded to the nearest integer.
  32. :attr:`Index.name` is required when using ``*expressions``.
  33. .. admonition:: Restrictions on Oracle
  34. Oracle requires functions referenced in an index to be marked as
  35. ``DETERMINISTIC``. Django doesn't validate this but Oracle will error. This
  36. means that functions such as
  37. :class:`Random() <django.db.models.functions.Random>` aren't accepted.
  38. .. admonition:: Restrictions on PostgreSQL
  39. PostgreSQL requires functions and operators referenced in an index to be
  40. marked as ``IMMUTABLE``. Django doesn't validate this but PostgreSQL will
  41. error. This means that functions such as
  42. :class:`Concat() <django.db.models.functions.Concat>` aren't accepted.
  43. .. admonition:: MySQL and MariaDB
  44. Functional indexes are ignored with MySQL < 8.0.13 and MariaDB as neither
  45. supports them.
  46. ``fields``
  47. ----------
  48. .. attribute:: Index.fields
  49. A list or tuple of the name of the fields on which the index is desired.
  50. By default, indexes are created with an ascending order for each column. To
  51. define an index with a descending order for a column, add a hyphen before the
  52. field's name.
  53. For example ``Index(fields=['headline', '-pub_date'])`` would create SQL with
  54. ``(headline, pub_date DESC)``.
  55. .. admonition:: MariaDB
  56. Index ordering isn't supported on MariaDB < 10.8. In that case, a
  57. descending index is created as a normal index.
  58. ``name``
  59. --------
  60. .. attribute:: Index.name
  61. The name of the index. If ``name`` isn't provided Django will auto-generate a
  62. name. For compatibility with different databases, index names cannot be longer
  63. than 30 characters and shouldn't start with a number (0-9) or underscore (_).
  64. .. admonition:: Partial indexes in abstract base classes
  65. You must always specify a unique name for an index. As such, you
  66. cannot normally specify a partial index on an abstract base class, since
  67. the :attr:`Meta.indexes <django.db.models.Options.indexes>` option is
  68. inherited by subclasses, with exactly the same values for the attributes
  69. (including ``name``) each time. To work around name collisions, part of the
  70. name may contain ``'%(app_label)s'`` and ``'%(class)s'``, which are
  71. replaced, respectively, by the lowercased app label and class name of the
  72. concrete model. For example ``Index(fields=['title'],
  73. name='%(app_label)s_%(class)s_title_index')``.
  74. ``db_tablespace``
  75. -----------------
  76. .. attribute:: Index.db_tablespace
  77. The name of the :doc:`database tablespace </topics/db/tablespaces>` to use for
  78. this index. For single field indexes, if ``db_tablespace`` isn't provided, the
  79. index is created in the ``db_tablespace`` of the field.
  80. If :attr:`.Field.db_tablespace` isn't specified (or if the index uses multiple
  81. fields), the index is created in tablespace specified in the
  82. :attr:`~django.db.models.Options.db_tablespace` option inside the model's
  83. ``class Meta``. If neither of those tablespaces are set, the index is created
  84. in the same tablespace as the table.
  85. .. seealso::
  86. For a list of PostgreSQL-specific indexes, see
  87. :mod:`django.contrib.postgres.indexes`.
  88. ``opclasses``
  89. -------------
  90. .. attribute:: Index.opclasses
  91. The names of the `PostgreSQL operator classes
  92. <https://www.postgresql.org/docs/current/indexes-opclass.html>`_ to use for
  93. this index. If you require a custom operator class, you must provide one for
  94. each field in the index.
  95. For example, ``GinIndex(name='json_index', fields=['jsonfield'],
  96. opclasses=['jsonb_path_ops'])`` creates a gin index on ``jsonfield`` using
  97. ``jsonb_path_ops``.
  98. ``opclasses`` are ignored for databases besides PostgreSQL.
  99. :attr:`Index.name` is required when using ``opclasses``.
  100. ``condition``
  101. -------------
  102. .. attribute:: Index.condition
  103. If the table is very large and your queries mostly target a subset of rows,
  104. it may be useful to restrict an index to that subset. Specify a condition as a
  105. :class:`~django.db.models.Q`. For example, ``condition=Q(pages__gt=400)``
  106. indexes records with more than 400 pages.
  107. :attr:`Index.name` is required when using ``condition``.
  108. .. admonition:: Restrictions on PostgreSQL
  109. PostgreSQL requires functions referenced in the condition to be marked as
  110. IMMUTABLE. Django doesn't validate this but PostgreSQL will error. This
  111. means that functions such as :ref:`date-functions` and
  112. :class:`~django.db.models.functions.Concat` aren't accepted. If you store
  113. dates in :class:`~django.db.models.DateTimeField`, comparison to
  114. :class:`~datetime.datetime` objects may require the ``tzinfo`` argument
  115. to be provided because otherwise the comparison could result in a mutable
  116. function due to the casting Django does for :ref:`lookups <field-lookups>`.
  117. .. admonition:: Restrictions on SQLite
  118. SQLite `imposes restrictions <https://www.sqlite.org/partialindex.html>`_
  119. on how a partial index can be constructed.
  120. .. admonition:: Oracle
  121. Oracle does not support partial indexes. Instead, partial indexes can be
  122. emulated by using functional indexes together with
  123. :class:`~django.db.models.expressions.Case` expressions.
  124. .. admonition:: MySQL and MariaDB
  125. The ``condition`` argument is ignored with MySQL and MariaDB as neither
  126. supports conditional indexes.
  127. ``include``
  128. -----------
  129. .. attribute:: Index.include
  130. A list or tuple of the names of the fields to be included in the covering index
  131. as non-key columns. This allows index-only scans to be used for queries that
  132. select only included fields (:attr:`~Index.include`) and filter only by indexed
  133. fields (:attr:`~Index.fields`).
  134. For example::
  135. Index(name="covering_index", fields=["headline"], include=["pub_date"])
  136. will allow filtering on ``headline``, also selecting ``pub_date``, while
  137. fetching data only from the index.
  138. Using ``include`` will produce a smaller index than using a multiple column
  139. index but with the drawback that non-key columns can not be used for sorting or
  140. filtering.
  141. ``include`` is ignored for databases besides PostgreSQL.
  142. :attr:`Index.name` is required when using ``include``.
  143. See the PostgreSQL documentation for more details about `covering indexes`_.
  144. .. admonition:: Restrictions on PostgreSQL
  145. PostgreSQL supports covering B-Tree and :class:`GiST indexes
  146. <django.contrib.postgres.indexes.GistIndex>`. PostgreSQL 14+ also supports
  147. covering :class:`SP-GiST indexes
  148. <django.contrib.postgres.indexes.SpGistIndex>`.
  149. .. _covering indexes: https://www.postgresql.org/docs/current/indexes-index-only-scans.html