当前位置:网站首页>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 :
- The depth of each leaf node is the same , Usually it is 3 Layer or 4 layer ;
- Query operation , Performance is very objective ;
- 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 .
边栏推荐
- 不同环境相同配置项的内容如何diff差异?
- Flask 上下文详解
- Éducation à la transmission du savoir | Comment passer à un test logiciel pour l'un des postes les mieux rémunérés sur Internet? (joindre la Feuille de route pour l'apprentissage des tests logiciels)
- LOGO特训营 第五节 字体结构与设计常用技法
- leetcode 72. Edit distance edit distance (medium)
- 业务太忙,真的是没时间搞自动化理由吗?
- 蓝队攻防演练中的三段作战
- 都说软件测试很简单有手就行,但为何仍有这么多劝退的?
- Breakpoint debugging under vs2019 c release
- 集群的概述与定义,一看就会
猜你喜欢
Introducing QA into the software development lifecycle is the best practice that engineers should follow
A large number of virtual anchors in station B were collectively forced to refund: revenue evaporated, but they still owe station B; Jobs was posthumously awarded the U.S. presidential medal of freedo
UML图记忆技巧
Business is too busy. Is there really no reason to have time for automation?
将QA引入软件开发生命周期是工程师要遵循的最佳实践
Play with grpc - go deep into concepts and principles
Locust性能测试 —— 环境搭建及使用
2022-07-04: what is the output of the following go language code? A:true; B:false; C: Compilation error. package main import “fmt“ func main() { fmt.Pri
集群的概述与定义,一看就会
[Yugong series] go teaching course 003-ide installation and basic use in July 2022
随机推荐
嵌入式开发:技巧和窍门——提高嵌入式软件代码质量的7个技巧
Redis sentinel simply looks at the trade-offs between distributed high availability and consistency
Xiangjiang Kunpeng joined the shengteng Wanli partnership program and continued to write a new chapter of cooperation with Huawei
leetcode 72. Edit distance edit distance (medium)
Huawei Nova 10 series released Huawei application market to build a solid application security firewall
Microservices -- Opening
TLA+ 入门教程(1):形式化方法简介
卷积神经网络模型之——LeNet网络结构与代码实现
华泰证券是国家认可的券商吗?开户安不安全?
LOGO特訓營 第一節 鑒別Logo與Logo設計思路
Li Kou 98: verify binary search tree
Now MySQL cdc2.1 is parsing the datetime class with a value of 0000-00-00 00:00:00
How to reset the password of MySQL root account
如何实现轻松管理1500万员工?
【lua】int64的支持
Concurrent optimization summary
Tla+ introductory tutorial (1): introduction to formal methods
Practice and principle of PostgreSQL join
力扣_回文数
Business is too busy. Is there really no reason to have time for automation?