How do I make a Case Insensitive, Partial Text Search Engine that uses Regex with MongoDB and PHP?
one text
Solution:
Beware: Regex search on indexed column will affect the performance, as stated at $regex docs:
Case insensitive regular expression queries generally cannot use indexes effectively. The $regex implementation is not collation-aware and is unable to utilize case-insensitive indexes.
Your problem is that MongoDB use prefix (ex: /^acme/
) on $regex
to lookup index.
For case sensitive regular expression queries, if an index exists for the field, then MongoDB matches the regular expression against the values in the index, which can be faster than a collection scan. Further optimization can occur if the regular expression is a “prefix expression”, which means that all potential matches start with the same string. This allows MongoDB to construct a “range” from that prefix and only match against those values from the index that fall within that range.
So it needs to be changed like this:
$query=$collection->find(['movie' => new MongoDB\BSON\Regex('^'.$input, 'i')]);
I suggest you design your collection more carefully.
Related:
- https://stackoverflow.com/a/46228114/6118551
- https://scalegrid.io/blog/mongodb-regular-expressions-indexes-performance/