Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting with MongoDB full text search

Tags:

mongodb

I am looking for a way to sort results by value of a field while performing a full text search with mongodb 2.4.

My text search command looks something like this:

db.books.runCommand( "text", { search: "science" } )

What I would like to do is something like:

db.books.runCommand( "text", { search: "science", "sort": "rating" } )

I can see in the documentation that a limit parameter exists, but not something to sort results by other than the default sort by relevance score.

Re sorting the results is probably going to be inefficient. What is a good way to get this done?

like image 591
user2338229 Avatar asked May 01 '13 03:05

user2338229


1 Answers

Had the same problem, managed to solve the problem (pymongo) by using instead of the runCommand stuff the '$meta' operator:

# create text index
db.collection.ensure_index([("textField", "text")], name = "Text_search_index")    
# query     
queryDict = { "$text": { "$search": ""science"}}    
# cursor
cursor = db.collection.find(queryDict, {'score': {'$meta': 'textScore'}, "_id":1}).sort([('score', {'$meta': 'textScore'})]).limit(limit_value)

Looks like this is available only from 2.6 version at least in pymongo

Also in Mongo shell this equivalent to :

db.collection.ensureIndex({"textField":"text"})    
queryDict = { "$text": { "$search": "science"}}    
db.collection.find(queryDict, {'score': {'$meta': 'textScore'}}).sort({'score': {'$met
a': 'textScore'}}).limit(100)
like image 162
scoulomb Avatar answered Sep 25 '22 20:09

scoulomb