Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyMongo sort with metadata

I wondering how to convert the follow mongodb query to pymongo syntax

db.articles.find(
   { $text: { $search: "cake" } },
   { score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } ).limit(3)

I tried this:

results = \
    mongo.db.products.find({ '$text': { '$search': 'cake' } }, { 'score': { '$meta': 'textScore' } }) \
        .sort({ 'score': { '$meta': 'textScore' } }) \
        .limit(3)

But I got the follow error on sort:

raise TypeError("second item in each key pair must be 1, -1, "
TypeError: second item in each key pair must be 1, -1, '2d', 'geoHaystack', or another valid MongoDB index specifier.

Anyone can help me? Thanks in advance

like image 389
Rodrigo Avatar asked May 15 '14 22:05

Rodrigo


1 Answers

I think that the solution is here: https://github.com/mongodb/mongo-python-driver/blob/master/pymongo/cursor.py#L658 . To add list of (key, direction) for new approach with "new" feature '$text':

    Beginning with MongoDB version 2.6, text search results can be
    sorted by relevance::

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

        # Sort by 'score' field.
        cursor.sort([('score', {'$meta': 'textScore'})]) #<<<< HERE
like image 73
horacioibrahim Avatar answered Oct 01 '22 22:10

horacioibrahim