关于后端:MongoDB-索引

5次阅读

共计 6483 个字符,预计需要花费 17 分钟才能阅读完成。

每日一句

Nothing like a little truth to sober you up.
唯有事实最能让人苏醒。

概述

索引反对在 MongoDB 中高效地执行查问。如果没有索引,MongoDB 必须执行全汇合扫描,即扫描汇合中的每个文档,以抉择与查问语句匹配的文档。这种扫描全汇合的查问效率是非常低的,特地在解决大量的数据时,查问能够要花费几十秒甚至几分钟,这对网站的性能是十分致命的。

如果查问存在适当的索引,MongoDB 能够应用该索引限度必须查看的文档数。

索引是非凡的数据结构,它以易于遍历的模式存储汇合数据集的一小部分。索引存储特定字段或一组字段的值,按字段值排序。索引项的排序反对无效的相等匹配和基于范畴的查问操作。此外,MongoDB 还能够应用索引中的排序返回排序后果。

官网文档:https://docs.mongodb.com/manual/indexes/

MongoDB 索引应用 B 树数据结构(确切的说是 B -Tree,MySQL 是 B +Tree)

索引分类

MongoDB 的索引能够分为:单字段索引、复合索引以及天文空间索引等。

单字段索引:MongoDB 反对在文档的单个字段上创立用户定义的升序 / 降序索引,称为单字段索引(Single Field Index)。

对于单个字段索引和排序操作,索引键的排序程序(即升序或降序)并不重要,因为 MongoDB 能够在任何方向上遍历索引。

复合索引:MongoDB 还反对多个字段的用户定义索引,即复合索引(Compound Index)。

复合索引中列出的字段程序具备重要意义。例如,如果复合索引由 {userid: 1, score: -1} 组成,则索引首先按 userid 正序排序,而后在每个 userid 的值内,再在按 score 倒序排序。

其余索引:

  • 天文空间索引(Geospatial Index)
  • 文本索引(Text Indexes)
  • 哈希索引(Hashed Indexes)。

天文空间索引(Geospatial Index): 为了反对对天文空间坐标数据的无效查问,MongoDB 提供了两种非凡的索引:返回后果时应用平面几何的二维索引和返回后果时应用球面几何的二维球面索引。

文本索引(Text Indexes):MongoDB 提供了一种文本索引类型,反对在汇合中搜寻字符串内容。这些文本索引不存储特定于语言的进行词(例如“the”、“a”、“or”),而将汇合中的词作为词干,只存储根词。

哈希索引(Hashed Indexes): 为了反对基于散列的分片,MongoDB 提供了散列索引类型,它对字段值的散列进行索引。这些索引在其范畴内的值散布更加随机,但只反对相等匹配,不反对基于范畴的查问。

索引操作

查看索引

返回一个汇合中的所有索引的数组

语法格局 db.collection.getIndexes()

提醒 :该语法命令运行要求是 MongoDB 3.0+

示例

# 查看 comment 汇合中所有的索引状况
> db.comment.getIndexes()
[{ "v" : 2, "key" : { "_id" : 1}, "name" : "_id_" } ]
>

后果中显示的是默认 _id 索引。

默认_id 索引 :MongoDB 在创立汇合的过程中,在 _id 字段上创立一个惟一的索引,默认名字为 id,该索引可避免客户端插入两个具备雷同值的文档,您不能在_id 字段上删除此索引。

留神 :该索引是惟一索引,因而值不能反复,即 _id 值不能反复的。在分片集群中,通常应用 _id 作为片键。

创立索引

在汇合上创立索引。

语法格局 db.collection.createIndex(keys, options)

参数阐明

Parameter Type Description
keys document 蕴含字段和值对的文档,其中字段是索引键,值形容该字段的索引类型。对于字段上的升序索引,请指定值 1;对于降序索引,请指定值 -1。比方:{字段:1 或 -1},其中 1 为指定按升序创立索引,如果你想按降序来创立索引指定为 -1 即可。另外,MongoDB 反对几种不同的索引类型,包含文本、天文空间和哈希索引。
options document 可选。蕴含一组管制索引创立的选项的文档。无关详细信息,请参见选项详情列表

options(更多选项)列表:

Parameter Type Description
background Boolean 建索引过程会阻塞其它数据库操作,background 可指定当前台形式创立索引,即减少 ”background” 可选参数。“background” 默认值为 false。
unique Boolean 建设的索引是否惟一。指定为 true 创立惟一索引。默认值为 false.
name string 索引的名称。如果未指定,MongoDB 的通过连贯索引的字段名和排序程序生成一个索引名称。
sparse Boolean 对文档中不存在的字段数据不启用索引;这个参数须要特地留神,如果设置为 true 的话,在索引字段中不会查问出不蕴含对应字段的文档.。默认值为 false.
expireAfterSeconds integer 指定一个以秒为单位的数值,实现 TTL 设定,设定汇合的生存工夫。
v index version 索引的版本号。默认的索引版本取决于 mongod 创立索引时运行的版本。
weights document 索引权重值,数值在 1 到 99,999 之间,示意该索引绝对于其余索引字段的得分权重。
default_language string 对于文本索引,该参数决定了停用词及词干和词器的规定的列表。默认为英语
language_override string 对于文本索引,该参数指定了蕴含在文档中的字段名,语言笼罩默认的 language,默认值为 language.

留神 : 在 3.0.0 版本前创立索引办法为 db.collection.ensureIndex(),之后的版本应用了 db.collection.createIndex() 办法,ensureIndex() 还能用,但只是 createIndex() 的别名。

实例

# 单字段索引示例:对 userid 字段建设索引 userid:1 示意升序索引
> db.comment.createIndex({userid:1})
{
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "createdCollectionAutomatically" : false,
    "ok" : 1
}
> db.comment.getIndexes()
[
  {
    "v" : 2,
    "key" : {"_id" : 1},
    "name" : "_id_"
  },
  {
    "v" : 2,
    "key" : {"userid" : 1},
    "name" : "userid_1"
  }
]
>

# 复合索引:对 userid 和 nickname 同时建设复合(Compound)索引
> db.comment.createIndex({userid:1,nickname:-1})
{
    "numIndexesBefore" : 2,
    "numIndexesAfter" : 3,
    "createdCollectionAutomatically" : false,
    "ok" : 1
}
> db.comment.getIndexes()
[
  {
    "v" : 2,
    "key" : {"_id" : 1},
    "name" : "_id_"
  },
  {
    "v" : 2,
    "key" : {"userid" : 1},
    "name" : "userid_1"
  },
  {
    "v" : 2,
    "key" : {
        "userid" : 1,
        "nickname" : -1
    },
    "name" : "userid_1_nickname_-1"
  }
]
>

移除索引

能够移除指定的索引,或移除所有索引

语法格局 db.collection.dropIndex(index) 或移除所有索引 db.collection.dropIndexes()

参数阐明

Parameter Type Description
index string or document 指定要删除的索引。能够通过索引名称或索引标准文档指定索引。若要删除文本索引,请指定索引名称。

实例

# 删除 comment 汇合中 userid 字段上的升序索引
> db.comment.getIndexes()
[
  {
    "v" : 2,
    "key" : {"_id" : 1},
    "name" : "_id_"
  },
  {
    "v" : 2,
    "key" : {"userid" : 1},
    "name" : "userid_1"
  },
  {
    "v" : 2,
    "key" : {
        "userid" : 1,
        "nickname" : -1
    },
    "name" : "userid_1_nickname_-1"
  }
]
> db.comment.dropIndex({userid:1})
{"nIndexesWas" : 3, "ok" : 1}
> db.comment.getIndexes()
[
  {
    "v" : 2,
    "key" : {"_id" : 1},
    "name" : "_id_"
  },
  {
    "v" : 2,
    "key" : {
        "userid" : 1,
        "nickname" : -1
    },
    "name" : "userid_1_nickname_-1"
  }
]
>

# 所有索引的移除
> db.comment.getIndexes()
[
  {
    "v" : 2,
    "key" : {"_id" : 1},
    "name" : "_id_"
  },
  {
    "v" : 2,
    "key" : {
      "userid" : 1,
      "nickname" : -1
    },
    "name" : "userid_1_nickname_-1"
  }
]
> db.comment.dropIndexes()
{
  "nIndexesWas" : 2,
  "msg" : "non-_id indexes dropped for collection",
  "ok" : 1
}
> db.comment.getIndexes()
[{ "v" : 2, "key" : { "_id" : 1}, "name" : "_id_" } ]
>

提醒 :_id 的字段的索引是无奈删除的,只能删除非 _id 字段的索引。

索引应用

执行打算

剖析查问性能(Analyze Query Performance)通常应用执行打算(解释打算、Explain Plan)来查看查问的状况,如查问消耗的工夫、是否基于索引查问等。

那么,通常,咱们想晓得,建设的索引是否无效,成果如何,都须要通过执行打算查看。

语法格局 db.collection.find(query,options).explain(options)

实例

# 查看依据 userid 查问数据的状况 关键点看:"stage" : "COLLSCAN", 示意全汇合扫描
> db.comment.find({userid:"1003"}).explain()
{
    "explainVersion" : "1",
    "queryPlanner" : {
            "namespace" : "test1.comment",
            ...
            "winningPlan" : {
                **"stage" : "COLLSCAN",**
                ...
            },
            "rejectedPlans" : []},
    ...,
    "ok" : 1
}
>

# 上面对 userid 建设索引 再次查看执行打算 关键点看:"stage" : "IXSCAN" , 基于索引的扫描
> db.comment.createIndex({userid:1})
{
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "createdCollectionAutomatically" : false,
        "ok" : 1
}
> db.comment.find({userid:"1013"}).explain()
{
  "explainVersion" : "1",
  "queryPlanner" : {
    ...
    "winningPlan" : {
      "stage" : "FETCH",
      "inputStage" : {
        **"stage" : "IXSCAN",**
        ...
      }
    },
    "rejectedPlans" : []},
  ...
  "ok" : 1
}
>

涵盖查问 Covered Queries

当查问条件和查问的投影仅蕴含索引字段时,MongoDB 间接从索引返回后果,而不扫描任何文档或将文档带入内存。这些笼罩的查问能够十分无效。

我的了解是相似于 mysql 的索引笼罩,毋庸回表查问。

实例

> db.comment.find({userid:"1003"},{userid:1,_id:0})
{"userid" : "1003"}
{"userid" : "1003"}
> db.comment.find({userid:"1003"},{userid:1,_id:0}).explain()
{
  "explainVersion" : "1",
  "queryPlanner" : {
    "namespace" : "test1.comment",
    "indexFilterSet" : false,
    "parsedQuery" : {
            "userid" : {"$eq" : "1003"}
    },
    "queryHash" : "8177476D",
    "planCacheKey" : "F842FA57",
    "maxIndexedOrSolutionsReached" : false,
    "maxIndexedAndSolutionsReached" : false,
    "maxScansToExplodeReached" : false,
    "winningPlan" : {
      "stage" : "PROJECTION_COVERED",
      "transformBy" : {
        "userid" : 1,
        "_id" : 0
      },
      "inputStage" : {
        "stage" : "IXSCAN",
        "keyPattern" : {"userid" : 1},
        "indexName" : "userid_1",
        "isMultiKey" : false,
        "multiKeyPaths" : {"userid" : []
        },
        "isUnique" : false,
        "isSparse" : false,
        "isPartial" : false,
        "indexVersion" : 2,
        "direction" : "forward",
        "indexBounds" : {
          "userid" : ["[\"1003\", \"1003\"]"
          ]
        }
      }
    },
    "rejectedPlans" : []},
  "command" : {
      "find" : "comment",
      "filter" : {"userid" : "1003"},
      "projection" : {
        "userid" : 1,
        "_id" : 0
      },
      "$db" : "test1"
  },
  "serverInfo" : {
    "host" : "DESKTOP-LVOGL41",
    "port" : 27017,
    "version" : "5.0.5",
    "gitVersion" : "d65fd89df3fc039b5c55933c0f71d647a54510ae"
  },
  "serverParameters" : {
    "internalQueryFacetBufferSizeBytes" : 104857600,
    "internalQueryFacetMaxOutputDocSizeBytes" : 104857600,
    "internalLookupStageIntermediateDocumentMaxSizeBytes" : 104857600,
    "internalDocumentSourceGroupMaxMemoryBytes" : 104857600,
    "internalQueryMaxBlockingSortMemoryUsageBytes" : 104857600,
    "internalQueryProhibitBlockingMergeOnMongoS" : 0,
    "internalQueryMaxAddToSetBytes" : 104857600,
    "internalDocumentSourceSetWindowFieldsMaxMemoryBytes" : 104857600
  },
  "ok" : 1
}
>

美文佳句

有故事的人,通常不喜爱讲故事。不想在嘴上卖命,是想在心中开发能量。缄默,是一种负重的刚强,是一种韬光养晦的低调。少说多做,才是最无力的践行。

你好,我是 yltrcc,日常分享技术点滴,欢送关注我的公众号:ylcoder

正文完
 0