Checks the document meta data and ensures all the indexes exist. Global defaults can be set in the meta - see :doc:`guide/defining-documents` By default, this will get called automatically upon first interaction with the Document collection (query, save, etc) so unless you
(cls)
| 894 | |
| 895 | @classmethod |
| 896 | def ensure_indexes(cls): |
| 897 | """Checks the document meta data and ensures all the indexes exist. |
| 898 | |
| 899 | Global defaults can be set in the meta - see :doc:`guide/defining-documents` |
| 900 | |
| 901 | By default, this will get called automatically upon first interaction with the |
| 902 | Document collection (query, save, etc) so unless you disabled `auto_create_index`, you |
| 903 | shouldn't have to call this manually. |
| 904 | |
| 905 | This also gets called upon every call to Document.save if `auto_create_index_on_save` is set to True |
| 906 | |
| 907 | If called multiple times, MongoDB will not re-recreate indexes if they exist already |
| 908 | |
| 909 | .. note:: You can disable automatic index creation by setting |
| 910 | `auto_create_index` to False in the documents meta data |
| 911 | """ |
| 912 | background = cls._meta.get("index_background", False) |
| 913 | index_opts = cls._meta.get("index_opts") or {} |
| 914 | index_cls = cls._meta.get("index_cls", True) |
| 915 | |
| 916 | collection = cls._get_collection() |
| 917 | |
| 918 | # determine if an index which we are creating includes |
| 919 | # _cls as its first field; if so, we can avoid creating |
| 920 | # an extra index on _cls, as mongodb will use the existing |
| 921 | # index to service queries against _cls |
| 922 | cls_indexed = False |
| 923 | |
| 924 | # Ensure document-defined indexes are created |
| 925 | if cls._meta["index_specs"]: |
| 926 | index_spec = cls._meta["index_specs"] |
| 927 | for spec in index_spec: |
| 928 | spec = spec.copy() |
| 929 | fields = spec.pop("fields") |
| 930 | cls_indexed = cls_indexed or includes_cls(fields) |
| 931 | opts = index_opts.copy() |
| 932 | opts.update(spec) |
| 933 | |
| 934 | # we shouldn't pass 'cls' to the collection.ensureIndex options |
| 935 | # because of https://jira.mongodb.org/browse/SERVER-769 |
| 936 | if "cls" in opts: |
| 937 | del opts["cls"] |
| 938 | |
| 939 | collection.create_index(fields, background=background, **opts) |
| 940 | |
| 941 | # If _cls is being used (for polymorphism), it needs an index, |
| 942 | # only if another index doesn't begin with _cls |
| 943 | if index_cls and not cls_indexed and cls._meta.get("allow_inheritance"): |
| 944 | # we shouldn't pass 'cls' to the collection.ensureIndex options |
| 945 | # because of https://jira.mongodb.org/browse/SERVER-769 |
| 946 | if "cls" in index_opts: |
| 947 | del index_opts["cls"] |
| 948 | |
| 949 | collection.create_index("_cls", background=background, **index_opts) |
| 950 | |
| 951 | @classmethod |
| 952 | def list_indexes(cls): |