当前位置:网站首页>Summary of index operations in mongodb

Summary of index operations in mongodb

2022-07-04 22:37:00 cui_ yonghua

One . summary

Indexes can often make queries more efficient , If there is no index ,MongoDB When the data is read, each file in the collection must be scanned and those records that meet the query criteria must be selected . The query efficiency of scanning the whole collection is very low , Especially when dealing with large amounts of data , Queries can take tens of seconds or even minutes , This can be deadly to the performance of your site .

An index is a special data structure , The index is stored in a collection of data that is easy to read through , An index is a structure that sorts the values of a column or columns in a database table

Indexes (Index) Help MySQL Data structure for efficient data acquisition .
You can get the essence of the index : An index is a data structure .
It can be simply understood as “ Quickly find data structures in order ”.

An index stores the values of a particular field or group of fields , Sort by the value of this field . Sorting of index entries supports effective equality matching and range based query operations .

in addition ,MongoDB You can return the sorted results by using the order in the index .

Index principle :MongoDB The data structure of the index defaults to B-Tree.B-Tree Characteristics of index structure of type :

  1. The depth of each leaf node is the same , Usually it is 3 Layer or 4 layer ;
  2. Query operation , Performance is very objective ;
  3. For range queries , Directly traversing the linked list of leaf nodes can quickly locate the pointer position matching the document record .

Official documents - Indexes https://www.mongodb.com/docs/manual/indexes/

Two . Common operations of indexing

2.1 Create index

MongoDB Use createIndex() Method to create the index .( 3.0.0 Add... After version )

Grammar format :db.collection.createIndex(keys, options)

In the syntax Key The value is the index field that you want to create ,1 Creates an index in ascending order for the specified , If you want to create the index in descending order specify as -1 that will do .

The optional parameters are as follows :

background Boolean type , The indexing process blocks other database operations ,background You can specify backchannel mode to create indexes , That is, increase “background” Optional parameters . “background” The default value is false.

unique Boolean type , Is the index created unique . Designated as true Create unique index . The default value is false.

name Boolean type , Name of index . If not specified ,MongoDB Generates an index name by concatenating the field name of the index and the sort order .

dropDups Boolean type , Whether to delete duplicate records when establishing a unique index , Appoint true Create unique index . The default value is false.

sparse Boolean type , Indexes are not enabled for field data that does not exist in the document ; This parameter requires special attention , If set to true Words , Documents that do not contain corresponding fields are not queried in index fields .. The default value is false.

expireAfterSeconds integer type , Specifies a value in seconds , complete TTL Set up , Sets the lifetime of the collection .

v The version number of the index . The default index version depends on mongod The version that runs when the index is created .

weights Index weight , Values in 1 To 99,999 Between , Represents the score weight of the index relative to other index fields .

default_language Boolean type , For text index , This parameter determines the list of stop words and the rules for the word stem and lexicon . Default to English

language_override Boolean type , For text index , This parameter specifies the name of the field to be included in the document , The language overrides the default language, The default value is language.

Case study 1: Create index

db.col.createIndex({
    "title":1})

Case study 2:createIndex() Method you can also set up multiple fields to create an index ( A relational database is called a composite index ).

db.col.createIndex({
    "title":1,"description":-1})

Case study 3: Create indexes in the background

db.values.createIndex({
    open: 1, close: 1}, {
    background: true})

notes :MongoDB You can also use ensureIndex() Method to create the index , 3.0.0 It can also be used after version , But only createIndex() Another name for .

2.2 Commonly used instructions

1、 Look at the collection index :db.col.getIndexes()

2、 Look at the size of the set index :db.col.totalIndexSize()

3、 Delete all indexes of the collection :db.col.dropIndexes()

4、 Deletes the specified index of the collection :db.col.dropIndex(" The index name ")

5、 utilize TTL Set the expiration time of the stored data : Expires after a specified period of time or at a specified point in time ,MongoDB Independent thread to clear data . This is similar to setting the scheduled automatic deletion of tasks , You can clear preconditions such as history or logs , Set up Index The key field of is date type new Date().

Case study : For example, in the data record createDate When the date type is :① Setup time 180 Automatically clear after seconds ;② Set after the record is created ,180 Seconds or so to delete .

db.col.createIndex({"createDate": 1},{expireAfterSeconds: 180})

3、 ... and 、 Index limits

3.1、 Maximum range

The index in the collection cannot exceed 64 individual
The index name cannot be longer than 125 Characters
A composite index can have at most 31 A field

3.2、 Query restrictions

The index cannot be used by the following query :

  • Regular expressions and non operators , Such as $nin, $not, etc. .
  • Arithmetic operator , Such as $mod, etc. .
  • $where Clause

therefore , It is a good habit to detect whether the statement uses an index , It can be used explain Check it out. .

3.3、 Extra expenses

Using indexes comes at a price , For each index added , Every write operation ( Insert 、 to update 、 Delete ) Will take more time . This is because , When the data changes ,MongoDB Not only to update the document , Also update all indexes on the collection . therefore , If you rarely read a collection , Index is not recommended .

原网站

版权声明
本文为[cui_ yonghua]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207042057005028.html