Skip to content

Instantly share code, notes, and snippets.

@minghigh
Created January 5, 2020 08:28
Show Gist options
  • Select an option

  • Save minghigh/8d3af5a3a08de763e541c1df1d6a7fc7 to your computer and use it in GitHub Desktop.

Select an option

Save minghigh/8d3af5a3a08de763e541c1df1d6a7fc7 to your computer and use it in GitHub Desktop.
Python for running full text search with pymongo
# -*- 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