Skip to content

Instantly share code, notes, and snippets.

@cpatrick
Last active October 3, 2021 15:18
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cpatrick/5719077 to your computer and use it in GitHub Desktop.
Save cpatrick/5719077 to your computer and use it in GitHub Desktop.
Sample Python for running a full-text search using PyMongo
from pymongo import Connection
if __name__ == '__main__':
# Connect to mongo
conn = Connection()
db = conn['canepi']
# Set the search term
term = 'foo'
# Run the search
results = db.command('text', 'healthmap', search=term)
# Print the results
print(results)
@alexeyproskuryakov
Copy link

What about mongo 3.x version?
I have this: pymongo.errors.OperationFailure: command SON([('text', '...'), ('search', '...')]) on namespace ....$cmd failed: no such command: text

@nod
Copy link

nod commented Feb 3, 2016

For pymongo against mongodb 3.2...

Given a collection of documents like

{'textfield': 'cool stuff in a doc',  'other': 'fields...'}

To perform the query, and get results sorted by the textual score:

db.my_collection.create_index([('textfield','text')])

cursor = db.my_collection.find(
    {'textfield': 'some string query'},
    {'_txtscr': {'$meta': 'textScore'}
).sort([('_txtscr', {'$meta':'textScore'})])

@legel
Copy link

legel commented Feb 5, 2016

@nod that only searches for an exact string match with the entire text, and not substrings as the $text command specifies.

I just explored for 3.2 and this should work:

import pymongo

client = pymongo.MongoClient()
db = client['some_db']
collection = db["some_collection"]

collection.insert({"textfield": "cool stuff in a doc"})
collection.create_index([('textfield', 'text')])

search_this_string = "stuff"
print collection.find({"$text": {"$search": search_this_string}}).count()

@ptmminh
Copy link

ptmminh commented Jul 7, 2016

thanks @legel! Super helpful!

@linzino7
Copy link

linzino7 commented Apr 9, 2018

thanks @legel!

@alperozaydin
Copy link

Awesome @legel!

@saamkhya
Copy link

how to do multiple text search, for eg: search for word1 and word2 together in the text sentence?

@niazangels
Copy link

@saamkhya
I ended up with the following for scoring the documents with multiple words:

cursor = collection.find(
            {'$text': {'$search': 'some words'}},
            {'score': {'$meta': 'textScore'}})

        # Sort by 'score' field.
        cursor.sort([('score', {'$meta': 'textScore'})])

Make sure you index the collection first.

Source: https://github.com/mongodb/mongo-python-driver/blob/master/pymongo/cursor.py#L658

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment