MongoDB,通过索引字段上的正则表达式进行查询的性能 [英] MongoDB, performance of query by regular expression on indexed fields

查看:2404
本文介绍了MongoDB,通过索引字段上的正则表达式进行查询的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按姓名找到一个帐户(在一个包含50K帐户的MongoDB集合中)

以通常的方式: 我们找到字符串

db.accounts.find({ name: 'Jon Skeet' })  // indexes help improve performance!

正则表达式怎么样?这是一项昂贵的操作吗?

db.accounts.find( { name: /Jon Skeet/ }) // worry! how indexes work with regex?






编辑:


根据WiredPrairie:


MongoDB使用RegEx的前缀来查找索引(例如: / ^前缀。* / ):

According to WiredPrairie:
MongoDB use prefix of RegEx to lookup indexes (ex: /^prefix.*/):

db.accounts.find( { name: /^Jon Skeet/ })  // indexes will help!'

MongoDB $ regex

推荐答案

实际上根据文档,


如果字段存在索引,则MongoDB将常规
表达式与索引中的值,可以比
集合扫描更快。如果常规
表达式是前缀表达式,则可以进一步优化,这意味着所有潜在的
匹配以相同的字符串开头。这允许MongoDB从该前缀构造
范围,并且仅匹配该范围内的
索引中的那些值。

If an index exists for the field, then MongoDB matches the regular expression against the values in the index, which can be faster than a collection scan. Further optimization can occur if the regular expression is a "prefix expression", which means that all potential matches start with the same string. This allows MongoDB to construct a "range" from that prefix and only match against those values from the index that fall within that range.

http://docs.mongodb.org/manual / reference / operator / query / regex / #index-use

换句话说:

对于/ Jon Skeet / regex,mongo将完全扫描索引中的键,然后将获取匹配的文档,这可能比收集扫描更快。

For /Jon Skeet/ regex ,mongo will full scan the keys in the index then will fetch the matched documents, which can be faster than collection scan.

For / ^ Jon Skeet / regex,mongo将仅扫描索引中以正则表达式开头的范围,这将更快。

For /^Jon Skeet/ regex ,mongo will scan only the range that start with the regex in the index, which will be faster.

这篇关于MongoDB,通过索引字段上的正则表达式进行查询的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆