gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:48:00 27 4
gpt4 key购买 nike

我有以下包含 8 亿个文档的 mongodb 文档。

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

我有以下索引

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

如果我根据姓氏和名字进行搜索,那么它会很快并在 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 使用范围

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

A regular expression is a “prefix expression” if it starts with a caret (^) or a left anchor (\A), followed by a string of simple symbols. For example, the regex /^abc./ will be optimized by matching only against the values from the index that start with abc. Additionally, while /^a/, /^a./, and /^a.$/ match equivalent strings, they have different performance characteristics. All of these expressions use an index if an appropriate index exists; however, /^a./, and /^a.*$/ are slower. /^a/ can stop scanning after matching the prefix.

regex

关于Mongodb 查询对于索引字段的部分字段搜索来说太慢了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47861510/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com