While I was trying to investigate performance issue with queries, I found that the source was this query. I am using Rails 4 with Mongoid gem.
Order.where("customer.email" => /\[email protected]\z/i)
where [email protected]
is just an example.
Customer is an embedded document in Order document and customer's email is indexed.
When I benchmarked performance using Benchmark.bmbm
where Order.where("customer.email" => /\[email protected]\z/i).count
was repeated 100
times, I got the following result.
user system total real
0.090000 0.010000 0.100000 ( 27.656723)
I thought perhaps \A
and \z
was causing the slowness, so I tried the following where it looks for emails that start with given argument: Order.where("customer.email" => /^test/i).count
And result wasn't much different.
user system total real
0.090000 0.010000 0.100000 ( 28.712883)
As the last resort, I tried just matching the entire string without regexp. This time, it made a huge difference: Order.where("customer.email" => "[email protected]").count
user system total real
0.080000 0.000000 0.080000 ( 0.122888)
When I looked at output of explain, it shows that using regexp scans all documents.
{
"cursor" => "BtreeCursor customer.email_1",
"isMultiKey" => false,
"n" => 781,
"nscannedObjects" => 781,
"nscanned" => 500000,
"nscannedObjectsAllPlans" => 781,
"nscannedAllPlans" => 500000,
"scanAndOrder" => false,
"indexOnly" => false,
"nYields" => 1397,
"nChunkSkips" => 0,
"millis" => 406,
"indexBounds" => {
"customer.email" => [
[0] [
[0] "",
[1] {}
],
[1] [
[0] /test/i,
[1] /test/i
]
]
}
}
While using entire string only scanned subset, which was what I expected.
{
"cursor" => "BtreeCursor customer.email_1",
"isMultiKey" => false,
"n" => 230,
"nscannedObjects" => 230,
"nscanned" => 230,
"nscannedObjectsAllPlans" => 230,
"nscannedAllPlans" => 230,
"scanAndOrder" => false,
"indexOnly" => false,
"nYields" => 1,
"nChunkSkips" => 0,
"millis" => 0,
"indexBounds" => {
"customer.email" => [
[0] [
[0] "[email protected]",
[1] "[email protected]"
]
]
}
}
Can someone please explain to me why using regexp in mongodb query causes it to scan all documents instead of index?
EDIT: Added indexBounds in the explain output, which was omitted in the original post.