Skip to content

Commit 03f5432

Browse files
committed
use text prefix in regex to speed up query
for selector; {"selector":{"_id":{"$regex":"doc.+"}}} before; { "include_docs": true, "view_type": "map", "reduce": false, "partition": null, "start_key": [], "end_key": [ "<MAX>" ], "direction": "fwd", "stable": false, "update": true, "conflicts": "undefined" } after; { "include_docs": true, "view_type": "map", "reduce": false, "partition": null, "start_key": [ "doc" ], "end_key": [ "doc�", "<MAX>" ], "direction": "fwd", "stable": false, "update": true, "conflicts": "undefined" } closes: #4775
1 parent b6ea325 commit 03f5432

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

src/mango/src/mango_idx_view.erl

+12
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@
3535
-include("mango.hrl").
3636
-include("mango_idx_view.hrl").
3737

38+
-define(PREFIX_RE, "^\\w+").
39+
3840
validate_new(#idx{} = Idx, _Db) ->
3941
{ok, Def} = do_validate(Idx#idx.def),
4042
{ok, Idx#idx{def = Def}}.
@@ -310,6 +312,8 @@ indexable({[{<<"$gte">>, _}]}) ->
310312
% Making `$exists` indexable should not cause problems in other cases.
311313
indexable({[{<<"$exists">>, _}]}) ->
312314
true;
315+
indexable({[{<<"$regex">>, _}]}) ->
316+
true;
313317
% All other operators are currently not indexable.
314318
% This is also a subtle assertion that we don't
315319
% call indexable/1 on a field name.
@@ -485,6 +489,14 @@ range({[{<<"$gt">>, Arg}]}, LCmp, Low, HCmp, High) ->
485489
max ->
486490
empty
487491
end;
492+
% use any text prefix in the regex to narrow the query
493+
range({[{<<"$regex">>, Arg}]}, LCmp, Low, HCmp, High) ->
494+
case re:run(Arg, ?PREFIX_RE, [{capture, first, binary}]) of
495+
{match, [Prefix]} ->
496+
{'$gte', Prefix, '$lte', <<Prefix/binary, 16#10FFFF>>};
497+
nomatch ->
498+
{LCmp, Low, HCmp, High}
499+
end;
488500
% There's some other un-indexable restriction on the index
489501
% that will be applied as a post-filter. Ignore it and
490502
% carry on our merry way.

0 commit comments

Comments
 (0)