玩转MongoDB: 索引,速度的引领

2020-05-28 00:00:00 索引 查询 字段 文档 指定


数据库索引与书籍的索引类似,有了索引就不需要翻整本书,数据库可以直接在索引中查找,在索引中找到条目后,就可以直接跳到目标文档的位置,这可以让查找的速度提高几个数量级。

一、创建索引

        我们在person这个集合的age键上创建一个索引,比较一下创建索引前后,一个查询的语句的性能区别。

        创建索引:db.person.ensureIndex({"age":1})。这里我们使用了ensureIndex在age上建立了索引。“1”:表示按照age进行升序,“-1”:表示按照age进行降序。

        没有索引的查询性能:

        有索引的查询性能:

        我们主要来看这几个参数,(参数说明,请看上一篇文章

        executionTimeMillis(这次query整体的耗时):无索引耗时962毫秒 ;有索引耗时143毫秒。

        totalDocsExamined(文档扫描条目):无索引是200万条;有索引是2000条。

        stage(查询的类型):无索引是COLLSCAN(全表扫描);有索引是FETCH+IXSCAN(索引扫描+根据索引去检索指定document)。

        executionStages.executionTimeMillisEstimate(检索document获得数据的耗时):无索引耗时910毫秒;有索引耗时毫秒。

        建好索引后,这个query整体的速度提高了1个数量级 (1个数量级是10倍的意思)。根据查询语句的不同,索引可以使速度提高几个数量级。


二、复合索引 

        在多个键上建立的索引就是复合索引,有时候我们的查询不是单条件的,可能是多条件,比如查找年龄在20~30名字叫‘ryan1’的同学,那么我们可以建立“age”和“name”的联合索引来加速查询。

        为了演示索引的效果,我们来重新生成插入一份200万个文档的集合。

//删除原来的集合
db.person.drop();
//插入200万条数据
for(var i=;i<2000000;i++){
    db.person.insert({"name":"ryan"+i%1000,"age":20+i%10});
}
//创建三个索引
db.person.ensureIndex({"age":1})
db.person.ensureIndex({"name":1,"age":1})
db.person.ensureIndex({"age":1,"name":1})

        我们可以用hint()方法来强制查询走哪个索引。

        我们来看一下,当查询条件是多个的时候,复合索引相比单键索引的强大魅力。

        使用单键索引

db.person.find({"age":{"$gte":20,"$lte":30},"name":"ryan1"})
.hint({"age":1}).explain("executionStats");

        结果如下:

{
   ...
   "executionStats" : {
       "executionSuccess" : true,
       "nReturned" : 2000,
       "executionTimeMillis" : 2031,
       "totalKeysExamined" : 2000000,
       "totalDocsExamined" : 2000000,
   ...    
}

        使用复合索引

db.person.find({"age":{"$gte":20,"$lte":30},"name":"ryan1"})
.hint({"age":1,"name":1}).explain("executionStats");

        结果如下:

{
   ...
   "executionStats" : {
       "executionSuccess" : true,
       "nReturned" : 2000,
       "executionTimeMillis" : 8,
       "totalKeysExamined" : 2010,
       "totalDocsExamined" : 2000,
   ...
}

        从executionTimeMillis的值上,一眼就可以看出却别。单间索引耗费了2031毫秒,复合索引用了8毫秒。 由此我们可以看出,根据查询语句的不同,建立正确的索引是非常重要的,对于查询语句中是多条件的,应多考虑复合索引的应用。

        下面,我们再说一种复合索引的重要应用情况。有对一个键排序并只要前100个结果的情景(实际项目中经常都是这种情景)。对于这种情况,索引应该这样建{"sortKey":1,"queryCriteria":1},排序的键应该放在复合索引的位。

        排序键没有放在复合索引的位:

db.person.find({"age":{"$gte":21.0,"$lte":30.0}})
.sort({"name":1}).limit(100)
.hint({"age":1,"name":1}).explain("executionStats");

        结果如下:

{
   ...
       "executionStats" : {
       "executionSuccess" : true,
       "nReturned" : 100,
       "executionTimeMillis" : 6882,
       "totalKeysExamined" : 1800000,
       "totalDocsExamined" : 1800000,
   ...  
}

        排序键放在复合索引的位:

db.person.find({"age":{"$gte":21.0,"$lte":30.0}})
.sort({"name":1}).limit(100)
.hint({"name":1,"age":1}).explain("executionStats");

        结果如下:

{
   ...
   "executionStats" : {
       "executionSuccess" : true,
       "nReturned" : 100,
       "executionTimeMillis" : 3,
       "totalKeysExamined" : 2100,
       "totalDocsExamined" : 2100,
   ...
}

        从上面的结果,我们很容易看出,基于排序键的索引,效果非常好。

        分析:种索引,需要找到所有复合查询条件的值(依据索引,键和文档可以快速找到),但是找到后,需要对文档在内存中进行排序,这个步骤消耗了非常多的时间。第二种索引,效果非常好,因为不需要在内存中对大量数据进行排序。但是,MongoDB不得不扫描整个索引以便找到所有文档。因此,如果对查询结果的范围做了限制,那么MongoDB在几次匹配之后就可以不再扫描索引,在这种情况下,将排序键放在位是一个非常好的策略。 


三、索引

        索引可以确保集合的每个文档的指定键都有值。如果想保证不同文档的“name”键拥有不同的值,在“name”键上创建一个索引就可以了。

db.person.ensureIndex({"name":1},{"unique":true});

        然后用db.person.getIndexes()命令,查看目前person集合所有的索引。

        也可以创建复合的索引。创建复合索引时,单个键的值可以相同,但所有键的组合值必须是的。 

db.person.ensureIndex({"name":1,"age":1},{"unique":true});

        然后用db.person.getIndexes()命令,查看目前person集合所有的索引。


四、稀疏索引

        索引会把null看作值,所以无法将多个缺少索引中的键的文档插入到集合中。然而,在有些情况下,你可能希望索引只对包含相应键的文档生效。这个时候我们可以用到MongoDB中的稀疏索引。该索引与关系型数据库中的稀疏索引是完全不同的概念。MongoDB中的稀疏索引只是不需要将每个文档都作为索引条目。

        比如,如果有一个可选的mobilephone字段,但是,如果提供了这个字段,那么它的值必须是的:

db.person.ensureIndex({"mobilephone":1}{"unique":true,"sparse":true});

        稀疏索引不必是的。只要去掉unique选项,就可以创建一个非的稀疏索引。


五、索引管理

        如小节所述,可以使用ensureIndex方法创建新的索引,也可以使用createIndex方法。

        创建一个索引之后,可以利用getIndexes()方法来查看给定集合上的所有索引的信息。

db.person.getIndexes();//获取集合的索引信息

        结果如下:

[
   {
       "v" : 1,
       "key" : {
           "_id" : 1
       },
       "name" : "_id_",
       "ns" : "personmap.person"
   },
   {
       "v" : 1,
       "unique" : true,
       "key" : {
           "name" : 1.0
       },
       "name" : "name_1",
       "ns" : "personmap.person"
   },
   {
       "v" : 1,
       "unique" : true,
       "key" : {
           "name" : 1.0,
           "age" : 1.0
       },
       "name" : "name_1_age_1",
       "ns" : "personmap.person"
   },
   {
       "v" : 1,
       "unique" : true,
       "key" : {
           "mobilephone" : 1.0
       },
       "name" : "mobilephone_1",
       "ns" : "personmap.person",
       "sparse" : true
   }
]

       

随着业务的不断变化,你可能会发现数据或者查询已经发生了改变,原来的索引也不那么好用了。这时可以使用dropIndex()方法删除不需要的索引:

db.person.dropIndex("name_1");//删除索引名为name_1的索引。




接下来,将要给大家介绍mongoDB中一些常用的特殊索引类型,主要包括:

  • 用于简单字符串搜索的全文本索引;

  • 用于球体空间(2dsphere)的地理空间索引

  • 用于二维平面(2d)的地理空间索引。 

一、全文索引

        mongoDB有一个特殊的索引用在文档中搜索文本,之前的博客都是用匹配来查询字符串,这些技术有一定的限制。在搜索大块文本的速度非常慢,而且无法处理自然语言礼节的问题。全文本索引使用的是“倒排索引”的思想来做的,和当前非常开源的lucene(全文检索,Apacle基金会下的开源项目)项目是一样的思想来做的。使用全文本索引可以非常快的进行文本搜索,mongoDB支持多种语言,可惜在免费版中,并不支持世界的火星文语言(汉语)。查mongoDB的官网可以看到,在企业版中是支持汉语的全文索引的。

        如果公司用的是免费版的mongoDB,而又需要用到中文的全文索引,建议使用lucene或者solr等开源项目来做。(没钱就得用技术来补,赤裸裸的现实。)

        使用全文本检索需要专门开启这个功能才能进行使用。启动mongoDB时指定--setParameter textSearchEnabled=true选项,或者在运行时执行setParameter命令,都可以启用全文本索引。

db.adminCommand({"setParameter":1,"textSearchEnabled":true});

        准备10条数据:

db.news.insert({"title":"SEOUL","context":"SEOUL, June 10 (Reuters) - South Korean prosecutors raided the offices of Lotte Group, the country's fifth-largest conglomerate, and several affiliates on Friday, dealing a further blow to its hotel unit's planned IPO, billed as the world's biggest this year."});
db.news.insert({"title":"Many Chinese people","context":"Many Chinese people think that a job on a diplomatic team is too good to quit. So when 28-year-old Liu Xiaoxi left her embassy post as an attache late last year to start a career in photography, she quickly became a popular topic among the Chinese online community."});
db.news.insert({"title":"About","context":"About 200 investigators searched 17 locations including group headquarters in central Seoul and the homes of Chairman Shin Dong-bin and other key executives, local news agency Yonhap reported, citing the Seoul Central Prosecutor's office."});
db.news.insert({"title":"Three people","context":"Three people with direct knowledge of the matter told Reuters that Friday's raids were part of an investigation into a possible slush fund. They also declined to be identified."});
db.news.insert({"title":"A Lotte Group spokesman","context":"A Lotte Group spokesman on Friday declined to comment on the reason for the raid, when asked whether it concerned a possible slush fund. He noted, however, that the situation was difficult given the IPO plans and Lotte Chemical's Axiall bid."});
db.news.insert({"title":"According","context":"According to bourse rules, the deadline for Hotel Lotte to list is July 27, six months from the preliminary approval for the IPO. If it needed to refile its prospectus to warn investors about risks from Friday's probe, which appeared likely, it would probably not be able to meet that deadline, an exchange official told Reuters on Friday."});
db.news.insert({"title":"Friday","context":"On Friday, dozens of Chinese tourists queued as usual to access elevators to the flagship Lotte Duty Free outlet in the group's headquarters complex, as TV cameras waited for investigators to emerge from office doors around the corner."});
db.news.insert({"title":"Named","context":"Named after the heroine of an 18th century Goethe novel, Lotte has grown from its founding in Japan 68 years ago as a maker of chewing gum to a corporate giant with interests ranging from hotels and retail to food and chemicals. The group has annual revenue of around $60 billion in Korea."});
db.news.insert({"title":"Hotel Lotte's","context":"Hotel Lotte's planned flotation of around 35 percent of its shares was intended to bring transparency and improve corporate governance at a group whose ownership structure is convoluted even by the opaque standards of South Korea's conglomerates."});
db.news.insert({"title":"Shares","context":"Shares in Lotte Shopping (023530.KS) , whose units Lotte Department Store and Lotte Home Shopping were raided, fell 1.6 percent on Friday. Lotte Himart (071840.KS) , a consumer electronics retailer, dropped 2.1 percent."});

        一个集合上多只能有一个全文本索引,但是全文本索引可以包含多个字段。全文索引与“普通”的多键索引不同,全文本索引中的字段顺序不重要:每个字段都被同等对待,可以为每个字段指定不同的权重来控制不同字段的相对重要性。

        我们来给title和context字段建立全文本索引,给title字段2的权重,context字段1的权重。(权重的范围可以是1~1,000,000,000,默认权重是1)。

db.news.ensureIndex({"title":"text","context":"text"}
,{"weights":{"title":2,"context":1}})

        我们利用这个全文本索引来搜索一下。搜索的内容是“flotation”。

db.news.find({$text:{$search:"flotation"}})

        结果如下图所示:


二、2dsphere索引

        2dsphere索引是mongoDB常用的地理空间索引之一,用于地球表面类型的地图。允许使用GeoJSON格式(http://www.geojson.org)指定点、线、多边形。

        点可以用形如[longitude,latitude]([经度,纬度])的两个元素的数组表示("loc"字段的名字可以是任意的,但是其中的子对象是有GeoJSON指定的,不能改变):

{
   "name":"beijing",
   "loc":{
       "type":"Point",
       "coordinates":[40,2]
   }  
}

        线可以用一个由点组成的数组来表示:

{
   "name":"changjiang",
   "loc":{
       "type":"Line",
       "coordinates":[[1,2],[2,3],[3,4]]
   }  
}

        多边形的表示方式与线一样,但是“type”不同:

{
   "name":"shenzhen",
   "loc":{
       "type":"Polygon",
       "coordinates":[[1,2],[2,3],[3,4]]
   }  
}

        创建2dsphere索引: 

db.mapinfo.ensureIndex({"loc":"2dsphere"})

        地理空间查询的类型有三种:交集(intersection)、包含(within)、接近(nearness)。查询时,需要将希望查找的内容指定为形如{"$geometry":geoJsonDesc}的GeoJSON对象。

        使用“$geoIntersects”查询位置相交的文档:

var customMapinfo = {
   "type":"Polygon",
   "coordinates":[[12.2223,39,4424],[13.2223,38,4424],[13.2223,39,4424]]
}
db.mapinfo.find({
   "loc":{"$geoIntersects":{"$geometry":customMapinfo}}
})

        这样就会找到所有与customMapinfo区域有交集的文档。

        使用“$within”查询完全包含在某个区域的文档:

db.mapinfo.find({
   "loc":{"$within":{"$geometry":customMapinfo}}
})

        使用“$near”查询附近的位置:

db.mapinfo.find({
   "loc":{"$near":{"$geometry":customMapinfo}}
})


三、2d索引

        2d索引也是mongoDB常用的地理空间索引之一,用于游戏地图。2d索引用于扁平表面,而不是球体表面。如果用在球体表面上,在极点附近会出现大量的扭曲变形。

        文档中应该使用包含两个元素的数组表示2d索引字段。

{
   "name":"node1",
   "tile":[32,22]
}

        创建索引:

db.gameMapinfo.ensureIndex({"tile":"2d"})

        使用$near查询点[20,20]附近的文档:

db.gameMapinfo.find({"tile":{"$near":[20,20]}})

        使用$within查询出某个形状(矩形、圆形或者多边形)范围内的所有文档。

        矩形,可以指定$box选项($box接受一个两元素的数组,个元素指定左下角的坐标,第二个元素指定右上角的坐标):

db.gameMapinfo.find({"tile":{"$within":{"$box":[[10,20],[15,30]]}}})

        圆形,可以指定$center选项($center接受一个两元素数组作为参数,个元素是一个点,用于指定圆心,第二个元素用于指定半径):

db.gameMapinfo.find({"tile":{"$within":{"$center":[[12,12],5]}}})

        多边形,可以指定$polygon($ploygon接受一个多元素的数组,每个元素对应多边形的点),下面以一个三角形为例:

db.gameMapinfo.find({"tile":{"$within":{"$polygon":[[0,20],[10,0],[-10,0]]}}})




END


作者:周钦雄,热衷分享,拥抱开源的程序员。本文经授权转载自微信公众号:精修Java。





相关文章