0

I have a Flask app that queries my self-managed MongoDB.

I've created an index on two fields so that I can perform a text search on it.

The search is working fine, but it is only matching full words.

For example, for the phrase "i am halfminded", if I perform a search with the keyword halfminded it works but doesn't work for half.

This is what i am using:

    def get_paginated_data(self, page, query):
    skip = (page - 1) * self.PER_PAGE
    data = (
        self.collection.find({"$text": {"$search": query}})
        .skip(skip)
        .limit(self.PER_PAGE)
    )
    return list(data)

I have tried using the below code as well:

def get_paginated_data(self, page, query):
    skip = (page - 1) * self.PER_PAGE
    data = (
        self.collection.find({"$text": {"$regex": f"/.*{query}/"}})
        .skip(skip)
        .limit(self.PER_PAGE)
    )
    return list(data)

but this throws the following error:

pymongo.errors.OperationFailure: Missing expected field "$search"

Can anyone advise on how i can get the partial text search to work.

3
  • 1
    Does this answer your question? How to find a substring in a field in Mongodb Commented Apr 12, 2024 at 16:42
  • Nope. The answer says to use $regex. That's what i did in my example above and i landed on an error because i am using indexes. Apparently if i use indexes i have to use the search keyword. Commented Apr 12, 2024 at 16:45
  • 2
    Why you must use $text and text index? You can simply use a normal index and do the regex search like this, if a substring search is what you are looking for Commented Apr 12, 2024 at 16:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.