一个关于MongoDB string字段索引的问题

学习MongoDB的索引发现一个奇怪的问题,给一个string类型的field设置text索引,但是在查询的时候并没有使用索引。比如:

db.tomcat_access_logs.ensureIndex( { url : 'text' });

 

db.tomcat_access.logs.find( { url : '1' } ).explain();

db.tomcat_access_logs.find( { url : /1/ } ).explain();

 

{

    "cursor" : "BasicCursor",

    "isMultiKey" : false,

    "n" : 0,

    "nscannedObjects" : 100,

    "nscanned" : 100,

    "nscannedObjectsAllPlans" : 100,

    "nscannedAllPlans" : 100,

    "scanAndOrder" : false,

    "indexOnly" : false,

    "nYields" : 0,

    "nChunkSkips" : 0,

    "millis" : 0,

    ...

}

 

从explain()的结果可以发现,在查询的时候只用了BasicCursor,也就是说没有使用索引。

后发现只有当使用$text查询的时候才会用到text索引:

 

db.tomcat_access_logs.find( { $text : { $search : '1'} } ).explain();

 

{

    "cursor" : "TextCursor",

    "n" : 0,

    "nscannedObjects" : 0,

    "nscanned" : 0,

    "nscannedObjectsAllPlans" : 0,

    "nscannedAllPlans" : 0,

    "scanAndOrder" : false,

    "nYields" : 0,

    "nChunkSkips" : 0,

    "millis" : 0,

    ...

}

 

只不过这样的话,就没有办法针对某个特定field进行查询了,因为$text是对所有text索引的field进行的全文搜索。此时只需要做一般的索引即可:

 

db.tomcat_access_logs.ensureIndex( { url : 1 } );

 

db.tomcat_access.logs.find( { url : '1' } ).explain();

db.tomcat_access.logs.find( { url : /.*1.*/g } ).explain();

{

    "cursor" : "BtreeCursor url_1",

    "isMultiKey" : false,

    "n" : 0,

    "nscannedObjects" : 0,

    "nscanned" : 100,

    "nscannedObjectsAllPlans" : 0,

    "nscannedAllPlans" : 100,

    "scanAndOrder" : false,

    "indexOnly" : false,

    "nYields" : 0,

    "nChunkSkips" : 0,

    "millis" : 1,

    "indexBounds" : {

        "url" : [

            [

                "",

                {

                    

                }

            ],

            [

                /.*1.*/,

                /.*1.*/

            ]

        ]

    },

    ...

}

 

总结

 

1.使用db.collection.find( { url : '1'} )或者db.collection.find( { url : /.*a.*/} ),不会使用的text索引,而是一般索引。

 

 

2.建立了text索引后,只能对text索引包含的所有字段进行全文搜索,无法对某个字段进行搜索

3.一般索引和text索引可以同时建立,以满足不同查询需求

 

 

原文来自:segmentfault

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值