Search code examples
pythonmongodbsearchknuth-morris-pratt

what is the effecient way to search a phrase in mongodb


What is the best way to search a phrase that have words that dont all matches, for example:

description = "a cell phone that have an external memory"

and i want to search:

search = "a good phone"

is there any tips using mongodb, or do i use Knuth-Morris-Pratt string matching from python (which will kill the server)?


Solution

  • For a simple regular expression search of a mongo db field you can use find with the "$regex" query expression.

    In pymongo that would be db.your_collection.find({"description": {"$regex": "<insert regex here>"}}).

    This will get you started. As others have stated, MongoDB doesn't necessarily appreciate you beating it up like this. You may need to consider a more robust solution for big time searching.

    Please consider the performance implications of doing a regular expression search in your DB.

    Read the MongoDB reference here http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions.