Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you pass weights for a text search to create_index in PyMongo?

I have an automated process that creates a text index on various fields in a Mongo instance (current Mongo 2.6 / PyMongo 2.72).

from pymongo import MongoClient, TEXT
db = MongoClient()
collection = db.collection

collection.create_index([("foo",TEXT), ("bar",TEXT), ("baz",TEXT)])

I want to weight the collection according to the Mongo docs. In the Mongo shell, this would be:

db.collection.create_index( { foo: text, bar: text, baz: text}, {weights: {foo: 10, bar: 5, baz 1}})

However, since I'm doing this in Python and not the Mongo shell. Does PyMongo support this?

like image 236
psvann Avatar asked Feb 08 '23 12:02

psvann


1 Answers

In Python (PyMongo 2.4.2 and newer), the index declaration looks like:

collection.create_index(
    [
        ('foo', TEXT),
        ('bar', TEXT),
        ('baz', TEXT)
    ],
    weights={
        'foo': 10,
        'bar': 5,
        'baz': 1
    }
)
like image 57
chridam Avatar answered Feb 11 '23 03:02

chridam