MongoDB学习八--MongoDB的索引操作

Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform acollection scan, i.e. scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.

Indexes are special data structures [1] that store a small portion of the collection’s data set in an easy to traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field. The ordering of the index entries supports efficient equality matches and range-based query operations. In addition, MongoDB can return sorted results by using the ordering in the index.

The following diagram illustrates a query that selects and orders the matching documents using an index:

Diagram of a query that uses an index to select and return sorted results. The index stores ``score`` values in ascending order. MongoDB can traverse the index in either ascending or descending order to return sorted results.

Fundamentally, indexes in MongoDB are similar to indexes in other database systems. MongoDB defines indexes at the collection level and supports indexes on any field or sub-field of the documents in a MongoDB collection.

[1] MongoDB indexes use a B-tree data structure.

Index Types

MongoDB provides a number of different index types to support specific types of data and queries.

Default _id

All MongoDB collections have an index on the _id field that exists by default. If applications do not specify a value for _id the driver or the mongod will create an _id field with an ObjectId value.

The _id index is unique and prevents clients from inserting two documents with the same value for the _idfield.

Single Field

In addition to the MongoDB-defined _id index, MongoDB supports the creation of user-defined ascending/descending indexes on a single field of a document.

Diagram of an index on the ``score`` field (ascending).

For a single-field index and sort operations, the sort order (i.e. ascending or descending) of the index key does not matter because MongoDB can traverse the index in either direction.

See Single Field Indexes and Sort with a Single Field Index for more information on single-field indexes.

Compound Index

MongoDB also supports user-defined indexes on multiple fields, i.e. compound indexes.

The order of fields listed in a compound index has significance. For instance, if a compound index consists of{ userid: 1, score: -1 }, the index sorts first by userid and then, within each userid value, sorts by score.

Diagram of a compound index on the ``userid`` field (ascending) and the ``score`` field (descending). The index sorts first by the ``userid`` field and then by the ``score`` field.

For compound indexes and sort operations, the sort order (i.e. ascending or descending) of the index keys can determine whether the index can support a sort operation. See Sort Order for more information on the impact of index order on results in compound indexes.

See Compound Indexes and Sort on Multiple Fields for more information on compound indexes.

Multikey Index

MongoDB uses multikey indexes to index the content stored in arrays. If you index a field that holds an array value, MongoDB creates separate index entries for every element of the array. These multikey indexes allow queries to select documents that contain arrays by matching on element or elements of the arrays. MongoDB automatically determines whether to create a multikey index if the indexed field contains an array value; you do not need to explicitly specify the multikey type.

Diagram of a multikey index on the ``addr.zip`` field. The ``addr`` field contains an array of address documents. The address documents contain the ``zip`` field.

See Multikey Indexes and Multikey Index Bounds for more information on multikey indexes.

Geospatial Index

To support efficient queries of geospatial coordinate data, MongoDB provides two special indexes: 2d indexes that uses planar geometry when returning results and 2sphere indexes that use spherical geometry to return results.

See 2d Index Internals for a high level introduction to geospatial indexes.

Text Indexes

MongoDB provides a text index type that supports searching for string content in a collection. These text indexes do not store language-specific stop words (e.g. “the”, “a”, “or”) and stem the words in a collection to only store root words.

See Text Indexes for more information on text indexes and search.

Hashed Indexes

To support hash based sharding, MongoDB provides a hashed index type, which indexes the hash of the value of a field. These indexes have a more random distribution of values along their range, but only support equality matches and cannot support range-based queries.

Index Properties

Unique Indexes

The unique property for an index causes MongoDB to reject duplicate values for the indexed field. Other than the unique constraint, unique indexes are functionally interchangeable with other MongoDB indexes.

Sparse Indexes

The sparse property of an index ensures that the index only contain entries for documents that have the indexed field. The index skips documents that do not have the indexed field.

You can combine the sparse index option with the unique index option to reject documents that have duplicate values for a field but ignore documents that do not have the indexed key.

TTL Indexes

TTL indexes are special indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time. This is ideal for certain types of information like machine generated event data, logs, and session information that only need to persist in a database for a finite amount of time.

See: Expire Data from Collections by Setting TTL for implementation instructions.

Index Use

Indexes can improve the efficiency of read operations. The Analyze Query Performance tutorial provides an example of the execution statistics of a query with and without an index.

For information on how MongoDB chooses an index to use, see query optimizer.

Covered Queries

When the query criteria and the projection of a query include only the indexed fields, MongoDB will return results directly from the index without scanning any documents or bringing documents into memory. These covered queries can be very efficient.

Diagram of a query that uses only the index to match the query criteria and return the results. MongoDB does not need to inspect data outside of the index to fulfill the query.

For more information on covered queries, see Covered Query.

Index Intersection

New in version 2.6.

MongoDB can use the intersection of indexes to fulfill queries. For queries that specify compound query conditions, if one index can fulfill a part of a query condition, and another index can fulfill another part of the query condition, then MongoDB can use the intersection of the two indexes to fulfill the query. Whether the use of a compound index or the use of an index intersection is more efficient depends on the particular query and the system.

具体操作:

1,插入15W条数据

for(var i=0;i<150000;i++){ var rand=parseInt(i*Math.random()); db.person.insert({"name":"Lily"+i,"age":i,"rand":rand}) }

insert 15W data

插入好像消耗时间3分钟

2,性能分析函数(explain)

利用mongodb中给我们提供了一个关键字叫做“explain"做性能分析看图,注意,这里的name字段没有建立任何索引,这里我就查询一个“name10000”的姓名。3.0.5的要在explain()中加关键字才有统计数据返回, db.person.find({"name":"Lily"+11000}).explain("executionStats")

explain

"executionTimeMillis" : 64,这个就是我们最最最....关心的东西,总共耗时85毫秒。

"totalDocsExamined" : 150000,  数据总量

"nReturned" : 1, 这里是1,也就是最终返回了1个文档。

3,建立索引(ensureIndex)

在15w条这么简单的集合中查找一个文档要85毫秒,是不太快,那么我们该如何优化呢?mongodb中给我们带来了索引查找,看看能不能让我们的查询一飞冲天.....db.person.createIndex({"name":1})

createindex

search by index

看看结果,Oh,My,God ~不能直视了,红框处~——~

这里我们使用了createIndex在name上建立了索引。”1“:表示按照name进行升序,”-1“:表示按照name进行降序。

我的神啊,再来看看这些敏感信息。擦,数据库只浏览了一个文档;看看这个时间真的不敢相信,秒秒杀。

4,唯一索引

和sqlserver一样都可以建立唯一索引,重复的键值自然就不能插入,在mongodb中的使用方法是:

db.person.createIndex({"name":1},{"unique":true})

index error

报错了,要先删除已存在的在此字段上的索引 db.person.dropIndex("name_1")

unique index

建索引成功

unique index

5,组合索引

有时候我们的查询不是单条件的,可能是多条件,比如按年龄查找同学,那么我们可以建立“姓名”和"年龄的联合索引来加速查询。查询创建的索引db.person.getIndexes()

getIndexes

创建两个组合索引db.person.createIndex({"name":1,"age":1})   db.person.createIndex({"age":1,"name":1})

indexes

此时我们肯定很好奇,到底查询优化器会使用哪个查询作为操作,呵呵,还是看看效果图:

db.person.find({"age":149938,"name":"Lily149938"}).explain("executionStats"); 可以看到用的还是name_1的索引

90

看来还得再测试,再建两个组合索引db.person.createIndex({"rand":1,"age":1}) db.person.createIndex({"age":1,"rand":1})

执行统计分析,好像都是用的一个索引db.person.find({"age":149957,"rand":104550}).explain("executionStats");db.person.find({"rand":89541,"age":149938}).explain("executionStats");

df

看完上图我们要相信查询优化器,它给我们做出的选择往往是最优的,因为我们做查询时,查询优化器会使用我们建立的这些索引来创建查询方案,如果某一个先执行完则其他查询方案被close掉,这种方案会被mongodb保存起来,当然如果非要用自己指定的查询方案,这也是可以的,在mongodb中给我们提供了hint方法让我们可以暴力执行。db.person.find({"age":149957,"rand":104550}).hint({"age":1,"rand":1}).explain("executionStats");

dfg

6,删除索引

可能随着业务需求的变化,原先建立的索引可能没有存在的必要了,可能有的人想说没必要就没必要呗,但是请记住,索引会降低CUD这三
种操作的性能,因为这玩意需要实时维护,所以啥问题都要综合考虑一下,这里就把刚才建立的索引清空掉db.person.dropIndex("name_1_age_1")


发布了32 篇原创文章 · 获赞 14 · 访问量 17万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章