Created
January 5, 2020 08:28
-
-
Save minghigh/8d3af5a3a08de763e541c1df1d6a7fc7 to your computer and use it in GitHub Desktop.
Python for running full text search with pymongo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding: utf-8 -*- | |
| import pymongo | |
| # mongodb config | |
| MONGODB_SERVER = 'localhost' | |
| MONGODB_PORT = 27017 | |
| MONGODB_DB = 'database' | |
| MONGODB_COLLECTION = 'collection' | |
| connection = pymongo.MongoClient(MONGODB_SERVER, MONGODB_PORT) | |
| database = connection[MONGODB_DB] | |
| collection = database[MONGODB_COLLECTION] | |
| # `title` is the index to be created | |
| collection.create_index([('title', 'text')]) | |
| print('Index Created!') | |
| search_string = "python" | |
| cursor = collection.find({"$text": {"$search": search_string}}, {'score': {'$meta': 'textScore'}}) | |
| cursor.sort([('score', {'$meta': 'textScore'})]) | |
| for item in cursor: | |
| print(item) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment