您的位置:首页 > 数据库 > Mongodb

mongodb-manual-3.0.0 indexes2

2015-05-29 13:45 579 查看
Compound Indexes

mongodb支持复合索引。

{

"_id":ObjectId(...),

"item":"Banana",

"category":[
"food",
"produce",
"grocery"],

"location":"4th Street Store",

"stock":4,

"type":"cases",

"arrival":Date(...)

}

像上面的文档,如果你要查询item或者要查询item和stock(一起查),你可以建一个复合索引:db.products.createIndex(
{ "item":1,"stock":1
} )来完成上面的两种查询。

(!!!重要!!!!)如果在有hash索引的地方你想建组合索引,就会出错。
组合索引中field的排列顺序十分重要。
除了支持索引域的查询外,组合索引还支持对索引字段的前缀查询。

Sort Order
索引存储field的相关信息要么是升序的,要么是降序的。对于单个field的索引来说升序和降序并不重要,因为mongodb可以在任何一个方向遍历索引。但是对于组合索引来说,这个顺序就非常重要了,因为它决定了这个索引是否能进行某种顺序操作。
例如:
db.events.createIndex( {"username"
:
1,"date"
: -1
} )这个索引支持db.events.find().sort( { username: 1,
date: -1 } )和db.events.find().sort( { username:
-1, date:1
} )。

但是它不支持:db.events.find().sort( { username: 1,
date: 1 } )

Prefixes:索引前缀是组合索引前一个或几个索引,例如:组合索引:{"item":1,"location":1,"stock":1}可以使用到前缀索引的是下面几种查询方式:

{
item:1 }
{
item:1, location:1 }
{
item:1, location:1 stock:1 }
{
item:1, stock:1 } 这个索引不像上面其它那么高效

但是下面几种查询是不会使用到上面索引的:
{ location:1 }
{ stock:1 }
{ location:1 stock:1 }

如果你的collection有一个组合索引,并且还有前缀索引例如你有:db.events.createIndex( { "username" : 1, "date" :
1 } ),又有db.events.createIndex( { "username" : 1} )如果你第二个索引没有稀疏或唯一性的限制,那么还是把第二个索引删除了吧,因为mongodb默认会使用组合索引中的前缀索引。
index
intersection
2.6版本开始可以使用index
intersection技术。但是到底是使用compound index还是使用 index intersection根据你的系统特点来决定。

multikey
indexes
为了索引一个包含数组的field,mongodb会给数组中的每一个条目都加索引。这些multikey indexes允许mongodb使用数组中的值返回document。如果包括数组,mongodb会自动决定是否要创建multikey index,你不需要显示地指定multikey type。

Limitations
Interactions between Compound and Multikey Indexes
可能有这种情况:组合索引中,一个field有数组。你可以建一个像这样的索引:{ a: 1,b: 1 }给下面两种集合:{a:
[
1,
2], b:
1},{a:
1, b:
[
1,
2]}

(!!!重要!!!)但是不能向一个建了{ a: 1,b: 1 }索引的collection中插入{a:
[
1,
2], b:
[
1,
2]}。主要是为了防止索引无限变大不好维护。
(!!!重要!!!)shard
key不能有multi-key 索引和2dsphere索引,但可以有地理索引。

hash
indexes
hash
indexes不能和multi-key兼容。
不能在一个有hash
indexes的field上加compound indexes和unique constraint。但是可以加上 ascending/descending index。MongoDB will use the scalar index for range queries.

mongodb将破坏内嵌文档的结构并使用全部的值来计算hash值(这段翻译有点不懂附上英文)
To
compute the hash for a
hashed index, MongoDB collapses embedded documents and computes the hash for the

entire value. For fields that hold arrays or embedded documents, you cannot use the index to support queries that

introspect the embedded document。

(!!!重要!!!)mongodb在计算hash值之前,会截断浮点数,使之变成64位整数。例如对于2.3,2.2,2.9它们的hash值都是一样的。

创建hash索引的方法为:db.active.createIndex(
{ a:
"hashed" } )。

它的用词是collapse.

后面是一个例子,页数是472.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: