MongoDB Study Notes (6) MongoDB index usage and Efficiency Analysis

Source: Internet
Author: User
Tags createindex
In fact, the indexes in MongoDB are similar to relational databases. They are designed to improve the efficiency of query and sorting, and the Implementation Principles are basically the same. The keys (fields) in the set can be common data types or subdocuments. MongoDB can create indexes on various types of keys. The following describes how to create, query, and maintain various types of indexes.
I. Create an index

1. Default Index

MongoDB has a default "_ id" key, which is equivalent to a "primary key" role. After the set is created, the system automatically creates an index on the "_ id" key, which is the default index and the index name is "_ id _", which cannot be deleted. You can view it in the following ways:

1 VaR _ idindex = collections collection. Metadata. Indexes. Single (x => X. Key ="_ Id _");
2 Console. writeline (_ idindex );

2. Single Column Index

The index created on a single key is a single column index. For example, we want to create a single column index for the "username" key on the "userinfo" set. The syntax is as follows: (1 indicates the positive order, -1)

1 Mongocollection. Metadata. createindex (New Document {{"Username", 1 }},False);

Then, we use the same method to find the index named "_ username _".

1 VaR _ username_index = collections collection. Metadata. Indexes. Single (x => X. Key ="_ Username _");
2 Console. writeline (_ username_index );

3. combined index

In addition, you can create a composite index for multiple keys at the same time. As follows:CodeA composite index is created in the forward and backward order of "userid:

1 Mongocollection. Metadata. createindex (New Document {{"Userid", 1 },{"Username",-1 }},False);

4. Sub-document index

We can create various indexes for the key of the document type, such as single-column indexes. The following is a single-column index for "detail:

1 Mongocollection. Metadata. createindex (New Document {{"Detail", 1 }},False);

Create a composite index on the key of the sub-document: for example, create a composite index on "detail. Address" and "detail. Age:

1 Mongocollection. Metadata. createindex (New Document {{"Detail. Address", 1 },{"Detail. Age",-1 }},False);

5. Unique Index

Unique indexes limit that duplicate information cannot be added when values are added to the current key. It is worth noting that when the specified key does not exist in the document, the key value is considered as "null", so "null" is also considered repeated, therefore, the key is generally used as the unique index. It is best to have a key-value pair.

Create a unique index for "userid" (the last parameter is "true" at this time "):

1 Mongocollection. Metadata. createindex (New Document {{"Userid", 1 }},True);
Ii. Index Maintenance

1. query Indexes

The index name query method is introduced. But sometimes we may forget the index name. How can we query it?

The following provides a method to traverse all indexes and print all index information:

1 Foreach (VAR IndexIn Collections collection. Metadata. indexes)
2  {
3 Console. writeline (index. value );
4 }

Output result example:

1 {"Name":"_ Id _","Ns":"Mydatabase. userinfo","Key":{"_ Id": 1 }}
2 {"Name":"_ Userid_unique _","Ns":"Mydatabase. userinfo","Key":{"Userid": 1 },"Unique":True,"_ Id":"4d8f406ab8a4730b7811605" }
3 { "name" : "_ username _" , "ns" : "mydatabase. userinfo " , " key " : { "username" :1 }, "unique" : false , "_ id" : "4d8f406ab8a4730b78000006" }
4 { "name" : "_ detail. address_detail.age _ " , " ns " : " mydatabase. userinfo " , " key " :{ " detail. address " : 1, " detail. age " :- 1 }, " unique " : false , "_ id" : "4d8f406ab8a4730b78000007" }
5 { "name" : "_ userid_username _" , "ns" : "mydatabase. userinfo " , " key " : { "userid" : 1, "username" : -1 }, "unique" : false , "_ id" : "4d8f406ab8a4730b78000008" }
6 {"Name":"_ Detail _","Ns":"Mydatabase. userinfo","Key":{"Detail": 1 },"Unique":False,"_ Id":"4d8f406ab8a4730b78000009" }

It can be seen that the index of a set is maintained by a set. Name indicates the index name, NS indicates the database and set of the index, key indicates the index key, positive or backward, and unique indicates whether the index is unique...

2. delete an index

A common misunderstanding for new users is that the index does not exist if the set is deleted. In a relational database, the table is deleted and the index does not exist. In MongoDB, the statement of deleting a set does not exist. Even if the set data is cleared, the indexes are still there. to delete an index, you must manually delete it.

For example, delete an index named "_ username:

1 Collections collection. Metadata. dropindex ("_ Username _");
The following describes how to delete all indexes except the default index:
01 Public Void Dropallindex ()
02 {
03 VaR listindexes = collections collection. Metadata. Indexes. tolist ();
04 For (Int I = 0; I <listindexes. Count; I ++)
05 {
06 If (Listindexes [I]. Key! ="_ Id _")
07 {
08 Collections collection. Metadata. dropindex (listindexes [I]. Key );
09 }
10 }
11 }

Iii. Index Efficiency

Can MongoDB index improve query efficiency? Here we use an example to test. Compare the query speed of the same data without indexing and indexing.

First, we use this method to insert 10 million data records:

01 Public Void Insertbigdata ()
02 {
03 VaR random =New Random ();
04 For (Int I = 1; I <100000; I ++)
05 {
06 Document Doc =New Document ();
07  
08 Doc ["ID"] = I;
09 Doc ["Data"] ="Data" + Random. Next (100000 );
10  
11 Collections collection. Save (DOC );
12 }
13  
14 Console. writeline ("Existing" + Collections collection. findall (). Documents. Count () +"Data entries");
15 }

Then, implement a method to create an index:

1 Public Void Createindexfordata ()
2 {
3 Mongocollection. Metadata. createindex (New Document {{"Data", 1 }},False);
4 }

There are also sorting methods:

1 Public Void Sortfordata ()
2 {
3 Collections collection. findall (). Sort (New Document {{"Data", 1 }});
4 }

Run the test code as follows:

01 Static Void Main (String[] ARGs)
02 {
03 Indexbll =New Indexbll ();
04 Indexbll. dropallindex ();
05 Indexbll. deleteall ();
06 Indexbll. insertbigdata ();
07  
08 Stopwatch wattings =New Stopwatch ();
09 Watch1.start ();
10 For (Int I = 0; I <1; I ++) indexbll. sortfordata ();
11 Console. writeline ("No-index sorting execution time :" + Watch1.elapsed );
12  
13 Indexbll. createindexfordata ();
14  
15 Stopwatch watch2 =New Stopwatch ();
16 Watch2.start ();
17 For (Int I = 0; I <1; I ++) indexbll. sortfordata ();
18 Console. writeline ("Index sorting execution time :" + Watch2.elapsed );
19  
20 }

Last executedProgramView results:

Multiple tests show that the query efficiency is higher than that without an index.

Source:

Http://www.cnblogs.com/lipan/archive/2011/03/28/1997202.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.