资讯专栏INFORMATION COLUMN

MongoDB ( 五 )高级_索引

focusj / 1189人阅读

摘要:插入两条数据建立全文索引需要注意的是这里使用关键词来代表全文索引,我们在这里就不建立数据模型了。全文索引查找表示要在全文索引中查东西。全文索引在工作还是经常使用的,比如博客文章的搜索,长文件的关键词搜索,这些都需要使用全文索引来进行。

</>复制代码

  1. 索引

在认识索引的之前我们先建立一张表,并往其中插入200万条数据。

</>复制代码

  1. // test.js
  2. //生成随机数
  3. function GetRandomNum(min,max){
  4. let range = max-min; //得到随机数区间
  5. let rand = Math.random(); //得到随机值
  6. return (min + Math.round(rand *range)); //最小值+随机数取整
  7. }
  8. //console.log(GetRandomNum(10000,99999));
  9. //生成随机用户名
  10. function GetRadomUserName(min,max){
  11. let tempStringArray= "123456789qwertyuiopasdfghjklzxcvbnm".split("");//构造生成时的字母库数组
  12. let outPuttext = ""; //最后输出的变量
  13. //进行循环,随机生产用户名的长度,这里需要生成随机数方法的配合
  14. for(let i=1 ;i
  15. </>复制代码

    1. > mongo
    2. > load("./test.js")
    3. connecting to: mongodb://127.0.0.1:27017/company
    4. MongoDB server version: 3.4.10
    5. ···
    6. // 这个过程可能需要2分钟左右
    7. > use company
    8. switched to db company
    9. > db.randomInfo.stats() // 使用这个查看插入了几条数据
    10. {
    11. "ns" : "company.randomInfo",
    12. "size" : 421908971,
    13. "count" : 1835000,
    14. "avgObjSize" : 229,
    15. "storageSize" : 188686336,
    16. "capped" : false,
    17. "wiredTiger" : {
    18. "metadata" : {
    19. "formatVersion" : 1
    20. },
    21. "creationString" : "access_pattern_hint=none,allocation_size=4KB,app_metadata=(formatVersion=1),block_allocation=best,block_compressor=snappy,cache_resident=false,checksum=on,colgroups=,collator=,columns=,dictionary=0,encryption=(keyid=,name=),exclusive=false,extractor=,format=btree,huffman_key=,huffman_value=,ignore_in_memory_cache_size=false,immutable=false,internal_item_max=0,internal_key_max=0,internal_key_truncate=true,internal_page_max=4KB,key_format=q,key_gap=10,leaf_item_max=0,leaf_key_max=0,leaf_page_max=32KB,leaf_value_max=64MB,log=(enabled=true),lsm=(auto_throttle=true,bloom=true,bloom_bit_count=16,bloom_config=,bloom_hash_count=8,bloom_oldest=false,chunk_count_limit=0,chunk_max=5GB,chunk_size=10MB,merge_max=15,merge_min=0),memory_page_max=10m,os_cache_dirty_max=0,os_cache_max=0,prefix_compression=false,prefix_compression_min=4,source=,split_deepen_min_child=0,split_deepen_per_child=0,split_pct=90,type=file,value_format=u",
    22. "type" : "file",
    23. "uri" : "statistics:table:collection-0-5869292382622143333",
    24. "LSM" : {
    25. "bloom filter false positives" : 0,
    26. "bloom filter hits" : 0,
    27. "bloom filter misses" : 0,
    28. "bloom filter pages evicted from cache" : 0,
    29. "bloom filter pages read into cache" : 0,
    30. "bloom filters in the LSM tree" : 0,
    31. "chunks in the LSM tree" : 0,
    32. "highest merge generation in the LSM tree" : 0,
    33. "queries that could have benefited from a Bloom filter that did not exist" : 0,
    34. "sleep for LSM checkpoint throttle" : 0,
    35. "sleep for LSM merge throttle" : 0,
    36. "total size of bloom filters" : 0
    37. },
    38. "block-manager" : {
    39. "allocations requiring file extension" : 15471,
    40. "blocks allocated" : 15475,
    41. "blocks freed" : 39,
    42. "checkpoint size" : 188481536,
    43. "file allocation unit size" : 4096,
    44. "file bytes available for reuse" : 188416,
    45. "file magic number" : 120897,
    46. "file major version number" : 1,
    47. "file size in bytes" : 188686336,
    48. "minor version number" : 0
    49. },
    50. "btree" : {
    51. "btree checkpoint generation" : 20,
    52. "column-store fixed-size leaf pages" : 0,
    53. "column-store internal pages" : 0,
    54. "column-store variable-size RLE encoded values" : 0,
    55. "column-store variable-size deleted values" : 0,
    56. "column-store variable-size leaf pages" : 0,
    57. "fixed-record size" : 0,
    58. "maximum internal page key size" : 368,
    59. "maximum internal page size" : 4096,
    60. "maximum leaf page key size" : 2867,
    61. "maximum leaf page size" : 32768,
    62. "maximum leaf page value size" : 67108864,
    63. "maximum tree depth" : 4,
    64. "number of key/value pairs" : 0,
    65. "overflow pages" : 0,
    66. "pages rewritten by compaction" : 0,
    67. "row-store internal pages" : 0,
    68. "row-store leaf pages" : 0
    69. },
    70. "cache" : {
    71. "bytes currently in the cache" : 502018875,
    72. "bytes read into cache" : 0,
    73. "bytes written from cache" : 437640755,
    74. "checkpoint blocked page eviction" : 0,
    75. "data source pages selected for eviction unable to be evicted" : 12,
    76. "hazard pointer blocked page eviction" : 0,
    77. "in-memory page passed criteria to be split" : 130,
    78. "in-memory page splits" : 62,
    79. "internal pages evicted" : 0,
    80. "internal pages split during eviction" : 1,
    81. "leaf pages split during eviction" : 56,
    82. "modified pages evicted" : 56,
    83. "overflow pages read into cache" : 0,
    84. "overflow values cached in memory" : 0,
    85. "page split during eviction deepened the tree" : 1,
    86. "page written requiring lookaside records" : 0,
    87. "pages read into cache" : 0,
    88. "pages read into cache requiring lookaside entries" : 0,
    89. "pages requested from the cache" : 2232017,
    90. "pages written from cache" : 15472,
    91. "pages written requiring in-memory restoration" : 0,
    92. "tracked dirty bytes in the cache" : 0,
    93. "unmodified pages evicted" : 0
    94. },
    95. "cache_walk" : {
    96. "Average difference between current eviction generation when the page was last considered" : 0,
    97. "Average on-disk page image size seen" : 0,
    98. "Clean pages currently in cache" : 0,
    99. "Current eviction generation" : 0,
    100. "Dirty pages currently in cache" : 0,
    101. "Entries in the root page" : 0,
    102. "Internal pages currently in cache" : 0,
    103. "Leaf pages currently in cache" : 0,
    104. "Maximum difference between current eviction generation when the page was last considered" : 0,
    105. "Maximum page size seen" : 0,
    106. "Minimum on-disk page image size seen" : 0,
    107. "On-disk page image sizes smaller than a single allocation unit" : 0,
    108. "Pages created in memory and never written" : 0,
    109. "Pages currently queued for eviction" : 0,
    110. "Pages that could not be queued for eviction" : 0,
    111. "Refs skipped during cache traversal" : 0,
    112. "Size of the root page" : 0,
    113. "Total number of pages currently in cache" : 0
    114. },
    115. "compression" : {
    116. "compressed pages read" : 0,
    117. "compressed pages written" : 15312,
    118. "page written failed to compress" : 0,
    119. "page written was too small to compress" : 158,
    120. "raw compression call failed, additional data available" : 0,
    121. "raw compression call failed, no additional data available" : 0,
    122. "raw compression call succeeded" : 0
    123. },
    124. "cursor" : {
    125. "bulk-loaded cursor-insert calls" : 0,
    126. "create calls" : 3,
    127. "cursor-insert key and value bytes inserted" : 429166606,
    128. "cursor-remove key bytes removed" : 0,
    129. "cursor-update value bytes updated" : 0,
    130. "insert calls" : 1835000,
    131. "next calls" : 162051,
    132. "prev calls" : 1,
    133. "remove calls" : 0,
    134. "reset calls" : 30748,
    135. "restarted searches" : 0,
    136. "search calls" : 0,
    137. "search near calls" : 1227,
    138. "truncate calls" : 0,
    139. "update calls" : 0
    140. },
    141. "reconciliation" : {
    142. "dictionary matches" : 0,
    143. "fast-path pages deleted" : 0,
    144. "internal page key bytes discarded using suffix compression" : 31112,
    145. "internal page multi-block writes" : 4,
    146. "internal-page overflow keys" : 0,
    147. "leaf page key bytes discarded using prefix compression" : 0,
    148. "leaf page multi-block writes" : 66,
    149. "leaf-page overflow keys" : 0,
    150. "maximum blocks required for a page" : 242,
    151. "overflow values written" : 0,
    152. "page checksum matches" : 209,
    153. "page reconciliation calls" : 171,
    154. "page reconciliation calls for eviction" : 57,
    155. "pages deleted" : 1
    156. },
    157. "session" : {
    158. "object compaction" : 0,
    159. "open cursor count" : 3
    160. },
    161. "transaction" : {
    162. "update conflicts" : 0
    163. }
    164. },
    165. "nindexes" : 1,
    166. "totalIndexSize" : 18272256,
    167. "indexSizes" : {
    168. "_id_" : 18272256
    169. },
    170. "ok" : 1
    171. }

  16. </>复制代码

    1. // 执行
    2. > db.randomInfo.getIndexes()
    3. [
    4. {
    5. "v" : 2,
    6. "key" : {
    7. "_id" : 1
    8. },
    9. "name" : "_id_",
    10. "ns" : "company.randomInfo"
    11. }
    12. ]
    13. // 这是默认的索引,我们一般不会使用这个索引的
  17. 建立一个索引

  18. </>复制代码

    1. > db.randomInfo.ensureIndex({username: 1})
    2. {
    3. "createdCollectionAutomatically" : false,
    4. "numIndexesBefore" : 1,
    5. "numIndexesAfter" : 2,
    6. "ok" : 1
    7. }
    8. > db.randomInfo.getIndexes() // 然后查看发现有两条索引了
    9. [
    10. {
    11. "v" : 2,
    12. "key" : {
    13. "_id" : 1
    14. },
    15. "name" : "_id_",
    16. "ns" : "company.randomInfo"
    17. },
    18. {
    19. "v" : 2,
    20. "key" : {
    21. "username" : 1
    22. },
    23. "name" : "username_1",
    24. "ns" : "company.randomInfo"
    25. }
    26. ]
    27. >
  19. </>复制代码

    1. //test1.js
    2. var startTime = new Date().getTime() //得到程序运行的开始时间
    3. var db = connect("company") //链接数据库
    4. var rs=db.randomInfo.find({username:"tfruhjy8k"}) //根据用户名查找用户
    5. rs.forEach(rs=>{printjson(rs)}) //循环输出
    6. var runTime = new Date().getTime()-startTime; //得到程序运行时间
    7. print("[SUCCESS]This run time is:"+runTime+"ms") //打印出运行时间
  20. </>复制代码

    1. // 执行查找
    2. > load("./test1.js")
    3. connecting to: mongodb://127.0.0.1:27017/company
    4. MongoDB server version: 3.4.10
    5. {
    6. "_id" : ObjectId("5ac8b73b5646d96c6db3e1a8"),
    7. "username" : "od2umr6kec",
    8. "regeditTime" : ISODate("2018-04-07T12:18:44.292Z"),
    9. "randNum0" : 577322,
    10. "randNum1" : 961443,
    11. "randNum2" : 999621,
    12. "randNum3" : 968291,
    13. "randNum4" : 834839,
    14. "randNum5" : 637084,
    15. "randNum6" : 172311,
    16. "randNum7" : 219693,
    17. "randNum8" : 617081
    18. }
    19. [SUCCESS]This run time is:11ms // 关键看这里,你会发现时间缩短了好多呢
    20. true
    21. >
  21. 无论是在关系型数据库还是文档数据库,建立索引都是非常重要的。前边讲了,索引这东西是要消耗硬盘和内存资源的,所以还是要根据程序需要进行建立了。MongoDB也给我们进行了限制,只允许我们建立64个索引值。

  22. </>复制代码

    1. 复合索引
  23. 复合索引就是两条以上的索引

  24. </>复制代码

    1. // 在建立一个索引
    2. > db.randomInfo.ensureIndex({randNum0: 1});
    3. {
    4. "createdCollectionAutomatically" : false,
    5. "numIndexesBefore" : 2,
    6. "numIndexesAfter" : 3,
    7. "ok" : 1
    8. }
  25. </>复制代码

    1. > db.randomInfo.getIndexes();
    2. [
    3. {
    4. "v" : 2,
    5. "key" : {
    6. "_id" : 1
    7. },
    8. "name" : "_id_",
    9. "ns" : "company.randomInfo"
    10. },
    11. {
    12. "v" : 2,
    13. "key" : {
    14. "username" : 1
    15. },
    16. "name" : "username_1",
    17. "ns" : "company.randomInfo"
    18. },
    19. {
    20. "v" : 2,
    21. "key" : {
    22. "randNum0" : 1
    23. },
    24. "name" : "randNum0_1",
    25. "ns" : "company.randomInfo"
    26. }
    27. ]
    28. >
  26. 我们同时查询两个索引的值,看看效果是怎么样的。

  27. </>复制代码

    1. //
    2. var startTime=new Date().getTime();
    3. var db = connect("company");
    4. var rs= db.randomInfo.find({username:"7xwb8y3",randNum0:565509});
    5. rs.forEach(rs=>{printjson(rs)});
    6. var runTime = new Date().getTime()-startTime;
    7. print("[Demo]this run time is "+runTime+"ms");
    8. // 从性能上看并没有什么特殊的变化,查询时间还是在10ms左右。MongoDB的复合查询是按照我们的索引顺序进行查询的。就是我们用db.randomInfo.getIndexes()查询出的数组。
  28. 指定索引查找

  29. </>复制代码

    1. //
    2. var rs= db.randomInfo.find({username:"7xwb8y3",randNum0:565509}).hint({randNum0:1});
  30. 删除索引

  31. </>复制代码

    1. db.randomInfo.dropIndex("randNum0_1");//索引的唯一ID
  32. 这里需要注意的是删除时填写的值,并不是我们的字段名称(key),而是我们索引查询表中的name值。这是一个小坑。

  33. </>复制代码

    1. 全文索引
  34. 有些时候需要在大篇幅的文章中搜索关键词,比如我写的文章每篇都在万字以上,这时候你想搜索关键字是非常不容易的,MongoDB为我们提供了全文索引。

  35. </>复制代码

    1. // 插入两条数据
    2. db.info.insert({contextInfo:"I am a programmer, I love life, love family. Every day after work, I write a diary."})
    3. db.info.insert({contextInfo:"I am a programmer, I love PlayGame, love drink. Every day after work, I playGame and drink."})
  36. 建立全文索引

  37. </>复制代码

    1. db.info.ensureIndex({contextInfo:"text"});
    2. //需要注意的是这里使用text关键词来代表全文索引,我们在这里就不建立数据模型了。
  38. 全文索引查找

  39. </>复制代码

    1. // $text:表示要在全文索引中查东西。这里的$test指的就是contextInfo
    2. // $search:后边跟查找的内容。
    3. db.info.find({$text:{$search:"programmer"}}); // 查找contextInfo中含有programmer关键字的
  40. 查找多个词

  41. </>复制代码

    1. // 比如我们希望查找数据中有programmer,family,diary,drink的数据(这是或的关系),所以两条数据都会出现。
    2. db.info.find({$text:{$search:"programmer family diary drink"}})
    3. // 如果我们这时候希望不查找出来有drink这个单词的记录,我们可以使用“-”减号来取消。
    4. db.info.find({$text:{$search:"programmer family diary -drink"}})
    5. // 全文搜索中是支持转义符的,比如我们想搜索的是两个词(love PlayGame和drink),这时候需要使用斜杠来转意。
    6. db.info.find({$text:{$search:""love PlayGame" drink"}})
  42. </>复制代码

    1. 全文索引在工作还是经常使用的,比如博客文章的搜索,长文件的关键词搜索,这些都需要使用全文索引来进行。

  43. </>复制代码

    1. 到这里Mongodb的基本知识就基本结束了,下一节我们将会学习如何管理Mongodb
  44. 参考文献

  45. 技术胖

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/19240.html

相关文章

  • MongoDB高级_管理:用户的创建、删除与修改

    摘要:安装好时,它为我们默认开了一个最高管理权限方便我们管理数据库,我们可以用链接数据库,就是这个原理。这节课我们就学习一下的用户管理。超级账号,超级权限查找用户信息删除用户建权如果正确返回,如果错误返回。。 安装好MongoDB时,它为我们默认开了一个最高管理权限方便我们管理数据库,我们可以用mongo链接数据库,就是这个原理。但在实际开发中并一般不能使用这个用户,因为大家都知道和最高权限...

    linkFly 评论0 收藏0
  • MongoDB指南---13、索引类型、索引管理

    摘要:复合唯一索引也可以创建复合的唯一索引。中的稀疏索引与关系型数据库中的稀疏索引是完全不同的概念。但是这里不会指明索引是否是多键索引。上一篇文章指南使用和何时不应该使用索引下一篇文章指南特殊的索引和集合固定集合索引全文本索引 上一篇文章:MongoDB指南---12、使用explain()和hint()、何时不应该使用索引下一篇文章:MongoDB指南---14、特殊的索引和集合:固定集合...

    Enlightenment 评论0 收藏0
  • MongoDB指南---13、索引类型、索引管理

    摘要:复合唯一索引也可以创建复合的唯一索引。中的稀疏索引与关系型数据库中的稀疏索引是完全不同的概念。但是这里不会指明索引是否是多键索引。上一篇文章指南使用和何时不应该使用索引下一篇文章指南特殊的索引和集合固定集合索引全文本索引 上一篇文章:MongoDB指南---12、使用explain()和hint()、何时不应该使用索引下一篇文章:MongoDB指南---14、特殊的索引和集合:固定集合...

    seanHai 评论0 收藏0
  • SpringBoot高级MongoDB之修改基本使用姿势

    摘要:原文高级篇之修改基本使用姿势本篇依然是中的一篇,主要介绍的更新,主要内容如下常见类型成员的修改数组类型成员的增删改类型成员的增删改基本使用首先是准备好基本环境,可以参考博文高级篇之基本环境搭建与使用高级篇之查询基本使用姿势在开 原文: 190218-SpringBoot高级篇MongoDB之修改基本使用姿势 本篇依然是MongoDB curd中的一篇,主要介绍document的更新,...

    lauren_liuling 评论0 收藏0
  • UCloud MongoDB 如何应对高考填志愿的上亿流量高峰

    摘要:优志愿张海鹏宋体背景宋体每年月下旬到月下旬期间是高考填志愿的高峰期,也是优志愿后端面临大流量高并发请求的业务高峰期。对于优志愿读多写少的场景及其业务高峰期,用户可以按需增删节点,更好地实现读取性能的扩展。 随着用户规模的增长,数据库的压力也在成倍增加。面对大流量、高并发,UCloud MongoDB 做到了高效,并展现出了更好的性能体验。 —— 优志愿 CTO 张海鹏 背景...

    cppprimer 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<