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

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

问题描述

引用文档:

<块引用>

创建索引时,与键关联的数字指定索引的方向,所以它应该总是 1(升序)或 -1(降序).方向对于单个键索引或对于随机访问检索,但如果您进行排序或复合索引的范围查询.

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

解决方案

MongoDB 以某种方式连接复合键,并将其用作 BTree 中的键.

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

如果您返回一系列节点 - 彼此靠近的元素将沿着树的相同分支向下.节点在范围内越近,检索它们的速度就越快.

使用单个字段索引 - 顺序无关紧要.如果它们以升序排列在一起,它们也会以降序排列在一起.

当你有一个复合键 - 顺序开始很重要.

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

<前>行 A B1 1 12 2 63 2 74 3 45 3 56 3 67 5 1

对 A 升序 B 降序的查询将需要乱序绕过索引以返回行并且速度会更慢.例如它将返回行 1, 3, 2, 6, 5, 4, 7

与索引顺序相同的范围查询只会以正确的顺序依次返回行.

在 BTree 中查找记录需要 O(Log(n)) 时间.按顺序查找记录范围只需 OLog(n) + k,其中 k 是要返回的记录数.

如果记录乱序,代价可能高达 OLog(n) * k

To quote the docs:

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 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.

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 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.

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.

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

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

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