One, MongoDB index
1. Index Introduction
The index is supported in MongoDB, and if there is no index, MONGODB must scan each document collection to select a matching query record. This makes the collection of scans inefficient because it requires the Mongod process to use a large amount of data for traversal operations. An index is a special data structure that holds a small subset of simple collection data. The index stores some special fields and sorts them.
Fundamentally, indexes are similar in MongoDB to other database systems. MONGODB Specifies the collection level of the index, supports indexing of any fields, or sub-fields in the MongoDB document collection.
2. Index optimization Query Scheme
To consider the relationship between data, do query optimization.
Creating an index supports common user-facing queries, ensuring that the scan reads the minimum number of files.
Indexes can optimize the performance of other businesses in a particular scenario.
3. Sort return Data
Take a look at a specific example of an index (in fact, the same as our query field)
650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/74/4C/wKiom1YYiRSyyRnvAAFZDyc7LAM551.jpg "title=" 1.png " alt= "Wkiom1yyirsyyrnvaafzdyc7lam551.jpg"/>
4. Index type
MONGODB provides specific types of data and queries that are supported by a number of different index types
default _id (_id index): All MongoDB has a _id field index by default, and if we do not specify a value of _id, a Objectid value is automatically generated. The _id index is unique and prevents the client from inserting two of the _id field values.
# Query The index of the Articles collection Db.articles.getIndexes (); # Add Titlei field index and Db.articles.ensureIndex ({title:1}) in ascending order; #重构索引 (Use caution) Db.articles.reIndex ();
Note: Index collation ascending: 1, descending-1
Compound Index (composite index [multi-field index]): You can customize the index of multiple fields in MongoDB. For example, if a composite indicator includes {userid:1,score:-1}, the index sorts the first user name after each user identifier value, sorted by the score + + reverse order + +.
{"_id": ObjectId (...), "Item": "Banana", "category": ["Food", "produce", "grocery"], "Location": "4th Street" Store "," Stock ": 4," type ":" Cases "," Arrival ": Date (...)}
To create a method:
# Create a composite index of the item, the Stock field, and sort Db.products.ensureIndex ({"Item": 1, "Stock": 1}) Note: The Hashed field cannot create an index, and an error will occur if created application Sort Order use case: Descending user name ascending time. # query result set sort Db.events.find (). Sort ({username:-1, date:1}) # query result set sorted Db.user_scores.find (). Sort ({score:-1,date:-1}). Limit (1)
An example of this is given in the official documentation:
{userid: "marker", address:[{zip: "618255"}, {zip: "618254"}]}# create the index and arrange the zip in ascending order Db.users.ensureIndex ( {"Address.zip": 1}); # If we do such a query Db.users.find ({"addr": {"$in": [{zip: "618254"}]})
Note: You can create a multi-key composite index (Multikey compound indexes)
Db.places.ensureIndex ({loc: "2dsphere"})
text Indexes (textual index): The text index, which was updated in 2.4, provides a collection feature in a text-search document that contains: A string, an array of characters. Use $text to do query operations. version 2.6 enables the text Search feature by default. In MongoDB 2.4, you need to make the text search feature manually create a full-text index and perform a text search
# Create Text index Db.articles.ensureIndex ({content: "text"});
A composite index can contain a text index called: Compound text index (compound text indexes), but with limitations:
Composite text indexes cannot contain any other special index types, such as: Multi-key index (Multi-key Indexes)
If the composite text index contains a key for the text index, the $text query must be the same query condition. may not translate the original text:
(If the compound text index includes keys preceding the text index key, to perform a $text search, the query
predicate must include equality match conditions on the preceding keys1)
# Create a hash index for User_scores's score field
Db.user_scores.ensureIndex ({score: "hashed"})
5. Properties of the Index
In addition to support for many index types, you can use a variety of properties to adjust performance.
TTL Indexes: It is a special index that can automatically delete the index of a document collection at some time. For some information data such as logs, event objects, session information, only need to be stored in the database for a specific period.
Usage Restrictions:
Composite indexes are not supported
Must be a Date Time Type field
If it is a date array, it expires by the earliest time.
Note: The TTL index does not guarantee that the expiration time is deleted immediately, and the background task does not run for 60 seconds to delete, depending on the mongod process.
# Create a unique index Db.members.ensureIndex ({"user_id": 1}, {unique:true})
Note: If the field is NULL, it is NULL, but the null value cannot be inserted repeatedly. You cannot create a unique index if there are two entities in collection that have a unique index field that is empty
In other words, we can also use it as a unique constraint similar to a relational database.
# force insert null object after error > Db.users.insert ({content: "Unique testing"}) Writeresult ({"ninserted": 0, "Writeerror": { "Code": 11000, "errmsg": "Insertdocument:: Caused by:: 11000 E11000 duplicate key error Index:test.users. $DSADSADSA dup key: {: null} "}})
Db.addresses.ensureIndex ({"xmpp_id": 1}, {sparse:true})
Background Properties Efficiently Modify/Create indexes: in a project run, if we create an index directly using the previous method or modify the index, the database blocks all requests during indexing. MongoDB provides the background property for background processing.
Db.addresses.ensureIndex ({"xmpp_id": 1}, {background:true})
We know that if you block all requests, indexing will be quick, but users who use the system need to wait, affecting the operation of the database, so you can choose to use the Background property in more specific cases.
6. Index name
# Auto-generated index name Db.products.ensureIndex ({item:1, Quantity:-1}) # is named: item_1_quantity_-1# Custom index name Db.products.ensureIndex ( {item:1, Quantity:-1}, {name: "Inventory"})
7 . Manage Indexes
# Add/Modify index Db.users.ensureIndex ({name: "text"}); # Delete all indexes of the collection Db.users.dropIndexes (); # Delete a specific index (delete the index of the ID word orderby order) Db.users.dropIndex ({"id": 1}) # Gets the collection index db.users.getIndexes (); # refactoring index Db.users.reIndex ();
8. Index classification
Default _id (_id index)
Single fields (single field index)
Compound index (composite index [multi-field index])
Multikey index (Multi-key indexing)
Geospatial Index (GEO-spatial index)
Text Indexes (textual index)
Hashed Indexes (hash code index)
Ii. Examples of application
To create a single-field index:
> Db.testcoll.ensureIndex ({name:1}) > Db.testcoll.getIndexes () [{"V": 1, "Name": "_id_", "key": {"_id": 1 }, "ns": "Test.testcoll"}, {"V": 1, "name": "Name_1", "key": {"name": 1}, "ns": "Test.testcoll"}]
To create a hash index:
> Db.testcoll.ensureIndex ({name: "hashed"}) > Db.testcoll.getIndexes () [{"V": 1, "Name": "_id_", "key": {"_ ID ": 1}," ns ":" Test.testcoll "}, {" V ": 1," name ":" Name_1 "," key ": {" name ": 1}," ns ":" Test.testcoll " }, {"V": 1, "name": "Name_hashed", "key": {"name": "Hashed"}, "ns": "Test.testcoll"}]
To delete a hash index:
> Db.testcoll.dropIndex ("name_hashed") {"Nindexeswas": 3, "OK": 1}> db.testcoll.getIndexes () [{"V": 1, "Name" : "_id_", "key": {"_id": 1}, "ns": "Test.testcoll"}, {"V": 1, "name": "Name_1", "key": {"name": 1 }, "ns": "Test.testcoll"}]
To delete a single field index:
> Db.testcoll.dropIndex ({name:1}) {"Nindexeswas": 2, "OK": 1}> db.testcoll.getIndexes () [{"V": 1, "Name": " _id_ "," key ": {" _id ": 1}," ns ":" Test.testcoll "}]
Delete all indexes:
> db.testcoll.dropIndexes ()
See if the index is used:
> Db.testcoll.find ({Name: "user:88"}). Explain () {"cursor": "Basiccursor", "Ismultikey": false, "n": 1, " Nscannedobjects ":", "nscanned": +, "Nscannedobjectsallplans": +, "Nscannedallplans": +, "Scanandorder": false, "IndexOnly": false, "Nyields": 0, "nchunkskips": 0, "Millis":, "Indexbounds": {}, "server": "www.example.com:27017"}&G T Db.testcoll.find (). Count () 100
By creating an index, you can discover that only one line is required at the time of the query, not in full document scanning:
> Db.testcoll.ensureIndex ({name:1}), {unique:true}{"unique": True}> db.testcoll.find ({Name: "user:88"}). Explain () {"cursor": "Btreecursor name_1", "Ismultikey": false, "n": 1, "nscannedobjects": 1, "nscanned": 1, "Nscannedobje Ctsallplans ": 1," Nscannedallplans ": 1," Scanandorder ": false," indexOnly ": false," Nyields ": 0," nchunkskips ": 0," Millis ": 0," Indexbounds ": {" Name ": [[" user:88 "," user:88 "]}," Server ":" www.example.com:27017 "}
To specify an index query:
> Db.testcoll.find ({Name: "user:88"}). Hint ({name:1}). Explain ()
Summarize:
The first is simply to introduce the index of MongoDB and its use, in the query we should be able to query based on the index created, this can greatly reduce the cost of disk IO. If there is no relevant index at the time of the query, it is very likely to traverse all documents, which greatly reduces performance. Create and use indexes in real-world use: Create the most appropriate indexes based on actual requirements, and use the most appropriate indexes when querying. For the use of the index is only a few of the fur of knowledge, if you want to further study the recommendations can be consulted in the database index design and optimization.
This article is from the "Bread" blog, make sure to keep this source http://cuchadanfan.blog.51cto.com/9940284/1701493
MongoDB (iii)