1

I have the following query

query = query & Builders<Profile>.Filter.And(query, 
Builders<Profile>.Filter.Regex(p => p.email, '^' + search));

But i know that MongoDb can't use indexes with regex queries. Is it possible to implement an alternative that will work using indexes ? Also, i have many regexes that could be implemented, for ex. search by string's start and string's end, string contains and other.

I use MongoDb v 3.0.2 & Official c# driver v 2.0

Vladyslav Furdak
  • 1,765
  • 2
  • 22
  • 46

1 Answers1

1

Please refer to MongoDB documentation that describes how indexes work with regular expression queries. The gist of it is that the indexes will be efficiently used only in case your regex is a "prefix" expression, meaning that the strings matched will always start with the same substring.

So searching "by string's start" (as in your code sample) will use indexes in an efficient way. Searching with a regex "by string's end" or "contains" can only use indexes for index scans and not for index seeks. Index scans can be only marginally faster than table scans, and mainly due to the fact that the relevant indexes may already be loaded into memory and don't have to be read from disk.

EDIT: Since you're asking about alternatives - if you really do require efficient full-text search on your data, you can look into dedicated text search engines such as Lucene and Solr. It will take much greater effort to incorporate them into your solution, but your full-text queries are going to be super-fast.

Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67