MongoDB 索引

基本

  1. 在没有索引的情况下,collection scan ,扫描集合中所有的文档
  2. 索引的有序性使得等值匹配和基于范围的查询非常高效
  3. MongoDb通过有序索引可以返回已排序数据集
  4. 在collection级别定义索引,索引可以建立在任何字段或者子字段
  5. MongoDB indexes use a B-tree data structure.

默认 _id 索引

MongoDB在集合创建的时候会在_id字段上建立unique index,而且这个索引不能被删除。

创建索引

db.collection.createIndex( <key and index type specification>, <options> )

shell中创建索引

// -1降序   1升序
db.collection.createIndex( { name: -1 } )

java代码创建索引

collection.createIndex(Indexes.descending("name"));

注意:创建索引只有在之前索引不存在的情况下,才会成功创建;否则不会成功,也不会报错。但是结果里面会有提示:

{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 3,
    "numIndexesAfter" : 3,
    "note" : "all indexes already exist",
    "ok" : 1.0
}

索引的类型

Single Field

跟_id 唯一索引不同的是,mongodb支持在单字段创建用户定义的升序/降序 索引

Compound Index

复合索引的创建语法跟普通索引类似

db.data.createIndex( { a:1, b: 1, c: 1, d: 1 } )

sort 与 Index Prefix

db.data.find().sort( { a: -1 } )    //{ a: 1 }
db.data.find().sort( { a: 1, b: 1, c: 1 } )     //{ a: 1, b: 1, c: 1 }
db.data.find( { a: { $gt: 4 } } ).sort( { a: 1, b: 1 } )   //{ a: 1, b: 1 }

sort 与 Non-prefix Subset of an Index

db.data.find( { a: 5 } ).sort( { b: 1, c: 1 } ) //{ a: 1 , b: 1, c: 1 }
db.data.find( { b: 3, a: 4 } ).sort( { c: 1 } ) //{ a: 1, b: 1, c: 1 }

Multikey Index

这里指的是在建立在数组中元素上的索引,创建语法也比较简单

db.coll.createIndex( { <field>: < 1 or -1 > } )

例如:

//对于这样的集合文档数据
{
    userid:"ssd",
    addr:[
        {zip:"1003"},
        {zip:"121"}
    ]
}
//索引如下:
{"addr.zip":1}

Unique Multikey Index

{ _id: 1, a: [ { loc: "A", qty: 5 }, { qty: 10 } ] }
{ _id: 2, a: [ { loc: "A" }, { qty: 5 } ] }
{ _id: 3, a: [ { loc: "A", qty: 10 } ] }
db.collection.createIndex( { "a.loc": 1, "a.qty": 1 }, { unique: true } )
db.collection.insert( { _id: 4, a: [ { loc: "A" }, { qty: 5 } ] } )
//E11000 duplicate key error collection: test.testcol index: _id_ dup key: { : 4.0 }

限制

For a compound multikey index, each indexed document can have at most one indexed field whose value is an array.

{ _id: 1, a: [ 1, 2 ], b: [ 1, 2 ], category: "AB - both arrays" }
// You cannot create a compound multikey index { a: 1, b: 1 }

{ _id: 1, a: [1, 2], b: 1, category: "A array" }
{ _id: 2, a: 1, b: [1, 2], category: "B array" }
// A compound multikey index { a: 1, b: 1 } is permissible.No document contains array values for both a and b fields.

Geospatial Index

MongoDB支持二维空间索引,这是设计时考虑到基于位置的查询。例如“找到离目标位置最近的N条记录”。可以有效地作为附加条件过滤。

Text Indexes

创建Text Index

对于以下数据来说:

{
    "_id" : 2.0,
    "content" : "最爱下雨天",
    "about" : "rain,1 2 3 4 rain , abc",
    "keywords" : [ 
        "coffee", 
        "night rain"
    ]
}
{
    "_id" : 1.0,
    "content" : "This morning I had a cup of coffee. rain",
    "about" : "beverage",
    "keywords" : [ 
        "coffee", 
        "night rain"
    ]
}

创建以下索引:

db.data.createIndex(
   {
     content: "text",
     about: "text"
   }
 )
// 查询包含单词rain
db.data.find({$text:{$search:"rain"}})

// 查询包含rain但是不包含coffee
db.data.find({$text:{$search:"rain -coffee"}})

Specify Weights

For a text index, the weight of an indexed field denotes the significance of the field relative to the other indexed fields in terms of the text search score.

For each indexed field in the document, MongoDB multiplies the number of matches by the weight and sums the results. Using this sum, MongoDB then calculates the score for the document. See $meta operator for details on returning and sorting by text scores.

The default weight is 1 for the indexed fields. To adjust the weights for the indexed fields, include the weights option in the db.collection.createIndex() method.

db.data.createIndex(
   {
     content: "text",
     keywords: "text",
     about: "text"
   },
   {
     weights: {
       content: 10,
       keywords: 5
     },
     name: "TextIndex"
   }
 )
// 这里content字段匹配到的话,优先级更高

Wildcard Text Indexes

对文档中所有内容是string的字段建立索引,尤其在文档字段不明确的情况特别有用

db.collection.createIndex( { "$**": "text" } )

Hashed Indexes

db.collection.createIndex( { _id: "hashed" } )

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

db.collection.createIndex( <key and index type specification>, { unique: true } )

db.members.createIndex( { groupNumber: 1, lastname: 1, firstname: 1 }, { unique: true } )

Partial Indexes

db.restaurants.createIndex(
   { cuisine: 1 },
   { partialFilterExpression: { rating: { $gt: 5 } } }
)

To use the partial index, a query must contain the filter expression (or a modified filter expression that specifies a subset of the filter expression) as part of its query condition.

db.restaurants.find( { cuisine: "Italian", rating: { $gte: 8 } } )

索引的使用分析

db.data.find().explain()
db.data.find().explain("executionStats")

索引的删除

db.data.dropIndex("IndexName")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值