为什么MongoDB中的索引方向很重要? [英] Why does direction of index matter in MongoDB?

查看:151
本文介绍了为什么MongoDB中的索引方向很重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用文档


创建索引时,与键关联的数字指定索引的
方向,因此它应始终为1(升序)或-1
(降序)。方向对于单个键索引或
随机访问检索无关紧要,但如果您对复合索引进行排序或
范围查询,则这一点非常重要。

When creating an index, the number associated with a key specifies the direction of the index, so it should always be 1 (ascending) or -1 (descending). Direction doesn't matter for single key indexes or for random access retrieval but is important if you are doing sorts or range queries on compound indexes.

但是,我认为没有理由为什么索引的方向对复合索引很重要。有人可以提供进一步的解释(或示例)吗?

However, I see no reason why direction of the index should matter on compound indexes. Can someone please provide a further explanation (or an example)?

推荐答案

MongoDB以某种方式连接复合键并将其用作BTree中的密钥。

MongoDB concatenates the compound key in some way and uses it as the key in a BTree.

查找单个项目时 - 树中节点的顺序无关紧要。

When finding single items - The order of the nodes in the tree is irrelevant.

如果要返回一系列节点 - 彼此靠近的元素将位于树的相同分支下。节点越接近范围,它们就越快被检索。

If you are returning a range of nodes - The elements close to each other will be down the same branches of the tree. The closer the nodes are in the range the quicker they can be retrieved.

使用单个字段索引 - 订单无关紧要。如果它们按升序靠近在一起,它们也会按降序排列在一起。

With a single field index - The order won't matter. If they are close together in ascending order they will also be close together in descending order.

当你有复合键时 - 订单开始无关紧要。

When you have a compound key - The order starts to matter.

例如,如果密钥是A升序B升序,索引可能如下所示:

For example, if the key is A ascending B ascending the index might look something like this:


Row   A B
1     1 1
2     2 6
3     2 7 
4     3 4
5     3 5
6     3 6
7     5 1

A升序B降序的查询需要在索引周围跳转到返回行会慢一些。例如,它将返回Row 1,3,2,6,5,4,7

A query for A ascending B descending will need to jump around the index out of order to return the rows and will be slower. For example it will return Row 1, 3, 2, 6, 5, 4, 7

远程查询以与索引相同的顺序将以正确的顺序依次返回行。

A ranged query in the same order as the index will simply return the rows sequentially in the correct order.

在BTree中查找记录需要O(Log(n))时间。按顺序查找一系列记录仅为OLog(n)+ k,其中k是要返回的记录数。

Finding a record in a BTree takes O(Log(n)) time. Finding a range of records in order is only OLog(n) + k where k is the number of records to return.

如果记录乱序,则成本可能与OLog(n)* k

If the records are out of order, the cost could be as high as OLog(n) * k

这篇关于为什么MongoDB中的索引方向很重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆