搜索
首页数据库mysql教程mongodb索引使用以及使用explain与profile调优

索引是用来加快查询速度的,事物都有双面性的,同时在每次插入、更新和删除操作时都会产生额外的开销。索引有时并不能解决查询慢的问题,一般来说,返回集合中一半以上的结果,全表扫描要比查询索引更高效些。 创建太多索引,会导致插入非常慢,同时还会占用

索引是用来加快查询速度的,事物都有双面性的,同时在每次插入、更新和删除操作时都会产生额外的开销。索引有时并不能解决查询慢的问题,一般来说,返回集合中一半以上的结果,全表扫描要比查询索引更高效些。 创建太多索引,会导致插入非常慢,同时还会占用很大空间。可以通过explain和hint工具来分析。 索引有方向的,倒序还是升序。 每个集合默认的最大索引个数为64个。

1. 查看索引

> db.jiunile_events.getIndexes();
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "ns" : "jiunile_login.jiunile_events",
                "name" : "_id_"
        },
        {
                "v" : 1,
                "key" : {
                        "stmp" : -1
                },
                "ns" : "jiunile_login.jiunile_events",
                "name" : "stmp_-1"
        },
        {
                "v" : 1,
                "key" : {
                        "uid" : 1,
                        "stmp" : -1
                },
                "ns" : "jiunile_login.jiunile_events",
                "name" : "uid_1_stmp_-1"
        }
]

此实例中有三个索引,其中_id是创建表的时候自动创建的索引,不能删除。uid_1_stmp_-1是组合索引。1表示升序,-1表示降序。

2. 创建索引 索引参数有:

option			values				default
backgroud		true/false			false
dropDups		true/false			false
unique			true/false			false
sparse			true/false			false

常规索引创建

> db.jiunile_posts.ensureIndex({pid:1});

当有大量数据时,创建索引会非常耗时,可以指定到后台执行,只需指定“backgroud:true”即可。如

> db.jiunile_posts.ensureIndex({pid:1},{backgroud:true});

3. 嵌入式索引 为内嵌文档的键创建索引与普通的键创建索引并无差异。

> db.jiunile_posts.ensureIndex({"post.date":1})

4. 文档式索引

> db.jiunile_comments.insert({cid:222, properties:{user:'jiunile', email:'jiunile@jiunile.com'}})
> db.jiunile_comments.ensureIndex({properties:1})

5. 组合索引

> db.jiunile_comments.ensureIndex({"properties.user":1,"properties.email":1})

以下的查询将使用到此索引

> db.jiunile_comments.find({"properties.user":'jiunile',"properties.email":'jiunile@jiunile.com'})
> db.jiunile_comments.find({"properties.user":'jiunile'})
> db.jiunile_comments.find().sort({"properties.user":1})

对多个值进行组合索引,查询时,子查询与索引前缀匹配时,才可以使用该组合索引。

6. 唯一索引 只需要在ensureIndex命名中指定"unique:true"即可。

> db.jiunile_posts.ensureIndex({pid:1},{unique:true})

当为已有的集合创建索引,可能有些数据已经有重复了的,那么创建唯一索引将失败。可以使用dropDups来保留第一个文档,而后的重复文档将删除,这种方法慎重操作。

> db.jiunile_posts.ensureIndex({pid:1},{unique:true, dropDups:true})

7. 强制索引 hint命令可以强制使用某个索引

> db.jiunile_posts.find({pid:{$lt:333}}).hint({pid:1,date:1})

8. 删除索引 删除集合所有索引:

> db.collection.dropIndexes()

删除集合某个索引:

> db.collection.dropIndex({x:1})

9. 重建索引

> db.collection.reIndex()
> db.runCommand({reIndex:'collection'})

重建索引会锁住集合的。用repair命令修复数据库时,会重建索引的。

10. 全文索引 mongodb全文索引是在2.4版本引入的,后面再说这个。

11. explain执行计划 使用explain命令返回查询使用的索引情况,耗时,扫描文档数等等统计信息。

> db.jiunile_events.find({uid:178620830}).explain()
{
        "cursor" : "BtreeCursor uid_1_stmp_-1",
        "isMultiKey" : false,
        "n" : 2,
        "nscannedObjects" : 2,
        "nscanned" : 2,
        "nscannedObjectsAllPlans" : 2,
        "nscannedAllPlans" : 2,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 4,
        "indexBounds" : {
                "uid" : [
                        [
                                178620830,
                                178620830
                        ]
                ],
                "stmp" : [
                        [
                                {
                                        "$maxElement" : 1
                                },
                                {
                                        "$minElement" : 1
                                }
                        ]
                ]
        },
        "server" : "jiunile-191155:27017"
}

字段说明:

cursor:返回游标类型
isMultiKey:是否使用组合索引
n:返回文档数量
nscannedObjects:被扫描的文档数量
nscanned:被检查的文档或索引条目数量
scanAndOrder:是否在内存中排序
indexOnly:
nYields:该查询为了等待写操作执行等待的读锁的次数
nChunkSkips:
millis:耗时(毫秒)
indexBounds:所使用的索引
server: 服务器主机名

12. 开启profiling功能 查看profiling级别:

> db.getProfilingLevel()
0

设置profiling级别:

> db.setProfilingLevel( level , slowms )
> db.setProfilingLevel(2,10)
{ "was" : 0, "slowms" : 100, "ok" : 1 }

profile的级别可以取0,1,2 表示的意义如下:

0 – 不开启 默认级别

1 – 记录慢命令 (默认为>100ms)

2 – 记录所有命令

13. 查询profiling记录 MongoDB Profile 记录是直接存在系统 db 里的,记录位置system.profile 。

> db.system.profile.find().sort({$natural:-1}).limit(1)
{ "ts" : ISODate("2013-07-18T09:56:59.546Z"), "op" : "query", "ns" : "jiunile_event.jiunile_events", "query" : { "$query" : { "uid" : 161484152, "stmp" : { "$gt" : 0 } }, "$orderby" : { "stmp" : -1 } }, "ntoreturn" : 0, "ntoskip" : 0, "nscanned" : 35, "keyUpdates" : 0, "numYield" : 0, "lockStats" : { "timeLockedMicros" : { "r" : NumberLong(354), "w" : NumberLong(0) }, "timeAcquiringMicros" : { "r" : NumberLong(3), "w" : NumberLong(3) } }, "nreturned" : 35, "responseLength" : 7227, "millis" : 0, "client" : "10.1.242.209", "user" : "" }
> db.system.profile.find().pretty().limit(1)
{
        "ts" : ISODate("2013-07-18T09:53:40.103Z"),
        "op" : "query",
        "ns" : "jiunile_event.jiunile_event_friends",
        "query" : {
                "_id" : 195794232
        },
        "ntoreturn" : 1,
        "idhack" : true,
        "keyUpdates" : 0,
        "numYield" : 0,
        "lockStats" : {
                "timeLockedMicros" : {
                        "r" : NumberLong(45),
                        "w" : NumberLong(0)
                },
                "timeAcquiringMicros" : {
                        "r" : NumberLong(3),
                        "w" : NumberLong(5)
                }
        },
        "responseLength" : 20,
        "millis" : 0,
        "client" : "10.1.22.199",
        "user" : ""
}

字段说明:

ts: 该命令在何时执行
op: 操作类型
query: 本命令的详细信息
responseLength: 返回结果集的大小
ntoreturn: 本次查询实际返回的结果集
millis: 该命令执行耗时,以毫秒记

14. 修改profiling大小 capped Collections 比普通Collections 的读写效率高。Capped Collections 是高效率的Collection类型,它有如下特点:

a. 固定大小;Capped Collections 必须事先创建,并设置大小:

> db.createCollection("collection", {capped:true, size:100000}) 

b. Capped Collections 可以insert 和update 操作,不能delete 操作。只能用drop()方法删除整个Collection。

c. 默认基于Insert 的次序排序的。如果查询时没有排序,则总是按照insert 的顺序返回。

d. FIFO。如果超过了Collection 的限定大小,则用FIFO 算法,新记录将替代最先insert的记录

> db.setProfilingLevel(0)
{ "was" : 2, "slowms" : 10, "ok" : 1 }
>
> db.getProfilingLevel()
0
> db.system.profile.drop()
true
> db.createCollection("system.profile",{capped:true, size: 1000000})
{ "ok" : 1 }
> db.system.profile.stats()
{
        "ns" : "jiunile_event.system.profile",
        "count" : 0,
        "size" : 0,
        "storageSize" : 1003520,
        "numExtents" : 1,
        "nindexes" : 0,
        "lastExtentSize" : 1003520,
        "paddingFactor" : 1,
        "systemFlags" : 0,
        "userFlags" : 0,
        "totalIndexSize" : 0,
        "indexSizes" : {
        },
        "capped" : true,
        "max" : 2147483647,
        "ok" : 1
}

来源:http://www.ttlsa.com/html/1661.html

mongodb索引使用以及使用explain与profile调优 索引是用来加快查询速度的,事物都有双面性的,同时在每次插入、更新和删除操作时都会产生额外的开销。索引有时并不能解决查询慢的问题,一般来说,返回集合中一半以上的结果,全表扫描要比查询索引更高效些。 创建太多索引,会导致插入非常慢,同时还会占用很大空间。可以通过explain和hint工具来分析。 索引有方向的,倒序还是升序。 每个集合默认的最大索引个数为64个。 1. 查看索引 此实例中有三个索引,其中_id是创建表的时候自动创建的索引,不能删除。uid_1_stmp_-1是组合索引。1表示升序,-1表示降序。 2. 创建索引 索引参数有: 常规索引创建 当有大量数据时,创建索引会非常耗时,可以指定到后台执行,只需指定“backgroud:true”即可。如 3. 嵌入式索引 为内嵌文档的键创建索引与普通的键创建索引并无差异。 4. 文档式索引 5. 组合索引 以下的查询将使用到此索引 对多个值进行组合索引,查询时,子查询与索引前缀匹配时,才可以使用该组合索引。 6. 唯一索引 只需要在ensureIndex命名中指定"unique:true"即可。 当为已有的集合创建索引,可能有些数据已经有重复了的,那么创建唯一索引将失败。可以使用dropDups来保留第一个文档,而后的重复文档将删除,这种方法慎重操作。 7. 强制索引 hint命令可以强制使用某个索引 8. 删除索引 删除集合所有索引: 删除集合某个索引: 9. 重建索引 重建索引会锁住集合的。用repair命令修复数据库时,会重建索引的。 10. 全文索引 mongodb全文索引是在2.4版本引入的,后面再说这个。 11. explain执行计划 使用explain命令返回查询使用的索引情况,耗时,扫描文档数等等统计信息。 字段说明: 12. 开启profiling功能 查看profiling级别: 设置profiling级别: profile的级别可以取0,1,2 表示的意义如下: 0 – 不开启 默认级别 1 – 记录慢命令 [...]mongodb索引使用以及使用explain与profile调优
声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
在MySQL中使用视图的局限性是什么?在MySQL中使用视图的局限性是什么?May 14, 2025 am 12:10 AM

mysqlviewshavelimitations:1)他们不使用Supportallsqloperations,限制DatamanipulationThroughViewSwithJoinSorsubqueries.2)他们canimpactperformance,尤其是withcomplexcomplexclexeriesorlargedatasets.3)

确保您的MySQL数据库:添加用户并授予特权确保您的MySQL数据库:添加用户并授予特权May 14, 2025 am 12:09 AM

porthusermanagementInmysqliscialforenhancingsEcurityAndsingsmenting效率databaseoperation.1)usecReateusertoAddusers,指定connectionsourcewith@'localhost'or@'%'。

哪些因素会影响我可以在MySQL中使用的触发器数量?哪些因素会影响我可以在MySQL中使用的触发器数量?May 14, 2025 am 12:08 AM

mysqldoes notimposeahardlimitontriggers,butacticalfactorsdeterminetheireffactective:1)serverConfiguration impactactStriggerGermanagement; 2)复杂的TriggerSincreaseSySystemsystem load; 3)largertablesslowtriggerperfermance; 4)highConconcConcrencerCancancancancanceTigrignecentign; 5); 5)

mysql:存储斑点安全吗?mysql:存储斑点安全吗?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

mySQL:通过PHP Web界面添加用户mySQL:通过PHP Web界面添加用户May 14, 2025 am 12:04 AM

通过PHP网页界面添加MySQL用户可以使用MySQLi扩展。步骤如下:1.连接MySQL数据库,使用MySQLi扩展。2.创建用户,使用CREATEUSER语句,并使用PASSWORD()函数加密密码。3.防止SQL注入,使用mysqli_real_escape_string()函数处理用户输入。4.为新用户分配权限,使用GRANT语句。

mysql:blob和其他无-SQL存储,有什么区别?mysql:blob和其他无-SQL存储,有什么区别?May 13, 2025 am 12:14 AM

mysql'sblobissuitableForStoringBinaryDataWithInareLationalDatabase,而alenosqloptionslikemongodb,redis和calablesolutionsoluntionsoluntionsoluntionsolundortionsolunsolunsstructureddata.blobobobsimplobissimplobisslowderperformandperformanceperformancewithlararengelitiate;

mySQL添加用户:语法,选项和安全性最佳实践mySQL添加用户:语法,选项和安全性最佳实践May 13, 2025 am 12:12 AM

toaddauserinmysql,使用:createUser'username'@'host'Indessify'password'; there'showtodoitsecurely:1)choosethehostcarecarefullytocon trolaccess.2)setResourcelimitswithoptionslikemax_queries_per_hour.3)usestrong,iniquepasswords.4)Enforcessl/tlsconnectionswith

MySQL:如何避免字符串数据类型常见错误?MySQL:如何避免字符串数据类型常见错误?May 13, 2025 am 12:09 AM

toAvoidCommonMistakeswithStringDatatatPesInMysQl,CloseStringTypenuances,chosethirtightType,andManageEngencodingAndCollat​​ionsEttingsefectery.1)usecharforfixed lengengters lengengtings,varchar forbariaible lengength,varchariable length,andtext/blobforlabforlargerdata.2 seterters seterters seterters seterters

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具