Reputation: 4960
So I have some products in my mongodb which are listed below
Now the searches which I am getting comes in the small case and maybe sometimes with special characters or no special characters. So how can I build a query which can give the output accurately? For example, if a user has entered "quality sweet" then it should match "Quality-Sweet" in my mongodb. If the user has entered "HERLEYS SWEET" in uppecase then it should match "herleys sweet" (as shown above in my MongoDB)
db.product.find({"Product":re.compile('^' + re.escape(pr) + '$',re.IGNORECASE)})
I have the above query which works with upper or lower case but if the user is searching for something like "herleys-sweet" then it does not work.
Upvotes: 1
Views: 94
Reputation: 2121
One thing you can do is use the re.sub()
function to substitute special characters with something else.
You can have something like this:
db.product.find({"Product":re.compile('^' + re.sub('[<list of special characters>]', '<string to replace with>', pr) + '$',re.IGNORECASE)})
For example:
create the list of special characters: [\-\_\~\!\\\/\^\$\%]
choose what to substitute special characters with. Could be a space ' '
or anything .*
.
Then, you would have:
db.product.find({"Product":re.compile('^' + re.sub('[\-\_\~\!\\\/\^\$\%]', '.*', pr) + '$',re.IGNORECASE)})
Upvotes: 1