Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pymongo how to use full text search

I am looking to implement full text search in my python application using pymongo. I have been looking at this question but for some reason I am unable to implement this in my project as I am getting an error no such cmd: text. Can anyone direct me on what I am doing wrong?

Here is my code:

db = client.test
collection = db.videos
def search_for_videos(self, search_text)
    self.db.command("text", "videos", 
            search=search_text, 
            limit=10)

The collection I am trying to search is called videos however I am not sure if I am putting this in the correct parameter, and I also am not sure if I need the line project={"name": 1, "_id": 0}.

The documentation here I believe is using the mongo shell to execute commands, however I wish to perform this action in my code.

I have looked at using the db.videos.find() function, but cannot seem to implement it correctly either.

How to I use PyMongo Full Text Search from my Python Code?

like image 912
Brian Hamill Avatar asked Jan 21 '18 19:01

Brian Hamill


1 Answers

First be sure that you have a text index created on the field as mentioned here or you can just do it with pymongo too :

collection.create_index([('your field', 'text')])

Using pymongo you can do this to search:

collection.find({"$text": {"$search": your search}})

your function should look like this:

def search_for_videos(search_text):
    collection.find({"$text": {"$search": search_text}}).limit(10)

I hope this helps you.

like image 164
user3375448 Avatar answered Oct 05 '22 23:10

user3375448