Documentation Home
MySQL 8.0 Reference Manual
Related Documentation Download this Manual
PDF (US Ltr) - 47.0Mb
PDF (A4) - 47.1Mb
PDF (RPM) - 42.4Mb
HTML Download (TGZ) - 10.8Mb
HTML Download (Zip) - 10.9Mb
HTML Download (RPM) - 9.4Mb
Man Pages (TGZ) - 227.1Kb
Man Pages (Zip) - 333.8Kb
Info (Gzip) - 4.2Mb
Info (Zip) - 4.2Mb
Excerpts from this Manual

20.4.3.6 Create and Drop Indexes

Indexes are used to find documents with specific field values quickly. Without an index, MySQL must begin with the first document and then read through the entire collection to find the relevant fields. The larger the collection, the more this costs. If a collection is large and queries on a specific field are common, then consider creating an index on a specific field inside a document.

For example, the following query will perform better with an index:

mysql-py> db.countryinfo.find("demographics.Population < 100")
...[output removed]
8 documents in set (0.00 sec)
Add a Nonunique Index

To create a nonunique index, pass to the create_index() method an index name and the index information. Duplicate index names are prohibited.

The index information is a JSON document with details of one or more fields to include in the index. Each field definition must include the full document path to the field, and specify the type of the field. In MySQL, the _id field is equivalent to a primary key by default.

Here, the index is created using the Population field inside the demographics object, which is indexed as an integer numeric value. Further options are available, including options for use with GeoJSON data. You can also specify the type of index, which has been omitted here because the default type index is appropriate.

mysql-py> db.countryinfo.create_index("pop",\
{"fields": [{"field": "$.demographics.Population", "type": "INTEGER"}]})
Query OK (0.04 sec)
Add a Unique Index

To create a unique index, pass to the create_index() method an index name, the index definition, and the index type unique. This example shows a unique index created on the country name ("Name"), which is another common field in the countryinfo collection to index. In the index field description, "TEXT(40)" represents the number of characters to index, and "required": True specifies that the field is required to exist in the document.

mysql-py> db.countryinfo.create_index("name",\
{"fields": [{"field": "$.Name", "type": "TEXT(40)", "required": True}], "unique": True})
Query OK (0.04 sec)
Drop an Index

To drop an index, pass to the drop_index() method the name of the index to drop. For example, you can drop the pop index as follows:

mysql-py> db.countryinfo.drop_index("pop")
Query OK (0.58 sec)
Related Information