【问题标题】:Mongo regex index matching - multiple start stringsMongodb 正则表达式索引匹配 - 多个起始字符串
【发布时间】:2013-11-04 14:45:16
【问题描述】:

我想在 mongo 中匹配多个起始字符串。 explain() 表明它正在为此查询使用 indexedfield 索引:

db.mycol.find({indexedfield:/^startstring/,nonindexedfield:/somesubstring/});

但是,下面对多个起始字符串的查询确实很慢。当我运行解释时,我得到一个错误。从我在 mongostat(每秒 7k)中看到的错误来看,它正在扫描整个集合。它还每隔几秒在 0% 锁定和 90-95% 锁定之间交替。

db.mycol.find({indexedfield:/^(startstring1|startstring2)/,nonindexedfield:/somesubstring/}).explain();

JavaScript execution failed: error: { "$err" : "assertion src/mongo/db/key.cpp:421" } at src/mongo/shell/query.js:L128

任何人都可以阐明我如何做到这一点或导致解释错误的原因吗?

更新 - 更多信息

好的,所以我设法通过限制结果的数量来解释更复杂的查询。区别在于:

对于单个子字符串,“^/BA1/”(是的,它是邮政编码)

"cursor" : "BtreeCursor pc_1 multi",
"isMultiKey" : false,
"n" : 10,
"nscannedObjects" : 10,
"nscanned" : 10,
"nscannedObjectsAllPlans" : 19,
"nscannedAllPlans" : 19,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"indexBounds" : {
    "indexedfield" : [
        [
            "BA1",
            "BA2"
        ],
        [
            /^BA1/,
            /^BA1/
        ]
    ]
}

对于多个子字符串“^(BA1|BA2)/”

"cursor" : "BtreeCursor pc_1 multi",
"isMultiKey" : false,
"n" : 10,
"nscannedObjects" : 10,
"nscanned" : 1075276,
"nscannedObjectsAllPlans" : 1075285,
"nscannedAllPlans" : 2150551,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 5,
"nChunkSkips" : 0,
"millis" : 4596,
"indexBounds" : {
    "indexedfield" : [
        [
            "",
            {

            }
        ],
        [
            /^(BA1|BA2)/,
            /^(BA1|BA2)/
        ]
    ]
}

看起来不太好。

【问题讨论】:

  • 也许你应该试试 $or 运算符?
  • 或者工作得很好,干杯!
  • 太好了,很高兴它有帮助。

标签: regex mongodb indexing


【解决方案1】:

$or 解决了使用索引的问题(感谢 EddieJamsession)。查询现在正在快速减少。

db.mycoll.find({$or: [{indexedfield:/^startstring1/},{indexedfield:/^startstring2/],nonindexedfield:/somesubstring/})

但是,如果可能的话,我仍然希望使用正则表达式来执行此操作,因此我将问题留待解决。尤其是因为我现在必须重构我的应用程序以考虑这些类型的查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多