Mongodb查询对索引字段的部分字段搜索来说太慢了

问题描述 投票:2回答:1

我有跟随mongodb文件的800万份文件。

Customer
  {
   "lastName" : "LAST",
   "firstName" : "FIRST"
  }

我有以下索引

db.customer.createIndex( {lastName: 1, firstName: 1},{collation: { locale: "en_US", strength: 1}})

如果我基于lastName和firstName进行搜索,那么它的快速结果将在10毫秒内完成。

 db.customer.find({lastName:"LAST" ,firstName:"FIRST"}).collation({ locale: 'en_US', strength: 1 })

我试图找到所有文件“AS”作为姓氏中的字符。但它需要超过100秒才能返回响应。我尝试了以下选项,但都需要超过100秒。 mongoDB真的喜欢sql类似操作('%AS%')

1)

db.customer.find({lastName:{"$regex": "AS"} ,firstName:"FIRST"}).collation({ locale: 'en_US', strength: 1 })

2)

db.customer.find({lastName:{"$regex": "/AS/"} ,firstName:"FIRST"}).collation({ locale: 'en_US', strength: 1 })

3)

db.customer.find({lastName:{"$regex": "^/AS/"} ,firstName:"FIRST"}).collation({ locale: 'en_US', strength: 1 })
mongodb mongodb-query
1个回答
0
投票

尝试在正则表达式上使用前缀以允许MongoDB使用范围

db.customer.find({lastName:{"$regex": "/^AS/"} ,firstName:"FIRST"}).collation({ locale: 'en_US', strength: 1 })

如果正则表达式以插入符号(^)或左键(\ A)开头,后跟一串简单符号,则它是“前缀表达式”。例如,regex /^abc./将通过仅匹配以abc开头的索引中的值进行优化。另外,当/ ^ a /,/^a。/和/^a.$/匹配等效字符串时,它们具有不同的性能特征。如果存在适当的索引,则所有这些表达式都使用索引;但是,/^ a。/,和/^a.*$/比较慢。 / ^ a /可以在匹配前缀后停止扫描。

regex

© www.soinside.com 2019 - 2024. All rights reserved.