[mongo]索引机制

索引机制

术语

  • Covered Query

    • 如果所有需要的字段都在索引中,不需要额外的字段,就可
      以不再需要从数据页加载数据,这就是查询覆盖
  • IXSCAN/COLLSCAN

    • 索引扫描/集合扫描
    • 可以理解为索引扫描,全表扫描
  • Big O Notation

    • 时间复杂度
    • image
  • Query Shape

    • 查询的形状
    • image
  • Index Prefix

    • db.human.createIndex({firstName: 1, lastName: 1, gender: 1, age: 1})
    • 以上索引的全部前缀包括
      • {firstName: 1}
      • {firstName: 1, lastName: 1}
      • {firstName: 1, lastName: 1, gender: 1}
    • 所有索引前缀都可以被该索引覆盖,没有必要针对这些查询建立额外的索引
  • Selectivity

    • 过滤性
  • B树结构

索引执行计划

  • image

explain()

  • db.col.find({name:1111}).explain(true)

MongoDB 索引类型

组合索引 – Compound Index
- 最佳方式:ESR原则
    - 精确(Equal)匹配的字段放最前面
    - 排序(Sort)条件放中间
    - 范围(Range)匹配的字段放最后面
    - 同样适用: ES, ER
  • 范围组合查询: 索引字段顺序的影响
    • db.test.find({a: 2, b: {$gte: 2, $lte: 3}, c: 1})

      • image
    • db.test.find({a: 2, b: {$gte: 2, $lte: 3}, c: 1})

      • image
    • db.test.find({a: 2, b: {$gte: 2, $lte: 3}).sort({c: 1})

      • image
    • db.test.find({a: 2, b: {$gte: 2, $lte: 3}).sort({c: 1})

      • image
地理位置索引
db.geo_col.createIndex( { location: “2d”} , { min:-20, max: 20 , bits: 10},
{collation:{locale: "simple"} } )
-- 查询
db.geo_col.find( 
{ location : 
{ $geoWithin : 
{ $box : [ [ 1, 1 ] , [ 3, 3 ] ] } } }
)
全文索引
-- 插入数据
db.<collection_name>.insert(
{ _id: 1, content: “This morning I had a cup of 
coffee.”, about: “beverage”, keywords: [ 
“coffee” ] } ,
{ _id: 2, content: "Who doesn't like cake?", 
about: "food", keywords: [ "cake", "food", 
"dessert" ] },
{ _id: 3, content: "Why need coffee?", about: 
”food", keywords: [ ”drink", "food" ] }
)
-- 创建索引
>> db.<collection_name>.createIndex(
{‘content’ : “text” } )
部分索引
-- 创建部分索引
>> db.<collection_name>.createIndex( 
{‘a’: 1 }, 
{ partialFilterExpression: 
{a:
{$gte:5}
} )

-- 只对有wechat字段的建索引:
>> db.<collection_name>.createIndex( 
{‘wechat’: 1 }, 
{ partialFilterExpression: 
{wechat:
{$exists: true}
} )
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值